@tinycloud/web-sdk 3.14.0-beta.8 → 3.16.0

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.
@@ -1,2 +1,2 @@
1
1
  /*! For license information please see delegations-issued.mjs.LICENSE.txt */
2
- var e,t,r={4290(e){var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(i,{DecryptTransportResponseError:()=>a}),e.exports=(e=>((e,i,a,o)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let a of n(i))s.call(e,a)||void 0===a||t(e,a,{get:()=>i[a],enumerable:!(o=r(i,a))||o.enumerable});return e})(t({},"__esModule",{value:!0}),e))(i);var a=class extends Error{constructor(e,t,r){super("Node decrypt request failed"),this.status=e,this.permissionHint=t,this.notFoundMessage=r,this.name="DecryptTransportResponseError"}}}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var i=n[e]={exports:{}};return r[e](i,i.exports,s),i.exports}s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),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]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},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}(e||(e={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(t||(t={}));const i=e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),a=e=>{switch(typeof e){case"undefined":return i.undefined;case"string":return i.string;case"number":return Number.isNaN(e)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":return Array.isArray(e)?i.array:null===e?i.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?i.promise:"undefined"!=typeof Map&&e instanceof Map?i.map:"undefined"!=typeof Set&&e instanceof Set?i.set:"undefined"!=typeof Date&&e instanceof Date?i.date:i.object;default:return i.unknown}},o=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 c 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:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){const r=s.path[n];n===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof c))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={},r=[];for(const n of this.issues)if(n.path.length>0){const r=n.path[0];t[r]=t[r]||[],t[r].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}c.create=e=>new c(e);const u=(t,r)=>{let n;switch(t.code){case o.invalid_type:n=t.received===i.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case o.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,e.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:n=`Unrecognized key(s) in object: ${e.joinValues(t.keys,", ")}`;break;case o.invalid_union:n="Invalid input";break;case o.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${e.joinValues(t.options)}`;break;case o.invalid_enum_value:n=`Invalid enum value. Expected ${e.joinValues(t.options)}, received '${t.received}'`;break;case o.invalid_arguments:n="Invalid function arguments";break;case o.invalid_return_type:n="Invalid function return type";break;case o.invalid_date:n="Invalid date";break;case o.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:e.assertNever(t.validation):n="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case o.too_small:n="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 o.too_big:n="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 o.custom:n="Invalid input";break;case o.invalid_intersection_types:n="Intersection results could not be merged";break;case o.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case o.not_finite:n="Number must be finite";break;default:n=r.defaultError,e.assertNever(t)}return{message:n}};let d=u;var l;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(l||(l={}));function h(e,t){const r=d,n=(e=>{const{data:t,path:r,errorMaps:n,issueData:s}=e,i=[...r,...s.path||[]],a={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...s,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===u?void 0:u].filter(e=>!!e)});e.common.issues.push(n)}class f{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 n of t){if("aborted"===n.status)return p;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return f.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return p;if("aborted"===s.status)return p;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const p=Object.freeze({status:"aborted"}),y=e=>({status:"dirty",value:e}),g=e=>({status:"valid",value:e}),m=e=>"aborted"===e.status,v=e=>"dirty"===e.status,_=e=>"valid"===e.status,k=e=>"undefined"!=typeof Promise&&e instanceof Promise;class w{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}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 E=(e,t)=>{if(_(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 c(e.common.issues);return this._error=t,this._error}}};function b(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??n??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:i??r??s.defaultError}},description:s}}class T{get description(){return this._def.description}_getType(e){return a(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new f,ctx:{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(k(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:a(e)},n=this._parseSync({data:e,path:r.path,parent:r});return E(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return _(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=>_(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:a(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(k(n)?n:Promise.resolve(n));return E(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const s=e(t),i=()=>n.addIssue({code:o.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(i(),!1)):!!s||(i(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new xe({schema:this,typeName:Ce.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 Oe.create(this,this._def)}nullable(){return Re.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oe.create(this)}promise(){return Te.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return pe.create(this,e,this._def)}transform(e){return new xe({...b(this._def),schema:this,typeName:Ce.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ne({...b(this._def),innerType:this,defaultValue:t,typeName:Ce.ZodDefault})}brand(){return new Se({typeName:Ce.ZodBranded,type:this,...b(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ae({...b(this._def),innerType:this,catchValue:t,typeName:Ce.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return De.create(this,e)}readonly(){return Ue.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const x=/^c[^\s-]{8,}$/i,O=/^[0-9a-z]+$/,R=/^[0-9A-HJKMNP-TV-Z]{26}$/i,N=/^[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,A=/^[a-z0-9_-]{21}$/i,I=/^[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)?)??$/,D=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let U;const P=/^(?:(?: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])$/,C=/^(([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]))$/,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]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,B=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,V="((\\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])))",q=new RegExp(`^${V}$`);function F(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(`^${F(e)}$`)}function j(e){let t=`${V}T${F(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 H(e,t){return!("v4"!==t&&t||!P.test(e))||!("v6"!==t&&t||!C.test(e))}function Z(e,t){if(!I.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function W(e,t){return!("v4"!==t&&t||!L.test(e))||!("v6"!==t&&t||!K.test(e))}class z extends T{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==i.string){const e=this._getOrReturnCtx(t);return h(e,{code:o.invalid_type,expected:i.string,received:e.parsedType}),p}const r=new f;let n;for(const s of this._def.checks)if("min"===s.kind)t.data.length<s.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:o.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if("max"===s.kind)t.data.length>s.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:o.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if("length"===s.kind){const e=t.data.length>s.value,i=t.data.length<s.value;(e||i)&&(n=this._getOrReturnCtx(t,n),e?h(n,{code:o.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&h(n,{code:o.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if("email"===s.kind)D.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"email",code:o.invalid_string,message:s.message}),r.dirty());else if("emoji"===s.kind)U||(U=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),U.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"emoji",code:o.invalid_string,message:s.message}),r.dirty());else if("uuid"===s.kind)N.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"uuid",code:o.invalid_string,message:s.message}),r.dirty());else if("nanoid"===s.kind)A.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"nanoid",code:o.invalid_string,message:s.message}),r.dirty());else if("cuid"===s.kind)x.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"cuid",code:o.invalid_string,message:s.message}),r.dirty());else if("cuid2"===s.kind)O.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"cuid2",code:o.invalid_string,message:s.message}),r.dirty());else if("ulid"===s.kind)R.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"ulid",code:o.invalid_string,message:s.message}),r.dirty());else if("url"===s.kind)try{new URL(t.data)}catch{n=this._getOrReturnCtx(t,n),h(n,{validation:"url",code:o.invalid_string,message:s.message}),r.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"regex",code:o.invalid_string,message:s.message}),r.dirty())):"trim"===s.kind?t.data=t.data.trim():"includes"===s.kind?t.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):"toLowerCase"===s.kind?t.data=t.data.toLowerCase():"toUpperCase"===s.kind?t.data=t.data.toUpperCase():"startsWith"===s.kind?t.data.startsWith(s.value)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):"endsWith"===s.kind?t.data.endsWith(s.value)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):"datetime"===s.kind?j(s).test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:"datetime",message:s.message}),r.dirty()):"date"===s.kind?q.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:"date",message:s.message}),r.dirty()):"time"===s.kind?M(s).test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:"time",message:s.message}),r.dirty()):"duration"===s.kind?S.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"duration",code:o.invalid_string,message:s.message}),r.dirty()):"ip"===s.kind?H(t.data,s.version)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"ip",code:o.invalid_string,message:s.message}),r.dirty()):"jwt"===s.kind?Z(t.data,s.alg)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"jwt",code:o.invalid_string,message:s.message}),r.dirty()):"cidr"===s.kind?W(t.data,s.version)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"cidr",code:o.invalid_string,message:s.message}),r.dirty()):"base64"===s.kind?B.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"base64",code:o.invalid_string,message:s.message}),r.dirty()):"base64url"===s.kind?$.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"base64url",code:o.invalid_string,message:s.message}),r.dirty()):e.assertNever(s);return{status:r.value,value:t.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:o.invalid_string,...l.errToObj(r)})}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...l.errToObj(e)})}url(e){return this._addCheck({kind:"url",...l.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...l.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...l.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...l.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...l.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...l.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...l.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...l.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...l.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...l.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...l.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...l.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,...l.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,...l.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...l.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...l.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...l.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...l.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...l.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...l.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...l.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...l.errToObj(t)})}nonempty(e){return this.min(1,l.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 G(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}z.create=e=>new z({checks:[],typeName:Ce.ZodString,coerce:e?.coerce??!1,...b(e)});class J extends T{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)!==i.number){const e=this._getOrReturnCtx(t);return h(e,{code:o.invalid_type,expected:i.number,received:e.parsedType}),p}let r;const n=new f;for(const s of this._def.checks)"int"===s.kind?e.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),h(r,{code:o.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):"min"===s.kind?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"multipleOf"===s.kind?0!==G(t.data,s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):"finite"===s.kind?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),h(r,{code:o.not_finite,message:s.message}),n.dirty()):e.assertNever(s);return{status:n.value,value:t.data}}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,n){return new J({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(n)}]})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:l.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:l.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.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 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)}}J.create=e=>new J({checks:[],typeName:Ce.ZodNumber,coerce:e?.coerce||!1,...b(e)});class Y extends T{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)!==i.bigint)return this._getInvalidInput(t);let r;const n=new f;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"multipleOf"===s.kind?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):e.assertNever(s);return{status:n.value,value:t.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,n){return new Y({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(n)}]})}_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:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.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:Ce.ZodBigInt,coerce:e?.coerce??!1,...b(e)});class Q extends T{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==i.boolean){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.boolean,received:t.parsedType}),p}return g(e.data)}}Q.create=e=>new Q({typeName:Ce.ZodBoolean,coerce:e?.coerce||!1,...b(e)});class X extends T{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==i.date){const e=this._getOrReturnCtx(t);return h(e,{code:o.invalid_type,expected:i.date,received:e.parsedType}),p}if(Number.isNaN(t.data.getTime()))return h(this._getOrReturnCtx(t),{code:o.invalid_date}),p;const r=new f;let n;for(const s of this._def.checks)"min"===s.kind?t.data.getTime()<s.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:o.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):"max"===s.kind?t.data.getTime()>s.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:o.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):e.assertNever(s);return{status:r.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:l.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:l.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:Ce.ZodDate,...b(e)});class ee extends T{_parse(e){if(this._getType(e)!==i.symbol){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.symbol,received:t.parsedType}),p}return g(e.data)}}ee.create=e=>new ee({typeName:Ce.ZodSymbol,...b(e)});class te extends T{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.undefined,received:t.parsedType}),p}return g(e.data)}}te.create=e=>new te({typeName:Ce.ZodUndefined,...b(e)});class re extends T{_parse(e){if(this._getType(e)!==i.null){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.null,received:t.parsedType}),p}return g(e.data)}}re.create=e=>new re({typeName:Ce.ZodNull,...b(e)});class ne extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return g(e.data)}}ne.create=e=>new ne({typeName:Ce.ZodAny,...b(e)});class se extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return g(e.data)}}se.create=e=>new se({typeName:Ce.ZodUnknown,...b(e)});class ie extends T{_parse(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.never,received:t.parsedType}),p}}ie.create=e=>new ie({typeName:Ce.ZodNever,...b(e)});class ae extends T{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.void,received:t.parsedType}),p}return g(e.data)}}ae.create=e=>new ae({typeName:Ce.ZodVoid,...b(e)});class oe extends T{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==i.array)return h(t,{code:o.invalid_type,expected:i.array,received:t.parsedType}),p;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(h(t,{code:e?o.too_big:o.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(h(t,{code:o.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(h(t,{code:o.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new w(t,e,t.path,r)))).then(e=>f.mergeArray(r,e));const s=[...t.data].map((e,r)=>n.type._parseSync(new w(t,e,t.path,r)));return f.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new oe({...this._def,minLength:{value:e,message:l.toString(t)}})}max(e,t){return new oe({...this._def,maxLength:{value:e,message:l.toString(t)}})}length(e,t){return new oe({...this._def,exactLength:{value:e,message:l.toString(t)}})}nonempty(e){return this.min(1,e)}}function ce(e){if(e instanceof ue){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Oe.create(ce(n))}return new ue({...e._def,shape:()=>t})}return e instanceof oe?new oe({...e._def,type:ce(e.element)}):e instanceof Oe?Oe.create(ce(e.unwrap())):e instanceof Re?Re.create(ce(e.unwrap())):e instanceof ye?ye.create(e.items.map(e=>ce(e))):e}oe.create=(e,t)=>new oe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ce.ZodArray,...b(t)});class ue extends T{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(),r=e.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(e){if(this._getType(e)!==i.object){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),p}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ie&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||a.push(e);const c=[];for(const e of s){const t=n[e],s=r.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new w(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ie){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)c.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(h(r,{code:o.unrecognized_keys,keys:a}),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 a){const n=r.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new w(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of c){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>f.mergeObjectSync(t,e)):f.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return l.errToObj,new ue({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:l.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new ue({...this._def,unknownKeys:"strip"})}passthrough(){return new ue({...this._def,unknownKeys:"passthrough"})}extend(e){return new ue({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ue({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ce.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ue({...this._def,catchall:e})}pick(t){const r={};for(const n of e.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ue({...this._def,shape:()=>r})}omit(t){const r={};for(const n of e.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new ue({...this._def,shape:()=>r})}deepPartial(){return ce(this)}partial(t){const r={};for(const n of e.objectKeys(this.shape)){const e=this.shape[n];t&&!t[n]?r[n]=e:r[n]=e.optional()}return new ue({...this._def,shape:()=>r})}required(t){const r={};for(const n of e.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof Oe;)e=e._def.innerType;r[n]=e}return new ue({...this._def,shape:()=>r})}keyof(){return we(e.objectKeys(this.shape))}}ue.create=(e,t)=>new ue({shape:()=>e,unknownKeys:"strip",catchall:ie.create(),typeName:Ce.ZodObject,...b(t)}),ue.strictCreate=(e,t)=>new ue({shape:()=>e,unknownKeys:"strict",catchall:ie.create(),typeName:Ce.ZodObject,...b(t)}),ue.lazycreate=(e,t)=>new ue({shape:e,unknownKeys:"strip",catchall:ie.create(),typeName:Ce.ZodObject,...b(t)});class de extends T{_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 c(e.ctx.common.issues));return h(t,{code:o.invalid_union,unionErrors:r}),p});{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=s._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&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map(e=>new c(e));return h(t,{code:o.invalid_union,unionErrors:s}),p}}get options(){return this._def.options}}de.create=(e,t)=>new de({options:e,typeName:Ce.ZodUnion,...b(t)});const le=t=>t instanceof _e?le(t.schema):t instanceof xe?le(t.innerType()):t instanceof ke?[t.value]:t instanceof Ee?t.options:t instanceof be?e.objectValues(t.enum):t instanceof Ne?le(t._def.innerType):t instanceof te?[void 0]:t instanceof re?[null]:t instanceof Oe?[void 0,...le(t.unwrap())]:t instanceof Re?[null,...le(t.unwrap())]:t instanceof Se||t instanceof Ue?le(t.unwrap()):t instanceof Ae?le(t._def.innerType):[];class he extends T{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.object)return h(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),p;const r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),p)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=le(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 s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new he({typeName:Ce.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...b(r)})}}function fe(t,r){const n=a(t),s=a(r);if(t===r)return{valid:!0,data:t};if(n===i.object&&s===i.object){const n=e.objectKeys(r),s=e.objectKeys(t).filter(e=>-1!==n.indexOf(e)),i={...t,...r};for(const e of s){const n=fe(t[e],r[e]);if(!n.valid)return{valid:!1};i[e]=n.data}return{valid:!0,data:i}}if(n===i.array&&s===i.array){if(t.length!==r.length)return{valid:!1};const e=[];for(let n=0;n<t.length;n++){const s=fe(t[n],r[n]);if(!s.valid)return{valid:!1};e.push(s.data)}return{valid:!0,data:e}}return n===i.date&&s===i.date&&+t===+r?{valid:!0,data:t}:{valid:!1}}class pe extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(m(e)||m(n))return p;const s=fe(e.value,n.value);return s.valid?((v(e)||v(n))&&t.dirty(),{status:t.value,value:s.data}):(h(r,{code:o.invalid_intersection_types}),p)};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])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pe.create=(e,t,r)=>new pe({left:e,right:t,typeName:Ce.ZodIntersection,...b(r)});class ye extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.array)return h(r,{code:o.invalid_type,expected:i.array,received:r.parsedType}),p;if(r.data.length<this._def.items.length)return h(r,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&r.data.length>this._def.items.length&&(h(r,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new w(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>f.mergeArray(t,e)):f.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ye({...this._def,rest:e})}}ye.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ye({items:e,typeName:Ce.ZodTuple,rest:null,...b(t)})};class ge extends T{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!==i.object)return h(r,{code:o.invalid_type,expected:i.object,received:r.parsedType}),p;const n=[],s=this._def.keyType,a=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new w(r,e,r.path,e)),value:a._parse(new w(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?f.mergeObjectAsync(t,n):f.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ge(t instanceof T?{keyType:e,valueType:t,typeName:Ce.ZodRecord,...b(r)}:{keyType:z.create(),valueType:e,typeName:Ce.ZodRecord,...b(t)})}}class me extends T{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!==i.map)return h(r,{code:o.invalid_type,expected:i.map,received:r.parsedType}),p;const n=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([e,t],i)=>({key:n._parse(new w(r,e,r.path,[i,"key"])),value:s._parse(new w(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of a){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return p;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of a){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return p;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}me.create=(e,t,r)=>new me({valueType:t,keyType:e,typeName:Ce.ZodMap,...b(r)});class ve extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.set)return h(r,{code:o.invalid_type,expected:i.set,received:r.parsedType}),p;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(h(r,{code:o.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(h(r,{code:o.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function a(e){const r=new Set;for(const n of e){if("aborted"===n.status)return p;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const c=[...r.data.values()].map((e,t)=>s._parse(new w(r,e,r.path,t)));return r.common.async?Promise.all(c).then(e=>a(e)):a(c)}min(e,t){return new ve({...this._def,minSize:{value:e,message:l.toString(t)}})}max(e,t){return new ve({...this._def,maxSize:{value:e,message:l.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ve.create=(e,t)=>new ve({valueType:e,minSize:null,maxSize:null,typeName:Ce.ZodSet,...b(t)});class _e extends T{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:Ce.ZodLazy,...b(t)});class ke extends T{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}function we(e,t){return new Ee({values:e,typeName:Ce.ZodEnum,...b(t)})}ke.create=(e,t)=>new ke({value:e,typeName:Ce.ZodLiteral,...b(t)});class Ee extends T{_parse(t){if("string"!=typeof t.data){const r=this._getOrReturnCtx(t),n=this._def.values;return h(r,{expected:e.joinValues(n),received:r.parsedType,code:o.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const e=this._getOrReturnCtx(t),r=this._def.values;return h(e,{received:e.data,code:o.invalid_enum_value,options:r}),p}return g(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 Ee.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ee.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ee.create=we;class be extends T{_parse(t){const r=e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==i.string&&n.parsedType!==i.number){const t=e.objectValues(r);return h(n,{expected:e.joinValues(t),received:n.parsedType,code:o.invalid_type}),p}if(this._cache||(this._cache=new Set(e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const t=e.objectValues(r);return h(n,{received:n.data,code:o.invalid_enum_value,options:t}),p}return g(t.data)}get enum(){return this._def.values}}be.create=(e,t)=>new be({values:e,typeName:Ce.ZodNativeEnum,...b(t)});class Te extends T{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.promise&&!1===t.common.async)return h(t,{code:o.invalid_type,expected:i.promise,received:t.parsedType}),p;const r=t.parsedType===i.promise?t.data:Promise.resolve(t.data);return g(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Te.create=(e,t)=>new Te({type:e,typeName:Ce.ZodPromise,...b(t)});class xe extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ce.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:e=>{h(n,e),e.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===s.type){const e=s.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===r.value)return p;const t=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?y(t.value):t});{if("aborted"===r.value)return p;const t=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?y(t.value):t}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,i);if(n.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===n.common.async){const t=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(t=>"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value).then(()=>({status:r.value,value:t.value}))))}if("transform"===s.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!_(e))return p;const t=s.transform(e.value,i);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>_(e)?Promise.resolve(s.transform(e.value,i)).then(e=>({status:r.value,value:e})):p)}e.assertNever(s)}}xe.create=(e,t,r)=>new xe({schema:e,typeName:Ce.ZodEffects,effect:t,...b(r)}),xe.createWithPreprocess=(e,t,r)=>new xe({schema:t,effect:{type:"preprocess",transform:e},typeName:Ce.ZodEffects,...b(r)});class Oe extends T{_parse(e){return this._getType(e)===i.undefined?g(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Oe.create=(e,t)=>new Oe({innerType:e,typeName:Ce.ZodOptional,...b(t)});class Re extends T{_parse(e){return this._getType(e)===i.null?g(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:Ce.ZodNullable,...b(t)});class Ne extends T{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===i.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ne.create=(e,t)=>new Ne({innerType:e,typeName:Ce.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...b(t)});class Ae extends T{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return k(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Ce.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...b(t)});class Ie extends T{_parse(e){if(this._getType(e)!==i.nan){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.nan,received:t.parsedType}),p}return{status:"valid",value:e.data}}}Ie.create=e=>new Ie({typeName:Ce.ZodNaN,...b(e)}),Symbol("zod_brand");class Se extends T{_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 De extends T{_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?p:"dirty"===e.status?(t.dirty(),y(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?p:"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 De({in:e,out:t,typeName:Ce.ZodPipeline})}}class Ue extends T{_parse(e){const t=this._def.innerType._parse(e),r=e=>(_(e)&&(e.value=Object.freeze(e.value)),e);return k(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Pe(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((n,s)=>{const i=e(n);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Pe(t,n),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Pe(t,n),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}}):ne.create()}var Ce;Ue.create=(e,t)=>new Ue({innerType:e,typeName:Ce.ZodReadonly,...b(t)}),ue.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"}(Ce||(Ce={}));const Ke=z.create,Be=J.create,$e=(Ie.create,Y.create,Q.create),Ve=(X.create,ee.create,te.create,re.create,ne.create,se.create),qe=(ie.create,ae.create,oe.create),Fe=ue.create,Me=(ue.strictCreate,de.create,he.create),je=(pe.create,ye.create,ge.create),He=(me.create,ve.create,_e.create,ke.create),Ze=Ee.create,We=(be.create,Te.create,xe.create,Oe.create,Re.create,xe.createWithPreprocess,De.create,e=>X.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 Ge(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function Je(e){return e.slice(10,e.indexOf("/"))}function Ye(e){return e.slice(e.indexOf("/")+1)}function Qe(e){const t={};for(const r of ze)Je(r.urn)===e&&(t[Ge(Ye(r.urn))]=r.urn);return t}var Xe=Qe("kv"),et={...Qe("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},tt={...Qe("duckdb"),DESCRIBE:"tinycloud.duckdb/describe",EXECUTE:"tinycloud.duckdb/execute"},rt=Qe("capabilities"),nt=(Qe("hooks"),Qe("encryption")),st=Qe("space"),it=ze;["tinychat-4jq","share-2fz","tinycloud-secrets","openkey-tinycloud-demo"].map(e=>new RegExp(`^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)?${e}\\.pages\\.dev$`));var at="applications",ot="account",ct="applications/",ut="secrets",dt="default",lt="public",ht="agents",ft="tinycloud.encryption",pt=nt.NETWORK_CREATE,yt=[dt,at,ot,ut,lt,ht],gt={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:dt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:dt,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:dt,path:"",actions:["read","write"]}]},mt={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:at,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:at,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:at,path:"",actions:["read","write"]}]},vt={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ot,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ot,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ot,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ot,path:"account",actions:["read","write","schema"]}]},_t={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:ut,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:ut,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:ut,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:ut,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:ut,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:ut,path:"",actions:["read"],skipPrefix:!0}]},kt={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:lt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:lt,path:"",actions:["get","list","metadata"]}]},wt={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:ht,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ht,path:"",actions:["get","put","del","list","metadata"]}]},Et={[dt]:gt,[at]:mt,[ot]:vt,[ut]:_t,[lt]:kt,[ht]:wt};function bt(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Tt(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 xt(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,n="read"===r||"get"===r?Xe.GET:"write"===r||"put"===r?Xe.PUT:"delete"===r||"del"===r?Xe.DEL:"list"===r?Xe.LIST:"metadata"===r?Xe.METADATA:void 0;if(void 0===n)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const s=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${s}`,actions:[n],skipPrefix:!0}})}(e).flatMap(e=>xt(e,t,r));const n=!0===e.skipPrefix||e.service===ft;return[{service:e.service,space:e.service===ft?"encryption":e.space??r,path:Tt(t,e.path,n),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 Ot(e){const t=new Set(e.filter(e=>e.service!==ft).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}`,n=t.get(e);if(n)for(const e of r.actions)n.actions.includes(e)||n.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:[rt.READ]}))])}function Rt(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,n=e.map(bt),s=n.flatMap(e=>{const t=e.prefix??e.app_id,r=e.space??at;return(e.permissions??[]).flatMap(e=>xt(e,t,r))});r&&s.push(...Nt.map(e=>({...e,actions:[...e.actions]})));const i=new Map;for(const e of n){const t=i.get(e.app_id)??[];t.push(bt(e)),i.set(e.app_id,t)}return{manifests:n,resources:Ot(s),delegationTargets:[],registryRecords:r?[...i.entries()].map(([e,t])=>({key:`${ct}${e}`,app_id:e,manifests:t})):[],expiryMs:6048e5,includePublicSpace:n.some(e=>e.includePublicSpace??!0)}}([Et[e]],{includeAccountRegistryPermissions:!1})}yt.map(e=>({name:e,manifest:Et[e],persistedAsApplication:e===ut}));var Nt=Object.freeze([{service:"tinycloud.kv",space:ot,path:ct,actions:[Xe.GET,Xe.PUT,Xe.LIST]},{service:"tinycloud.kv",space:ot,path:"spaces/",actions:[Xe.GET,Xe.PUT,Xe.LIST]},{service:"tinycloud.kv",space:ot,path:"system/bootstrap/complete",actions:[Xe.GET,Xe.PUT]},{service:"tinycloud.delegation",space:ot,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ot,path:"account",actions:[et.READ,et.WRITE,et.SCHEMA]},{service:"tinycloud.capabilities",space:ot,path:"",actions:[rt.READ]}]),At=Rt(dt),It={...At,resources:[...At.resources,...Nt.map(e=>({...e,actions:[...e.actions]}))]},St=Object.freeze(Object.fromEntries(yt.map(e=>[e,e===dt?It:Rt(e)]))),Dt=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[pt]}]);function Ut(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Pt(e,...t){if(!Ut(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Lt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ct(e,t){Pt(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Kt(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Bt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function $t(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}Object.freeze(yt.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:St[e].resources,...e===ot?{rawAbilities:Dt}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[st.HOST]}]));const Vt=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function qt(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Ut(e))throw new Error("Uint8Array expected, got "+typeof e);e=Ht(e)}return e}const Ft=(e,t)=>{function r(r,...n){if(Pt(r),!Vt)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?Pt(t):Pt(t,e.nonceLength)}const s=e.tagLength;s&&void 0!==n[1]&&Pt(n[1]);const i=t(r,...n),a=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Pt(t)}};let o=!1;return{encrypt(e,t){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Pt(e),a(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(Pt(e),s&&e.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(r,e),r};function Mt(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),a=Number(r>>s&i),o=Number(r&i),c=n?4:0,u=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+u,o,n)}function jt(e){return e.byteOffset%4==0}function Ht(e){return Uint8Array.from(e)}const Zt=16,Wt=new Uint8Array(16),zt=Kt(Wt),Gt=(e,t,r,n)=>({s3:r<<31|n>>>1,s2:t<<31|r>>>1,s1:e<<31|t>>>1,s0:e>>>1^225<<24&-(1&n)}),Jt=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Yt{constructor(e,t){this.blockLen=Zt,this.outputLen=Zt,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,Pt(e=qt(e),16);const r=$t(e);let n=r.getUint32(0,!1),s=r.getUint32(4,!1),i=r.getUint32(8,!1),a=r.getUint32(12,!1);const o=[];for(let e=0;e<128;e++)o.push({s0:Jt(n),s1:Jt(s),s2:Jt(i),s3:Jt(a)}),({s0:n,s1:s,s2:i,s3:a}=Gt(n,s,i,a));const c=(u=t||1024)>65536?8:u>1024?4:2;var u;if(![1,2,4,8].includes(c))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=c;const d=128/c,l=this.windowSize=2**c,h=[];for(let e=0;e<d;e++)for(let t=0;t<l;t++){let r=0,n=0,s=0,i=0;for(let a=0;a<c;a++){if(!(t>>>c-a-1&1))continue;const{s0:u,s1:d,s2:l,s3:h}=o[c*e+a];r^=u,n^=d,s^=l,i^=h}h.push({s0:r,s1:n,s2:s,s3:i})}this.t=h}_updateBlock(e,t,r,n){e^=this.s0,t^=this.s1,r^=this.s2,n^=this.s3;const{W:s,t:i,windowSize:a}=this;let o=0,c=0,u=0,d=0;const l=(1<<s)-1;let h=0;for(const f of[e,t,r,n])for(let e=0;e<4;e++){const t=f>>>8*e&255;for(let e=8/s-1;e>=0;e--){const r=t>>>s*e&l,{s0:n,s1:f,s2:p,s3:y}=i[h*a+r];o^=n,c^=f,u^=p,d^=y,h+=1}}this.s0=o,this.s1=c,this.s2=u,this.s3=d}update(e){Lt(this),Pt(e=qt(e));const t=Kt(e),r=Math.floor(e.length/Zt),n=e.length%Zt;for(let e=0;e<r;e++)this._updateBlock(t[4*e+0],t[4*e+1],t[4*e+2],t[4*e+3]);return n&&(Wt.set(e.subarray(r*Zt)),this._updateBlock(zt[0],zt[1],zt[2],zt[3]),Bt(zt)),this}destroy(){const{t:e}=this;for(const t of e)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(e){Lt(this),Ct(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:s}=this,i=Kt(e);return i[0]=t,i[1]=r,i[2]=n,i[3]=s,e}digest(){const e=new Uint8Array(Zt);return this.digestInto(e),this.destroy(),e}}class Qt extends Yt{constructor(e,t){Pt(e=qt(e));const r=function(e){e.reverse();const t=1&e[15];let r=0;for(let t=0;t<e.length;t++){const n=e[t];e[t]=n>>>1|r,r=(1&n)<<7}return e[0]^=225&-t,e}(Ht(e));super(r,t),Bt(r)}update(e){e=qt(e),Lt(this);const t=Kt(e),r=e.length%Zt,n=Math.floor(e.length/Zt);for(let e=0;e<n;e++)this._updateBlock(Jt(t[4*e+3]),Jt(t[4*e+2]),Jt(t[4*e+1]),Jt(t[4*e+0]));return r&&(Wt.set(e.subarray(n*Zt)),this._updateBlock(Jt(zt[3]),Jt(zt[2]),Jt(zt[1]),Jt(zt[0])),Bt(zt)),this}digestInto(e){Lt(this),Ct(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:s}=this,i=Kt(e);return i[0]=t,i[1]=r,i[2]=n,i[3]=s,e.reverse()}}function Xt(e){const t=(t,r)=>e(r,t.length).update(qt(t)).digest(),r=e(new Uint8Array(16),0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(t,r)=>e(t,r),t}const er=Xt((e,t)=>new Yt(e,t)),tr=(Xt((e,t)=>new Qt(e,t)),16),rr=new Uint8Array(tr);function nr(e){return e<<1^283&-(e>>7)}function sr(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=nr(e);return r}const ir=e=>e<<24|e>>>8,ar=e=>e<<8|e>>>24;function or(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const r=new Uint32Array(256).map((r,n)=>t(e[n])),n=r.map(ar),s=n.map(ar),i=s.map(ar),a=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let u=0;u<256;u++){const d=256*t+u;a[d]=r[t]^n[u],o[d]=s[t]^i[u],c[d]=e[t]<<8|e[u]}return{sbox:e,sbox2:c,T0:r,T1:n,T2:s,T3:i,T01:a,T23:o}}const cr=or((()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=nr(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=255&(n^n>>4^n>>5^n>>6^n>>7^99)}return Bt(e),t})(),e=>sr(e,3)<<24|e<<16|e<<8|sr(e,2)),ur=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=nr(r))e[t]=r;return e})();function dr(e,t,r,n,s,i){return e[r<<8&65280|n>>>8&255]^t[s>>>8&65280|i>>>24&255]}function lr(e,t,r,n,s){return e[255&t|65280&r]|e[n>>>16&255|s>>>16&65280]<<16}function hr(e,t,r,n,s){const{sbox2:i,T01:a,T23:o}=cr;let c=0;t^=e[c++],r^=e[c++],n^=e[c++],s^=e[c++];const u=e.length/4-2;for(let i=0;i<u;i++){const i=e[c++]^dr(a,o,t,r,n,s),u=e[c++]^dr(a,o,r,n,s,t),d=e[c++]^dr(a,o,n,s,t,r),l=e[c++]^dr(a,o,s,t,r,n);t=i,r=u,n=d,s=l}return{s0:e[c++]^lr(i,t,r,n,s),s1:e[c++]^lr(i,r,n,s,t),s2:e[c++]^lr(i,n,s,t,r),s3:e[c++]^lr(i,s,t,r,n)}}function fr(e,t,r,n,s){Pt(r,tr),Pt(n),s=function(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!jt(t))throw new Error("invalid output, must be aligned");return t}(n.length,s);const i=r,a=Kt(i),o=$t(i),c=Kt(n),u=Kt(s),d=t?0:12,l=n.length;let h=o.getUint32(d,t),{s0:f,s1:p,s2:y,s3:g}=hr(e,a[0],a[1],a[2],a[3]);for(let r=0;r+4<=c.length;r+=4)u[r+0]=c[r+0]^f,u[r+1]=c[r+1]^p,u[r+2]=c[r+2]^y,u[r+3]=c[r+3]^g,h=h+1>>>0,o.setUint32(d,h,t),({s0:f,s1:p,s2:y,s3:g}=hr(e,a[0],a[1],a[2],a[3]));const m=tr*Math.floor(c.length/4);if(m<l){const e=new Uint32Array([f,p,y,g]),t=(v=e,new Uint8Array(v.buffer,v.byteOffset,v.byteLength));for(let e=m,r=0;e<l;e++,r++)s[e]=n[e]^t[r];Bt(e)}var v;return s}function pr(e,t,r,n,s){const i=s?s.length:0,a=e.create(r,n.length+i);s&&a.update(s);const o=function(e,t,r){!function(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}(r);const n=new Uint8Array(16),s=$t(n);return Mt(s,0,BigInt(t),r),Mt(s,8,BigInt(e),r),n}(8*n.length,8*i,t);a.update(n),a.update(o);const c=a.digest();return Bt(o),c}const yr=Ft({blockSize:16,nonceLength:12,tagLength:16,varSizeNonce:!0},function(e,t,r){if(t.length<8)throw new Error("aes/gcm: invalid nonce length");function n(e,t,n){const s=pr(er,!1,e,n,r);for(let e=0;e<t.length;e++)s[e]^=t[e];return s}function s(){const r=function(e){Pt(e);const t=e.length;if(![16,24,32].includes(t))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+t);const{sbox2:r}=cr,n=[];jt(e)||n.push(e=Ht(e));const s=Kt(e),i=s.length,a=e=>lr(r,e,e,e,e),o=new Uint32Array(t+28);o.set(s);for(let e=i;e<o.length;e++){let t=o[e-1];e%i===0?t=a(ir(t))^ur[e/i-1]:i>6&&e%i===4&&(t=a(t)),o[e]=o[e-i]^t}return Bt(...n),o}(e),n=rr.slice(),s=rr.slice();if(fr(r,!1,s,s,n),12===t.length)s.set(t);else{const e=rr.slice();Mt($t(e),8,BigInt(8*t.length),!1);const r=er.create(n).update(t).update(e);r.digestInto(s),r.destroy()}return{xk:r,authKey:n,counter:s,tagMask:fr(r,!1,s,rr)}}return{encrypt(e){const{xk:t,authKey:r,counter:i,tagMask:a}=s(),o=new Uint8Array(e.length+16),c=[t,r,i,a];jt(e)||c.push(e=Ht(e)),fr(t,!1,i,e,o.subarray(0,e.length));const u=n(r,a,o.subarray(0,o.length-16));return c.push(u),o.set(u,e.length),Bt(...c),o},decrypt(e){const{xk:t,authKey:r,counter:i,tagMask:a}=s(),o=[t,r,a,i];jt(e)||o.push(e=Ht(e));const c=e.subarray(0,-16),u=e.subarray(-16),d=n(r,a,c);if(o.push(d),!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(d,u))throw new Error("aes/gcm: invalid ghash tag");const l=fr(t,!1,i,c);return Bt(...o),l}}}),gr=()=>"undefined"!=typeof globalThis&&globalThis.crypto?globalThis.crypto:"undefined"!=typeof window&&window.crypto?window.crypto:"undefined"!=typeof self&&self.crypto?self.crypto:void 0,mr={web:gr(),node:void 0,getRandomValues:function(e){const t=gr();if(t&&t.getRandomValues)return t.getRandomValues(e);throw new Error("crypto.getRandomValues is unavailable")}};function vr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function _r(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function kr(e,...t){if(!vr(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function wr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");_r(e.outputLen),_r(e.blockLen)}function Er(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function br(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Tr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function xr(e,t){return e<<32-t|e>>>t}const Or=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Rr=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Nr(e){if(kr(e),Or)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Rr[e[r]];return t}function Ar(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Ir(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Or)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=Ar(e.charCodeAt(s)),i=Ar(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}function Sr(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Dr(e){return"string"==typeof e&&(e=Sr(e)),kr(e),e}function Ur(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];kr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}class Pr{}function Lr(e){const t=t=>e().update(Dr(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Cr(e=32){if(mr&&"function"==typeof mr.getRandomValues)return mr.getRandomValues(new Uint8Array(e));if(mr&&"function"==typeof mr.randomBytes)return Uint8Array.from(mr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Kr(e,t,r){return e&t^~e&r}function Br(e,t,r){return e&t^e&r^t&r}class $r extends Pr{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Tr(this.buffer)}update(e){Er(this),kr(e=Dr(e));const{view:t,buffer:r,blockLen:n}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(n-this.pos,s-i);if(a===n){const t=Tr(e);for(;n<=s-i;i+=n)this.process(t,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Er(this),function(e,t){kr(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:s}=this;let{pos:i}=this;t[i++]=128,br(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),a=Number(r>>s&i),o=Number(r&i),c=n?4:0,u=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+u,o,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const a=Tr(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)a.setUint32(4*e,u[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=n,e.pos=a,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Vr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Fr=BigInt(2**32-1),Mr=BigInt(32);function jr(e,t=!1){return t?{h:Number(e&Fr),l:Number(e>>Mr&Fr)}:{h:0|Number(e>>Mr&Fr),l:0|Number(e&Fr)}}const Hr=(e,t,r)=>e>>>r,Zr=(e,t,r)=>e<<32-r|t>>>r,Wr=(e,t,r)=>e>>>r|t<<32-r,zr=(e,t,r)=>e<<32-r|t>>>r,Gr=(e,t,r)=>e<<64-r|t>>>r-32,Jr=(e,t,r)=>e>>>r-32|t<<64-r;function Yr(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}}const Qr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Xr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,en=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),tn=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,rn=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),nn=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,sn=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),an=new Uint32Array(64);class on extends $r{constructor(e=32){super(64,e,8,!1),this.A=0|Vr[0],this.B=0|Vr[1],this.C=0|Vr[2],this.D=0|Vr[3],this.E=0|Vr[4],this.F=0|Vr[5],this.G=0|Vr[6],this.H=0|Vr[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:i,G:a,H:o}=this;return[e,t,r,n,s,i,a,o]}set(e,t,r,n,s,i,a,o){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|i,this.G=0|a,this.H=0|o}process(e,t){for(let r=0;r<16;r++,t+=4)an[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=an[e-15],r=an[e-2],n=xr(t,7)^xr(t,18)^t>>>3,s=xr(r,17)^xr(r,19)^r>>>10;an[e]=s+an[e-7]+n+an[e-16]|0}let{A:r,B:n,C:s,D:i,E:a,F:o,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(xr(a,6)^xr(a,11)^xr(a,25))+Kr(a,o,c)+sn[e]+an[e]|0,d=(xr(r,2)^xr(r,13)^xr(r,22))+Br(r,n,s)|0;u=c,c=o,o=a,a=i+t|0,i=s,s=n,n=r,r=t+d|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,i,a,o,c,u)}roundClean(){br(an)}destroy(){this.set(0,0,0,0,0,0,0,0),br(this.buffer)}}const cn=(()=>function(e,t=!1){const r=e.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:r,l:a}=jr(e[i],t);[n[i],s[i]]=[r,a]}return[n,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),un=(()=>cn[0])(),dn=(()=>cn[1])(),ln=new Uint32Array(80),hn=new Uint32Array(80);class fn extends $r{constructor(e=64){super(128,e,16,!1),this.Ah=0|qr[0],this.Al=0|qr[1],this.Bh=0|qr[2],this.Bl=0|qr[3],this.Ch=0|qr[4],this.Cl=0|qr[5],this.Dh=0|qr[6],this.Dl=0|qr[7],this.Eh=0|qr[8],this.El=0|qr[9],this.Fh=0|qr[10],this.Fl=0|qr[11],this.Gh=0|qr[12],this.Gl=0|qr[13],this.Hh=0|qr[14],this.Hl=0|qr[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:i,Dh:a,Dl:o,Eh:c,El:u,Fh:d,Fl:l,Gh:h,Gl:f,Hh:p,Hl:y}=this;return[e,t,r,n,s,i,a,o,c,u,d,l,h,f,p,y]}set(e,t,r,n,s,i,a,o,c,u,d,l,h,f,p,y){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|i,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|u,this.Fh=0|d,this.Fl=0|l,this.Gh=0|h,this.Gl=0|f,this.Hh=0|p,this.Hl=0|y}process(e,t){for(let r=0;r<16;r++,t+=4)ln[r]=e.getUint32(t),hn[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ln[e-15],r=0|hn[e-15],n=Wr(t,r,1)^Wr(t,r,8)^Hr(t,0,7),s=zr(t,r,1)^zr(t,r,8)^Zr(t,r,7),i=0|ln[e-2],a=0|hn[e-2],o=Wr(i,a,19)^Gr(i,a,61)^Hr(i,0,6),c=zr(i,a,19)^Jr(i,a,61)^Zr(i,a,6),u=en(s,c,hn[e-7],hn[e-16]),d=tn(u,n,o,ln[e-7],ln[e-16]);ln[e]=0|d,hn[e]=0|u}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:a,Cl:o,Dh:c,Dl:u,Eh:d,El:l,Fh:h,Fl:f,Gh:p,Gl:y,Hh:g,Hl:m}=this;for(let e=0;e<80;e++){const t=Wr(d,l,14)^Wr(d,l,18)^Gr(d,l,41),v=zr(d,l,14)^zr(d,l,18)^Jr(d,l,41),_=d&h^~d&p,k=rn(m,v,l&f^~l&y,dn[e],hn[e]),w=nn(k,g,t,_,un[e],ln[e]),E=0|k,b=Wr(r,n,28)^Gr(r,n,34)^Gr(r,n,39),T=zr(r,n,28)^Jr(r,n,34)^Jr(r,n,39),x=r&s^r&a^s&a,O=n&i^n&o^i&o;g=0|p,m=0|y,p=0|h,y=0|f,h=0|d,f=0|l,({h:d,l}=Yr(0|c,0|u,0|w,0|E)),c=0|a,u=0|o,a=0|s,o=0|i,s=0|r,i=0|n;const R=Qr(E,T,O);r=Xr(R,w,b,x),n=0|R}({h:r,l:n}=Yr(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=Yr(0|this.Bh,0|this.Bl,0|s,0|i)),({h:a,l:o}=Yr(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=Yr(0|this.Dh,0|this.Dl,0|c,0|u)),({h:d,l}=Yr(0|this.Eh,0|this.El,0|d,0|l)),({h,l:f}=Yr(0|this.Fh,0|this.Fl,0|h,0|f)),({h:p,l:y}=Yr(0|this.Gh,0|this.Gl,0|p,0|y)),({h:g,l:m}=Yr(0|this.Hh,0|this.Hl,0|g,0|m)),this.set(r,n,s,i,a,o,c,u,d,l,h,f,p,y,g,m)}roundClean(){br(ln,hn)}destroy(){br(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const pn=Lr(()=>new on),yn=Lr(()=>new fn),gn=BigInt(0),mn=BigInt(1);function vn(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function _n(e,t,r=""){const n=vr(e),s=e?.length,i=void 0!==t;if(!n||i&&s!==t)throw new Error((r&&`"${r}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(n?`length=${s}`:"type="+typeof e));return e}function kn(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?gn:BigInt("0x"+e)}function wn(e){return kr(e),kn(Nr(Uint8Array.from(e).reverse()))}function En(e,t){return Ir(e.toString(16).padStart(2*t,"0"))}function bn(e,t){return En(e,t).reverse()}function Tn(e,t,r){let n;if("string"==typeof t)try{n=Ir(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!vr(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const s=n.length;if("number"==typeof r&&s!==r)throw new Error(e+" of length "+r+" expected, got "+s);return n}function xn(e){return Uint8Array.from(e)}const On=e=>"bigint"==typeof e&&gn<=e;function Rn(e,t,r,n){if(!function(e,t,r){return On(e)&&On(t)&&On(r)&&t<=e&&e<r}(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}const Nn=e=>(mn<<BigInt(e))-mn;function An(e,t,r={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function n(t,r,n){const s=e[t];if(n&&void 0===s)return;const i=typeof s;if(i!==r||null===s)throw new Error(`param "${t}" is invalid: expected ${r}, got ${i}`)}Object.entries(t).forEach(([e,t])=>n(e,t,!1)),Object.entries(r).forEach(([e,t])=>n(e,t,!0))}const In=()=>{throw new Error("not implemented")};function Sn(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(void 0!==s)return s;const i=e(r,...n);return t.set(r,i),i}}const Dn=BigInt(0),Un=BigInt(1),Pn=BigInt(2),Ln=BigInt(3),Cn=BigInt(4),Kn=BigInt(5),Bn=BigInt(7),$n=BigInt(8),Vn=BigInt(9),qn=BigInt(16);function Fn(e,t){const r=e%t;return r>=Dn?r:t+r}function Mn(e,t,r){let n=e;for(;t-- >Dn;)n*=n,n%=r;return n}function jn(e,t){if(e===Dn)throw new Error("invert: expected non-zero number");if(t<=Dn)throw new Error("invert: expected positive modulus, got "+t);let r=Fn(e,t),n=t,s=Dn,i=Un,a=Un,o=Dn;for(;r!==Dn;){const e=n/r,t=n%r,c=s-a*e,u=i-o*e;n=r,r=t,s=a,i=o,a=c,o=u}if(n!==Un)throw new Error("invert: does not exist");return Fn(s,t)}function Hn(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Zn(e,t){const r=(e.ORDER+Un)/Cn,n=e.pow(t,r);return Hn(e,n,t),n}function Wn(e,t){const r=(e.ORDER-Kn)/$n,n=e.mul(t,Pn),s=e.pow(n,r),i=e.mul(t,s),a=e.mul(e.mul(i,Pn),s),o=e.mul(i,e.sub(a,e.ONE));return Hn(e,o,t),o}function zn(e){if(e<Ln)throw new Error("sqrt is not defined for small field");let t=e-Un,r=0;for(;t%Pn===Dn;)t/=Pn,r++;let n=Pn;const s=Xn(e);for(;1===Qn(s,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Zn;let i=s.pow(n,t);const a=(t+Un)/Pn;return function(e,n){if(e.is0(n))return n;if(1!==Qn(e,n))throw new Error("Cannot find square root");let s=r,o=e.mul(e.ONE,i),c=e.pow(n,t),u=e.pow(n,a);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,r=e.sqr(c);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===s)throw new Error("Cannot find square root");const n=Un<<BigInt(s-t-1),i=e.pow(o,n);s=t,o=e.sqr(i),c=e.mul(c,o),u=e.mul(u,i)}return u}}const Gn=(e,t)=>(Fn(e,t)&Un)===Un,Jn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yn(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce((t,r,s)=>e.is0(r)?t:(n[s]=t,e.mul(t,r)),e.ONE),i=e.inv(s);return t.reduceRight((t,r,s)=>e.is0(r)?t:(n[s]=e.mul(t,n[s]),e.mul(t,r)),i),n}function Qn(e,t){const r=(e.ORDER-Un)/Pn,n=e.pow(t,r),s=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),a=e.eql(n,e.neg(e.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Xn(e,t,r=!1,n={}){if(e<=Dn)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,i,a,o=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modFromBytes&&(o=e.modFromBytes),a=e.allowedLengths}else"number"==typeof t&&(s=t),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:u}=function(e,t){void 0!==t&&_r(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}(e,s);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const l=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:Nn(c),ZERO:Dn,ONE:Un,allowedLengths:a,create:t=>Fn(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Dn<=t&&t<e},is0:e=>e===Dn,isValidNot0:e=>!l.is0(e)&&l.isValid(e),isOdd:e=>(e&Un)===Un,neg:t=>Fn(-t,e),eql:(e,t)=>e===t,sqr:t=>Fn(t*t,e),add:(t,r)=>Fn(t+r,e),sub:(t,r)=>Fn(t-r,e),mul:(t,r)=>Fn(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Dn)throw new Error("invalid exponent, negatives unsupported");if(r===Dn)return e.ONE;if(r===Un)return t;let n=e.ONE,s=t;for(;r>Dn;)r&Un&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Un;return n}(l,e,t),div:(t,r)=>Fn(t*jn(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>jn(t,e),sqrt:i||(t=>{return d||(d=(r=e)%Cn===Ln?Zn:r%$n===Kn?Wn:r%qn===Vn?function(e){const t=Xn(e),r=zn(e),n=r(t,t.neg(t.ONE)),s=r(t,n),i=r(t,t.neg(n)),a=(e+Bn)/qn;return(e,t)=>{let r=e.pow(t,a),o=e.mul(r,n);const c=e.mul(r,s),u=e.mul(r,i),d=e.eql(e.sqr(o),t),l=e.eql(e.sqr(c),t);r=e.cmov(r,o,d),o=e.cmov(u,c,l);const h=e.eql(e.sqr(o),t),f=e.cmov(r,o,h);return Hn(e,f,t),f}}(r):zn(r)),d(l,t);var r}),toBytes:e=>r?bn(e,u):En(e,u),fromBytes:(t,n=!0)=>{if(a){if(!a.includes(t.length)||t.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+t.length);const e=new Uint8Array(u);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+t.length);let s=r?wn(t):function(e){return kn(Nr(e))}(t);if(o&&(s=Fn(s,e)),!n&&!l.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Yn(l,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(l)}const es=BigInt(0),ts=BigInt(1);function rs(e,t){const r=t.negate();return e?r:t}function ns(e,t){const r=Yn(e.Fp,t.map(e=>e.Z));return t.map((t,n)=>e.fromAffine(t.toAffine(r[n])))}function ss(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function is(e,t){ss(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Nn(e),maxNumber:r,shiftBy:BigInt(e)}}function as(e,t,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:a}=r;let o=Number(e&s),c=e>>a;o>n&&(o-=i,c+=ts);const u=t*n;return{nextN:c,offset:u+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:t%2!=0,offsetF:u}}const os=new WeakMap,cs=new WeakMap;function us(e){return cs.get(e)||1}function ds(e){if(e!==es)throw new Error("invalid wNAF")}class ls{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>es;)t&ts&&(r=r.add(n)),n=n.double(),t>>=ts;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=is(t,this.bits),s=[];let i=e,a=i;for(let e=0;e<r;e++){a=i,s.push(a);for(let e=1;e<n;e++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,s=this.BASE;const i=is(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:d,offsetF:l}=as(r,e,i);r=a,c?s=s.add(rs(d,t[l])):n=n.add(rs(u,t[o]))}return ds(r),{p:n,f:s}}wNAFUnsafe(e,t,r,n=this.ZERO){const s=is(e,this.bits);for(let e=0;e<s.windows&&r!==es;e++){const{nextN:i,offset:a,isZero:o,isNeg:c}=as(r,e,s);if(r=i,!o){const e=t[a];n=n.add(c?e.negate():e)}}return ds(r),n}getPrecomputes(e,t,r){let n=os.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),os.set(t,n))),n}cached(e,t,r){const n=us(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const s=us(e);return 1===s?this._unsafeLadder(e,t,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),t,n)}createCache(e,t){ss(t,this.bits),cs.set(e,t),os.delete(e)}hasCache(e){return 1!==us(e)}}function hs(e,t,r,n){(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)})})(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)})}(n,t);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const a=e.ZERO,o=function(e){let t;for(t=0;e>gn;e>>=mn,t+=1);return t}(BigInt(s));let c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);const u=Nn(c),d=new Array(Number(u)+1).fill(a);let l=a;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){d.fill(a);for(let t=0;t<i;t++){const s=n[t],i=Number(s>>BigInt(e)&u);d[i]=d[i].add(r[t])}let t=a;for(let e=d.length-1,r=a;e>0;e--)r=r.add(d[e]),t=t.add(r);if(l=l.add(t),0!==e)for(let e=0;e<c;e++)l=l.double()}return l}function fs(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){An(e,Jn.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Xn(e,{isLE:r})}const ps=BigInt(0),ys=BigInt(1),gs=BigInt(2),ms=BigInt(8);class vs{constructor(e){this.ep=e}static fromBytes(e){In()}static fromHex(e){In()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Nr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}}function _s(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:Xn(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(e,function(e,t,r={}){if("function"!=typeof t)throw new Error('"hash" function param is required');An(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:s,Fp:i,Fn:a}=e,o=r.randomBytes||Cr,c=r.adjustScalarBytes||(e=>e),u=r.domain||((e,t,r)=>{if(vn(r,"phflag"),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function d(e){return a.create(wn(e))}function l(e){const{head:r,prefix:n,scalar:i}=function(e){const r=g.secretKey;e=Tn("private key",e,r);const n=Tn("hashed private key",t(e),2*r),s=c(n.slice(0,r));return{head:s,prefix:n.slice(r,2*r),scalar:d(s)}}(e),a=s.multiply(i),o=a.toBytes();return{head:r,prefix:n,scalar:i,point:a,pointBytes:o}}function h(e){return l(e).pointBytes}function f(e=Uint8Array.of(),...r){const s=Ur(...r);return d(t(u(s,Tn("context",e),!!n)))}const p={zip215:!0},y=i.BYTES,g={secretKey:y,publicKey:y,signature:2*y,seed:y};function m(e=o(g.seed)){return _n(e,g.seed,"seed")}const v={getExtendedPublicKey:l,randomSecretKey:m,isValidSecretKey:function(e){return vr(e)&&e.length===a.BYTES},isValidPublicKey:function(t,r){try{return!!e.fromBytes(t,r)}catch(e){return!1}},toMontgomery(t){const{y:r}=e.fromBytes(t),n=g.publicKey,s=32===n;if(!s&&57!==n)throw new Error("only defined for 25519 and 448");const a=s?i.div(ys+r,ys-r):i.div(r-ys,r+ys);return i.toBytes(a)},toMontgomerySecret(e){const r=g.secretKey;_n(e,r);const n=t(e.subarray(0,r));return c(n).subarray(0,r)},randomPrivateKey:m,precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=v.randomSecretKey(e);return{secretKey:t,publicKey:h(t)}},getPublicKey:h,sign:function(e,t,r={}){e=Tn("message",e),n&&(e=n(e));const{prefix:i,scalar:o,pointBytes:c}=l(t),u=f(r.context,i,e),d=s.multiply(u).toBytes(),h=f(r.context,d,c,e),p=a.create(u+h*o);if(!a.isValid(p))throw new Error("sign failed: invalid s");return _n(Ur(d,a.toBytes(p)),g.signature,"result")},verify:function(t,r,i,a=p){const{context:o,zip215:c}=a,u=g.signature;t=Tn("signature",t,u),r=Tn("message",r),i=Tn("publicKey",i,g.publicKey),void 0!==c&&vn(c,"zip215"),n&&(r=n(r));const d=u/2,l=t.subarray(0,d),h=wn(t.subarray(d,u));let y,m,v;try{y=e.fromBytes(i,c),m=e.fromBytes(l,c),v=s.multiplyUnsafe(h)}catch(e){return!1}if(!c&&y.isSmallOrder())return!1;const _=f(o,m.toBytes(),y.toBytes(),r);return m.add(y.multiplyUnsafe(_)).subtract(v).clearCofactor().is0()},utils:v,Point:e,lengths:g})}(function(e,t={}){const r=function(e,t,r={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const r=t[e];if(!("bigint"==typeof r&&r>es))throw new Error(`CURVE.${e} must be positive bigint`)}const s=fs(t.p,r.Fp,n),i=fs(t.n,r.Fn,n),a=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of a)if(!s.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:s,Fn:i}}("edwards",e,t,t.FpFnLE),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:a}=i;An(t,{},{uvRatio:"function"});const o=gs<<BigInt(8*s.BYTES)-ys,c=e=>n.create(e),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:ps}}});if(!function(e,t,r,n){const s=e.sqr(r),i=e.sqr(n),a=e.add(e.mul(t.a,s),i),o=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(a,o)}(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(e,t,r=!1){return Rn("coordinate "+e,t,r?ys:ps,o),t}function l(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const h=Sn((e,t)=>{const{X:r,Y:s,Z:i}=e,a=e.is0();null==t&&(t=a?ms:n.inv(i));const o=c(r*t),u=c(s*t),d=n.mul(i,t);if(a)return{x:ps,y:ys};if(d!==ys)throw new Error("invZ was invalid");return{x:o,y:u}}),f=Sn(e=>{const{a:t,d:r}=i;if(e.is0())throw new Error("bad point: ZERO");const{X:n,Y:s,Z:a,T:o}=e,u=c(n*n),d=c(s*s),l=c(a*a),h=c(l*l),f=c(u*t);if(c(l*c(f+d))!==c(h+c(r*c(u*d))))throw new Error("bad point: equation left != right (1)");if(c(n*s)!==c(a*o))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(e,t,r,n){this.X=d("x",e),this.Y=d("y",t),this.Z=d("z",r,!0),this.T=d("t",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};return d("x",t),d("y",r),new p(t,r,ys,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:s,d:a}=i;e=xn(_n(e,r,"point")),vn(t,"zip215");const d=xn(e),l=e[r-1];d[r-1]=-129&l;const h=wn(d),f=t?o:n.ORDER;Rn("point.y",h,ps,f);const y=c(h*h),g=c(y-ys),m=c(a*y-s);let{isValid:v,value:_}=u(g,m);if(!v)throw new Error("bad point: invalid y coordinate");const k=(_&ys)===ys,w=!!(128&l);if(!t&&_===ps&&w)throw new Error("bad point: x=0 and x_0=1");return w!==k&&(_=c(-_)),p.fromAffine({x:_,y:h})}static fromHex(e,t=!1){return p.fromBytes(Tn("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return y.createCache(this,e),t||this.multiply(gs),this}assertValidity(){f(this)}equals(e){l(e);const{X:t,Y:r,Z:n}=this,{X:s,Y:i,Z:a}=e,o=c(t*a),u=c(s*n),d=c(r*a),h=c(i*n);return o===u&&d===h}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:r,Z:n}=this,s=c(t*t),a=c(r*r),o=c(gs*c(n*n)),u=c(e*s),d=t+r,l=c(c(d*d)-s-a),h=u+a,f=h-o,y=u-a,g=c(l*f),m=c(h*y),v=c(l*y),_=c(f*h);return new p(g,m,_,v)}add(e){l(e);const{a:t,d:r}=i,{X:n,Y:s,Z:a,T:o}=this,{X:u,Y:d,Z:h,T:f}=e,y=c(n*u),g=c(s*d),m=c(o*r*f),v=c(a*h),_=c((n+s)*(u+d)-y-g),k=v-m,w=v+m,E=c(g-t*y),b=c(_*k),T=c(w*E),x=c(_*E),O=c(k*w);return new p(b,T,O,x)}subtract(e){return this.add(e.negate())}multiply(e){if(!s.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:r}=y.cached(this,e,e=>ns(p,e));return ns(p,[t,r])[0]}multiplyUnsafe(e,t=p.ZERO){if(!s.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===ps?p.ZERO:this.is0()||e===ys?this:y.unsafe(this,e,e=>ns(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return y.unsafe(this,i.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return a===ys?this:this.multiplyUnsafe(a)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&ys?128:0,r}toHex(){return Nr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return ns(p,e)}static msm(e,t){return hs(p,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,ys,c(i.Gx*i.Gy)),p.ZERO=new p(ps,ys,ys,ps),p.Fp=n,p.Fn=s;const y=new ls(p,s.BITS);return p.BASE.precompute(8),p}(t,r),n,s))}Sr("HashToScalar-");const ks=BigInt(0),ws=BigInt(1),Es=BigInt(2);const bs=BigInt(0),Ts=BigInt(1),xs=BigInt(2),Os=BigInt(3),Rs=BigInt(5),Ns=BigInt(8),As=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Is=(()=>({p:As,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ns,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ss(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),i=As,a=e*e%i*e%i,o=Mn(a,xs,i)*a%i,c=Mn(o,Ts,i)*e%i,u=Mn(c,Rs,i)*c%i,d=Mn(u,t,i)*u%i,l=Mn(d,r,i)*d%i,h=Mn(l,n,i)*l%i,f=Mn(h,s,i)*h%i,p=Mn(f,s,i)*h%i,y=Mn(p,t,i)*u%i;return{pow_p_5_8:Mn(y,xs,i)*e%i,b2:a}}function Ds(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Us=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ps(e,t){const r=As,n=Fn(t*t*t,r),s=Fn(n*n*t,r);let i=Fn(e*n*Ss(e*s).pow_p_5_8,r);const a=Fn(t*i*i,r),o=i,c=Fn(i*Us,r),u=a===e,d=a===Fn(-e,r),l=a===Fn(-e*Us,r);return u&&(i=o),(d||l)&&(i=c),Gn(i,r)&&(i=Fn(-i,r)),{isValid:u||d,value:i}}const Ls=(()=>Xn(Is.p,{isLE:!0}))(),Cs=(()=>Xn(Is.n,{isLE:!0}))(),Ks=(()=>({...Is,Fp:Ls,hash:yn,adjustScalarBytes:Ds,uvRatio:Ps}))(),Bs=(()=>_s(Ks))(),$s=(()=>{const e=Ls.ORDER;return function(e){const t=(An(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r}));var r;const{P:n,type:s,adjustScalarBytes:i,powPminus2:a,randomBytes:o}=t,c="x25519"===s;if(!c&&"x448"!==s)throw new Error("invalid type");const u=o||Cr,d=c?255:448,l=c?32:56,h=c?BigInt(9):BigInt(5),f=c?BigInt(121665):BigInt(39081),p=c?Es**BigInt(254):Es**BigInt(447),y=c?BigInt(8)*Es**BigInt(251)-ws:BigInt(4)*Es**BigInt(445)-ws,g=p+y+ws,m=e=>Fn(e,n),v=_(h);function _(e){return bn(m(e),l)}function k(e,t){const r=function(e,t){Rn("u",e,ks,n),Rn("scalar",t,p,g);const r=t,s=e;let i=ws,o=ks,c=e,u=ws,l=ks;for(let e=BigInt(d-1);e>=ks;e--){const t=r>>e&ws;l^=t,({x_2:i,x_3:c}=E(l,i,c)),({x_2:o,x_3:u}=E(l,o,u)),l=t;const n=i+o,a=m(n*n),d=i-o,h=m(d*d),p=a-h,y=c+u,g=m((c-u)*n),v=m(y*d),_=g+v,k=g-v;c=m(_*_),u=m(s*m(k*k)),i=m(a*h),o=m(p*(a+m(f*p)))}({x_2:i,x_3:c}=E(l,i,c)),({x_2:o,x_3:u}=E(l,o,u));const h=a(o);return m(i*h)}(function(e){const t=Tn("u coordinate",e,l);return c&&(t[31]&=127),m(wn(t))}(t),function(e){return wn(i(Tn("scalar",e,l)))}(e));if(r===ks)throw new Error("invalid private or public key received");return _(r)}function w(e){return k(e,v)}function E(e,t,r){const n=m(e*(t-r));return{x_2:t=m(t-n),x_3:r=m(r+n)}}const b={secretKey:l,publicKey:l,seed:l},T=(e=u(l))=>(kr(e,b.seed),e);return{keygen:function(e){const t=T(e);return{secretKey:t,publicKey:w(t)}},getSharedSecret:(e,t)=>k(e,t),getPublicKey:e=>w(e),scalarMult:k,scalarMultBase:w,utils:{randomSecretKey:T,randomPrivateKey:T},GuBytes:v.slice(),lengths:b}}({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:r,b2:n}=Ss(t);return Fn(Mn(r,Os,e)*n,e)},adjustScalarBytes:Ds})})(),Vs=Us,qs=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Fs=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Ms=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),js=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Hs=e=>Ps(Ts,e),Zs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ws=e=>Bs.Point.Fp.create(wn(e)&Zs);function zs(e){const{d:t}=Is,r=As,n=e=>Ls.create(e),s=n(Vs*e*e),i=n((s+Ts)*Ms);let a=BigInt(-1);const o=n((a-t*s)*n(s+t));let{isValid:c,value:u}=Ps(i,o),d=n(u*e);Gn(d,r)||(d=n(-d)),c||(u=d),c||(a=s);const l=n(a*(s-Ts)*js-o),h=u*u,f=n((u+u)*o),p=n(l*qs),y=n(Ts-h),g=n(Ts+h);return new Bs.Point(n(f*g),n(y*p),n(p*g),n(f*y))}class Gs extends vs{constructor(e){super(e)}static fromAffine(e){return new Gs(Bs.Point.fromAffine(e))}assertSame(e){if(!(e instanceof Gs))throw new Error("RistrettoPoint expected")}init(e){return new Gs(e)}static hashToCurve(e){return function(e){kr(e,64);const t=zs(Ws(e.subarray(0,32))),r=zs(Ws(e.subarray(32,64)));return new Gs(t.add(r))}(Tn("ristrettoHash",e,64))}static fromBytes(e){kr(e,32);const{a:t,d:r}=Is,n=As,s=e=>Ls.create(e),i=Ws(e);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(Ls.toBytes(i),e)||Gn(i,n))throw new Error("invalid ristretto255 encoding 1");const a=s(i*i),o=s(Ts+t*a),c=s(Ts-t*a),u=s(o*o),d=s(c*c),l=s(t*r*u-d),{isValid:h,value:f}=Hs(s(l*d)),p=s(f*c),y=s(f*p*l);let g=s((i+i)*p);Gn(g,n)&&(g=s(-g));const m=s(o*y),v=s(g*m);if(!h||Gn(v,n)||m===bs)throw new Error("invalid ristretto255 encoding 2");return new Gs(new Bs.Point(g,m,Ts,v))}static fromHex(e){return Gs.fromBytes(Tn("ristrettoHex",e,32))}static msm(e,t){return hs(Gs,Bs.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep;const s=As,i=e=>Ls.create(e),a=i(i(r+t)*i(r-t)),o=i(e*t),c=i(o*o),{value:u}=Hs(i(a*c)),d=i(u*a),l=i(u*o),h=i(d*l*n);let f;if(Gn(n*h,s)){let r=i(t*Vs),n=i(e*Vs);e=r,t=n,f=i(d*Fs)}else f=l;Gn(e*h,s)&&(t=i(-t));let p=i((r-t)*f);return Gn(p,s)&&(p=i(-p)),Ls.toBytes(p)}equals(e){this.assertSame(e);const{X:t,Y:r}=this.ep,{X:n,Y:s}=e.ep,i=e=>Ls.create(e),a=i(t*s)===i(r*n),o=i(r*s)===i(t*n);return a||o}is0(){return this.equals(Gs.ZERO)}}Gs.BASE=(()=>new Gs(Bs.Point.BASE))(),Gs.ZERO=(()=>new Gs(Bs.Point.ZERO))(),Gs.Fp=(()=>Ls)(),Gs.Fn=(()=>Cs)();class Js extends Pr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,wr(e);const r=Dr(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),br(s)}update(e){return Er(this),this.iHash.update(e),this}digestInto(e){Er(this),kr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:i,outputLen:a}=this;return e.finished=n,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ys=(e,t,r)=>new Js(e,t).update(r).digest();Ys.create=(e,t)=>new Js(e,t);const Qs=Uint8Array.from([0]),Xs=Uint8Array.of(),ei=(e,t,r,n,s)=>function(e,t,r,n=32){wr(e),_r(n);const s=e.outputLen;if(n>255*s)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/s);void 0===r&&(r=Xs);const a=new Uint8Array(i*s),o=Ys.create(e,t),c=o._cloneInto(),u=new Uint8Array(o.outputLen);for(let e=0;e<i;e++)Qs[0]=e+1,c.update(0===e?Xs:u).update(r).update(Qs).digestInto(u),a.set(u,s*e),o._cloneInto(c);return o.destroy(),c.destroy(),br(u,Qs),a.slice(0,n)}(e,function(e,t,r){return wr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Ys(e,Dr(r),Dr(t))}(e,t,r),n,s),ti=pn;var ri=s(4290),ni={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"};function si(e){return{ok:!0,data:e}}function ii(e){return{ok:!1,error:e}}function ai(e,t,r,n){return{code:e,message:t,service:r,cause:n?.cause,meta:n?.meta}}var oi="[REDACTED]",ci=new Set(["duration","durationMs","endedAt","startedAt","status","timestamp","latencyMs","stalenessMs","count","changes","deleted","fetched","pages","lagMs","pendingCleared","partitions","remaining","expiryMs"]),ui=new Set(["authenticated","ok","persisted","purgePending"]),di={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 li(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function hi(e,t){try{return e[t]}catch{return oi}}function fi(e){if(null==e)return e;if("object"!=typeof e)return oi;try{if(function(e){try{return Array.isArray(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}catch{return!0}}(e))return oi;const t={};for(const r of ci){const n=li(hi(e,r));void 0!==n&&(t[r]=n)}for(const r of ui){const n=hi(e,r);"boolean"==typeof n&&(t[r]=n)}for(const[r,n]of Object.entries(di)){const s=hi(e,r);"string"==typeof s&&n.includes(s)&&(t[r]=s)}void 0!==hi(e,"url")&&(t.url=oi);const r=hi(e,"error");return void 0!==r&&(t.error=function(e){if("object"!=typeof e||null===e)return{};const t=li(hi(e,"status"));return void 0!==t&&t>=100&&t<=599?{status:t}:{}}(r)),t}catch{return oi}}var pi="TinyCloud_debug";function yi(){return globalThis}function gi(){const e=globalThis.performance?.now?.bind(globalThis.performance);return"function"==typeof e?e():Date.now()}function mi(e){return!0===e||"true"===e||"1"===e}function vi(){const e=globalThis.process;return e?.env?.[pi]}function _i(){if(yi().window===globalThis)try{return globalThis.localStorage}catch{return}}function ki(e){const t=_i();if(t)try{e?t.setItem(pi,"true"):t.removeItem(pi)}catch{}}var wi=new class{constructor(){this.enabled=mi(yi()[pi])||mi(function(){const e=_i();if(e)try{return e.getItem(pi)}catch{return}}())||mi(vi()),this.sequence=0,this.events=[],this.maxEvents=1e3}isEnabled(){return this.enabled||mi(yi()[pi])||mi(vi())}enable(e={}){this.enabled=!0,yi()[pi]=!0,!1!==e.persist&&ki(!0),this.log("debug.enabled",{persisted:!1!==e.persist})}disable(e={}){this.log("debug.disabled",{persisted:!1!==e.persist}),this.enabled=!1,yi()[pi]=!1,!1!==e.persist&&ki(!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=gi();return this.log(`${e}.start`,t),{stop:t=>{const n=gi();return this.record({event:`${e}.end`,data:t,durationMs:n-r,startedAt:r,endedAt:n,level:"debug",timestamp:Date.now(),timestampIso:(new Date).toISOString()})}}}async timeAsync(e,t,r){if(!this.isEnabled())return t();const n=this.startTimer(e,r);try{const e=await t();return n.stop({ok:!0}),e}catch(e){throw n.stop({ok:!1,error:e}),e}}time(e,t,r){if(!this.isEnabled())return t();const n=this.startTimer(e,r);try{const e=t();return n.stop({ok:!0}),e}catch(e){throw n.stop({ok:!1,error:e}),e}}record(e){const t={...e,...void 0===e.data?{}:{data:fi(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 Ei(e){return wi.enable(e),wi}function bi(e){return wi.disable(e),wi}function Ti(){return wi.getLogs()}function xi(){wi.clear()}!function(){const e=yi();e.TinyCloudDebug=wi,e.enableTinyCloudDebug=Ei,e.disableTinyCloudDebug=bi,e.getTinyCloudDebugLogs=Ti,e.clearTinyCloudDebugLogs=xi}();var Oi=Fe({code:Ke(),message:Ke(),service:Ke(),cause:Ve().optional(),meta:Fe({}).passthrough().optional()});function Ri(e,t=Oi){return Me("ok",[Fe({ok:He(!0),data:e}),Fe({ok:He(!1),error:t})])}Ri(Ve(),Oi);var Ni,Ai=Fe({etag:Ke().optional(),contentType:Ke().optional(),lastModified:Ke().optional(),contentLength:Be().optional()});function Ii(e){try{return JSON.parse(e)}catch{return{}}}function Si(e,t,r,n,s){return s.message?Ui(s.message):/<!doctype html/i.test(i=n)||/<html[\s>]/i.test(i)?524===r||/524\s*[:-]/i.test(n)||/a timeout occurred/i.test(n)?`${e} ${t} failed: upstream request timed out. Please retry.`:`${e} ${t} failed: upstream service returned an HTML error page (${r}).`:`${e} ${t} failed: ${r} - ${Ui(n)}`;var i}function Di(e,t,r){const n={status:e,statusText:t},s=Ui(r);return s&&(n.responseSnippet=s.slice(0,300)),n}function Ui(e){const t=e.replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,500)}...`:t}Ni=Ve(),Fe({data:Ni,headers:Ai}),Ri(Fe({keys:qe(Ke()),truncated:$e().optional(),nextCursor:Ke().optional()})),Fe({service:Ke(),action:Ke(),span:Ke().optional(),key:Ke().optional(),timestamp:Be()}),Fe({service:Ke(),action:Ke(),span:Ke().optional(),ok:$e(),duration:Be(),durationMs:Be().optional(),status:Be().optional()}),Fe({service:Ke(),span:Ke().optional(),error:Oi}),Fe({service:Ke(),attempt:Be().int().positive(),maxAttempts:Be().int().positive(),error:Oi}),Fe({span:Ke(),ok:$e(),durationMs:Be(),service:Ke().optional(),action:Ke().optional(),status:Be().optional(),error:Oi.optional()}),Fe({maxAttempts:Be().int().positive(),backoff:Ze(["none","linear","exponential"]),baseDelayMs:Be().nonnegative(),maxDelayMs:Be().nonnegative(),retryableErrors:qe(Ke()),maxTotalMs:Be().positive().optional()}),Fe({delegationHeader:Fe({Authorization:Ke()}),delegationCid:Ke(),spaceId:Ke(),verificationMethod:Ke(),jwk:Fe({}).passthrough()});var Pi="urn:tinycloud:encryption:",Li=/^[a-z0-9][a-z0-9-]*$/,Ci=/^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/,Ki=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Bi(e){if("string"!=typeof e||0===e.length)throw new Ki("networkId must be a non-empty string");if(!e.startsWith(Pi))throw new Ki(`networkId must start with ${Pi} (got ${JSON.stringify(e)})`);const t=e.slice(25),r=t.lastIndexOf(":");if(r<=0||r===t.length-1)throw new Ki(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const n=t.slice(0,r),s=t.slice(r+1);if(!n.startsWith("did:"))throw new Ki(`networkId ownerDid must be a DID (got ${JSON.stringify(n)})`);const i=n.split(":");if(i.length<3||i.some(e=>0===e.length))throw new Ki(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(n)})`);if(!Li.test(s))throw new Ki(`networkId name ${JSON.stringify(s)} must match ${Li.source}`);return{networkId:e,ownerDid:n,name:s}}function $i(e){const t=e.lastIndexOf(":"),r=e.slice(t+1),n=r.indexOf("/"),s=-1===n?r:r.slice(0,n),i=Bi(-1===n?e:`${e.slice(0,t+1)}${s}`);if(-1===n)return i;const a=r.slice(n+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 Ki(`encryption resource has an invalid keyPath (got ${JSON.stringify(e)})`);return{...i,keyPath:a}}function Vi(e){const t=e.match(Ci);return t?{chainId:t[1],address:t[2].toLowerCase()}:null}function qi(e,t){const r=Vi(e),n=Vi(t);return r&&n?r.chainId===n.chainId&&r.address===n.address:e===t}Error,Error,Error,Error;var Fi={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 Mi(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(Fi,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 ji(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 n="string"==typeof t.space?t.space:void 0;return{service:t.service,...void 0===n?{}:{space:n},path:t.path,actions:[t.actions[0]]}}function Hi(e){return{code:ni.AUTH_REQUIRED,message:"Authentication required. Please sign in first.",service:e}}function Zi(e,t,r,n){const s=n.trim(),[,i,a]=/^([a-z_]+)(?::\s*([a-z_]+):)?/.exec(s)??[];let o;if(503!==r.status||"sql_busy"!==i&&"unavailable_retryable"!==i&&"read_audit_busy"!==i)if(503===r.status&&"request_timeout"===i)o=ni.REQUEST_TIMEOUT;else{if(500!==r.status||"outcome_unknown"!==i)return;o=ni.OUTCOME_UNKNOWN}else o=ni.NODE_BUSY;const c=o!==ni.OUTCOME_UNKNOWN,u=r.headers.get("retry-after")?.trim();return ai(o,t,e,{meta:{...Di(r.status,r.statusText,n),retryable:c,..."sql_busy"===i&&a?{stage:a}:{},...c&&u&&/^\d{1,9}$/.test(u)?{retryAfterMs:1e3*Number(u)}:{}}})}var Wi=class extends Error{constructor(e){super(`Request timed out after ${e}ms.`),this.name="TimeoutError",this.timeoutMs=e}};function zi(e){return e instanceof Wi||e instanceof Error&&"TimeoutError"===e.name&&"number"==typeof e.timeoutMs}function Gi(e,t,r){return void 0===t?{code:ni.TIMEOUT,message:"Request timed out.",service:e,...void 0===r?{}:{cause:r}}:{code:ni.TIMEOUT,message:`Request timed out after ${t}ms.`,service:e,...void 0===r?{}:{cause:r},meta:{timeoutMs:t}}}function Ji(e){const t=e.match(/^Unauthorized Action:\s*(.+?)\s*\/\s*(tinycloud\.\S+)$/m);return t?{resource:t[1].trim(),action:t[2].trim()}:{}}var Yi=new Set(it.map(({urn:e})=>e).filter(e=>!e.endsWith("/*"))),Qi=new Set(it.map(({service:e})=>e.slice(10)));function Xi(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 Bi(e),!0}catch{return!1}}const n=function(e,t){if(0===e.length||e.length>1024||!Qi.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 n=r.findIndex((e,t)=>t>0&&Qi.has(e));if(n<1||r[n]!==t)return;if(r.slice(1,n).some(e=>0===e.length||"."===e||".."===e))return;const s=r.slice(n+1);return s.some(e=>"."===e||".."===e)||"kv"!==t&&(0===s.length||""===s[s.length-1])?void 0:{space:r.slice(0,n).join("/"),path:s.join("/")}}(e,t);return void 0!==n&&(!n.path.endsWith("/")||"kv"===t&&"tinycloud.kv/list"===r)&&(""!==n.path||"kv"===t&&"tinycloud.kv/list"===r)}function ea(e){const t=na(e);if("unauthenticated"!==t&&"forbidden"!==t)return;const r=new Set;let n=e;for(let e=0;e<ta&&"object"==typeof n&&null!==n&&!r.has(n);e+=1){r.add(n);const e=n,t=ra(e),s=e.meta;if((401===t||403===t||void 0===t&&e.code===ni.AUTH_UNAUTHORIZED)&&"object"==typeof s&&null!==s&&!Array.isArray(s)){const t=s,{resource:r,requiredAction:n}=t;if("string"==typeof n&&Yi.has(n)){const s=n.slice(10,n.indexOf("/")),i=void 0===e.service?t.service:e.service;if(Xi(r,s,n)&&(void 0===i||i===s||i===`tinycloud.${s}`))return{resource:r,requiredAction:n}}}n=e.cause}}var ta=8;function ra(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 na(e){const t=new Set;let r=!1,n=e;for(let e=0;e<ta&&"object"==typeof n&&null!==n&&!t.has(n);e+=1){t.add(n);const e=n,s=ra(e);if(401===s)return"unauthenticated";if(403===s)return"forbidden";if(void 0!==s)return"other";e.code===ni.AUTH_UNAUTHORIZED&&(r=!0),n=e.cause}return r?"forbidden":void 0}function sa(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 ia={storage_quota_exceeded:!0,storage_limit_reached:!0};function aa(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=0}function oa(e){if("object"!=typeof e||null===e)return;const{usedBytes:t,limitBytes:r}=e;return aa(t)&&aa(r)?{usedBytes:t,limitBytes:r}:void 0}function ca(e){let t;try{t=JSON.parse(e)}catch{return sa(e)}if("object"!=typeof t||null===t)return;const r=t,n="string"==typeof r.message?r.message:"",s=oa(r.space)??sa(n),i="string"==typeof r.error&&!0===ia[r.error];if(!s&&!i)return;const a={...s},o=oa(r.account);if(o){const e=r.account.plan;a.account="string"==typeof e&&""!==e?{...o,plan:e}:o}return a}function ua(e,t,r,n){const s={...r,...ca(n)};return 402===t?function(e,t,r){return{code:ni.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,s):function(e,t,r){return{code:ni.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,s)}function da(e,t,r=ni.NETWORK_ERROR){const n=Mi(t);return n?{...n,service:e}:t instanceof Error?zi(t)?Gi(e,t.timeoutMs,t):"AbortError"===t.name?function(e){return{code:ni.ABORTED,message:"Request was aborted.",service:e}}(e):"TimeoutError"===t.name||t.message.toLowerCase().includes("timeout")?Gi(e):{code:r,message:t.message,service:e,cause:t}:{code:r,message:String(t),service:e}}var la=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,n){const s=this.getServiceName(),i=Date.now()-r,a=this.spanName(e);this.emit("service.response",{service:s,action:e,span:a,ok:t,duration:i,durationMs:i,status:n}),this.emit("telemetry.span",{span:a,service:s,action:e,ok:t,durationMs:i,status:n})}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,...n}={}){const s=()=>{const e=t();return{method:"POST",...n,headers:Array.isArray(e)?[...e,...Object.entries(r??{})]:{...e,...r}}};return this.context.invokeWithRetry?this.context.invokeWithRetry(e,s):this.context.fetch(e,s())}createRequestSignal(e,t){const r=new AbortController,n=[];let s;const i=()=>{void 0!==s&&(clearTimeout(s),s=void 0);for(const e of n.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}),n.push(()=>e.removeEventListener("abort",t))}const u=t??this._config.timeout;return"number"==typeof u&&u>0&&u<=2147483647&&(s=setTimeout(()=>a(new Wi(u)),u)),o}async withTelemetry(e,t,r){const n=Date.now();this.emitRequest(e,t);try{const t=await r();return t.ok?this.emitResponse(e,!0,n):(this.emitResponse(e,!1,n),this.emitError(t.error,e)),t}catch(t){const r=da(this.getServiceName(),t);return this.emitResponse(e,!1,n),this.emitError(r,e),ii(r)}}},ha=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?si({...r.data,results:r.data.results.map((t,r)=>({...t,key:e[r]}))}):r}async put(e,t,r){const n=this.getFullKey(e);return this._kv.put(n,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 ii(ai(ni.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?si({...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?si({...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}`,n=`${this._prefix}${r}`;return new e(this._kv,n)}},fa="tinycloud.kv/get",pa="tinycloud.kv/put",ya="tinycloud.kv/list",ga="tinycloud.kv/del",ma="tinycloud.kv/metadata",va="tinycloud.kv/sync";function _a(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var ka=new TextEncoder,wa=/^(?:Invalid invocation: )?delegation-(?:(revoked): [A-Za-z0-9]+|(ancestor-revoked): ancestor=[A-Za-z0-9]+ invoked=[A-Za-z0-9]+)$/;function Ea(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function ba(e,t,r,n){if(413!==r)return;const s=n.split(":",1)[0].trim();let i;return i=s===`${e}_request_too_large`||s!==`${e}_response_too_large`&&["batch","executeStatement","import"].includes(t),i?`${e.toUpperCase()}_REQUEST_TOO_LARGE`:void 0}(class extends la{constructor(e={}){super(),this.readThrough=null,this.readThroughReady=null,this._config=e}setReadThroughReady(e){const t=()=>{"function"==typeof e&&(e=Promise.resolve().then(e));const r=()=>{this.readThroughReady===t&&(this.readThroughReady=null)};return e.then(r,r)};this.readThroughReady=t,"function"!=typeof e&&t()}get config(){return this._config}setReadThrough(e){this.readThrough=e}handleQuotaErrorResponse(e,t,r){if((402===e.status||413===e.status)&&(413!==e.status||ca(t)))return ii(ua("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)?ii(ai(ni.KV_NOT_FOUND,`KV ${e.status} - ${r}`,"kv",{meta:{status:e.status,statusText:e.statusText}})):ii(ai(ni.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,n,s){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"kv",e,t),{headers:s,body:r,signal:n})}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,n=new Uint8Array(r.byteLength);return n.set(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),new Blob([n],{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,n=!1){const s=globalThis.atob(e),i=Uint8Array.from(s,e=>e.charCodeAt(0));if(n)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 n=e.results;if(!Array.isArray(n)||n.length!==t.length)return;for(const e of n){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(n.every(e=>"string"==typeof e.key)){const e=new Map(n.map(e=>[e.key,e]));if(e.size!==n.length)return;const r=[];for(const n of t){const t=e.get(n);if(!t)return;r.push(t)}return r}if(n.some(e=>void 0!==e.key))return;const s=t.map((e,t)=>t).sort((e,r)=>function(e,t){const r=ka.encode(e),n=ka.encode(t),s=Math.min(r.length,n.length);for(let e=0;e<s;e++)if(r[e]!==n[e])return r[e]-n[e];return r.length-n.length}(t[e],t[r])),i=new Array(n.length);for(let e=0;e<s.length;e++)i[s[e]]=n[e];return i}async batchRead(e,t,r){if(!this.requireAuth())return ii(Hi("kv"));if(0===e.length)return si({results:[],count:0});if(e.length>100)return ii(ai(ni.INVALID_INPUT,"KV batch reads accept at most 100 keys","kv"));if(1===e.length){const n=e[0];return si({results:[{key:n,result:t===fa?await this.get(n,r):await this.head(n,r)}],count:1})}if(!this.context.invokeAny)return ii(ai(ni.INVALID_INPUT,"KV batch reads require SDK runtime support for multi-resource invocations","kv"));const n=t===fa?r:void 0;if(void 0!==n?.maxResponseBytes&&(!Number.isSafeInteger(n.maxResponseBytes)||n.maxResponseBytes<=0))return ii(ai(ni.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const s=e.map(e=>this.getFullPath(e,r?.prefix));if(new Set(s).size!==s.length)return ii(ai(ni.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!==n?.maxResponseBytes&&(r["x-tinycloud-max-response-bytes"]=String(n.maxResponseBytes));const a=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.session;return this.context.invokeAny(e,s.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,s,t):413===a.status?ii(ai(ni.KV_RESPONSE_TOO_LARGE,"A KV batch value exceeds the requested response limit","kv",{meta:{status:a.status,statusText:a.statusText}})):ii(ai(ni.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(),s,t===fa);if(!o)return ii(ai(ni.NETWORK_ERROR,"KV batch read response did not match the requested keys","kv"));const c=o.map((r,s)=>{if(!r.ok)return{key:e[s],result:ii(ai(r.error.code,r.error.message,"kv"))};const i=r.headers,a=t===ma?void 0:this.parseBatchValue(r.dataBase64,i,n?.raw,n?.binary);return{key:e[s],result:si({data:a,headers:this.createBatchResponseHeaders(i)})}});return si({results:c,count:c.length})}catch(e){return ii(da("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 n=e.headers.get("content-type");if(n?.includes("application/json"))return await e.json();if(n?.startsWith("text/"))return await e.text();const s=await e.text();if(s)try{return JSON.parse(s)}catch{return s}}async createSignedReadUrlError(e,t,r){let n=e.statusText;try{const t=await e.text();t&&(n=t)}catch{}return 401===e.status||403===e.status?this.authorizationFailure(`Failed to create signed read URL for key ${JSON.stringify(t)}`,e,n,[r],fa):ii(ai(400===e.status?ni.INVALID_INPUT:ni.NETWORK_ERROR,`Failed to create signed read URL for key ${JSON.stringify(t)}: ${e.status} - ${n}`,"kv",{meta:{status:e.status,statusText:e.statusText}}))}async readAuthorizationText(e){try{return await e.text()}catch{return""}}authorizationFailure(e,t,r,n,s,i={}){const{resource:a,action:o}=Ji(r),c=n.find(e=>a===e||a===`${this.context.session.spaceId}/kv/${e}`),u=void 0!==c&&o===s?ea({service:"kv",code:ni.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 ii((l=`${e}: ${t.status} - ${d}`,h={status:t.status,...i,...u},ai(ni.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("network"!==t?.source&&null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ii(Hi("kv"));if(void 0!==t?.maxResponseBytes&&(!Number.isSafeInteger(t.maxResponseBytes)||t.maxResponseBytes<=0))return ii(ai(ni.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const s=()=>this.getFromNetwork(e,r,t,n.signal);if("network"===t?.source){const e=this.readThrough;if(null===e)return await s();let t="error";const n=Date.now();try{const e=await s();return t=e.ok?"found":e.error.code===ni.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()-n})}catch{}}}return null===this.readThrough?await s():await this.readThrough.get({space:this.context.session.spaceId,key:e,path:r,options:t,signal:n.signal,network:s})}catch(e){return ii(da("kv",e))}finally{n.dispose()}})}async getFromNetwork(e,t,r,n){const s=await this.invokeOperation(t,fa,void 0,n,void 0===r?.maxResponseBytes?void 0:{"x-tinycloud-max-response-bytes":String(r.maxResponseBytes)});if(!s.ok){if(401===s.status||403===s.status){const r=await this.readAuthorizationText(s),n=function(e){try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return;const r=t,n=r.error,s="object"==typeof n&&null!==n?n:void 0;return ji(r.permissionHint)??ji(s?.permissionHint)}catch{return}}(r),i="tinycloud.kv"===n?.service&&n.space===this.context.session.spaceId&&n.path===t?ea({service:"kv",code:ni.AUTH_UNAUTHORIZED,meta:{status:s.status,resource:`${this.context.session.spaceId}/kv/${t}`,requiredAction:fa}}):void 0;return this.authorizationFailure(`Failed to get key ${JSON.stringify(e)}`,s,r,[t],fa,i?{permissionHint:n,...i}:{})}if(404===s.status)return this.classifyNotFound(s,e);const r=await s.text();if(413===s.status)return ii(ai(ni.KV_RESPONSE_TOO_LARGE,`KV value at key ${JSON.stringify(e)} exceeds the requested response limit`,"kv",{meta:{status:s.status,statusText:s.statusText}}));const n=`Failed to get key ${JSON.stringify(e)}: ${s.status} - ${r}`,i=Zi("kv",n,s,r);return ii(i||ai(ni.NETWORK_ERROR,n,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return si({data:await this.parseResponse(s,r?.raw,r?.binary),headers:this.createResponseHeaders(s.headers),...s.retry&&{retry:s.retry}})}async batchGet(e,t){return this.withTelemetry("batchGet",String(e.length),()=>this.batchRead(e,fa,t))}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ii(Hi("kv"));if(void 0!==r?.ifMatch&&void 0!==r.ifNoneMatch)return ii(ai(ni.INVALID_INPUT,"KV put cannot combine ifMatch and ifNoneMatch","kv"));const n=this.getFullPath(e,r?.prefix),s=this.serializePutValue(t,r?.contentType),i=this.createRequestSignal(r?.signal,r?.timeout);try{const t=()=>this.putToNetwork(e,n,s,r,i.signal);return null===this.readThrough?await t():await this.readThrough.write({op:"put",space:this.context.session.spaceId,entries:[{path:n,body:s}],signal:i.signal,conditional:void 0!==r?.ifMatch||void 0!==r?.ifNoneMatch,network:t})}catch(e){return ii(da("kv",e))}finally{i.dispose()}})}async putToNetwork(e,t,r,n,s){const i=await this.invokeOperation(t,pa,r,s,{...void 0===n?.ifMatch?{}:{"if-match":n.ifMatch},...void 0===n?.ifNoneMatch?{}:{"if-none-match":n.ifNoneMatch}});if(401===i.status||403===i.status)return this.authorizationFailure(`Failed to put key ${JSON.stringify(e)}`,i,await this.readAuthorizationText(i),[t],pa);if(!i.ok){const t=await i.text();if(412===i.status)return ii(ai(ni.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}`,n=Zi("kv",r,i,t);if(n)return ii(n);return this.handleQuotaErrorResponse(i,t,e)||ii(ai(ni.KV_WRITE_FAILED,r,"kv",{meta:{status:i.status,statusText:i.statusText}}))}return si({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 ii(Hi("kv"));if(0===e.length)return si({written:[],count:0});if(!this.context.invokeAny)return ii(ai(ni.INVALID_INPUT,"KV batchPut requires SDK runtime support for multi-resource invocations","kv"));const r=this.context.session,n=e.map(e=>this.getFullPath(e.key,t?.prefix)),s=new Set;for(const e of n){if(s.has(e))return ii(ai(ni.INVALID_INPUT,`KV batchPut received duplicate key after prefix resolution: ${e}`,"kv"));s.add(e)}const i=this.createRequestSignal(t?.signal,t?.timeout);try{const t=()=>this.batchPutToNetwork(e,n,i.signal);if(null===this.readThrough)return await t();const s=e.map((e,t)=>({path:n[t],body:this.serializeBatchPutValue(e)}));return await this.readThrough.write({op:"batchPut",space:r.spaceId,entries:s,signal:i.signal,network:()=>this.batchPutToNetwork(e,n,i.signal,s)})}catch(e){const t=da("kv",e);return ii({...t,meta:{...t.meta,requestMayHaveDispatched:!1}})}finally{i.dispose()}})}async batchPutToNetwork(e,t,r,n){const s=this.context.session;let i=!1;try{const a=new FormData;for(let r=0;r<e.length;r++)a.append(Ea(t[r]),n?.[r]?.body??this.serializeBatchPutValue(e[r]));const o=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.invokeAny(s,t.map(e=>({spaceId:s.spaceId,service:"kv",path:e,action:pa})));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 ii(ai(ni.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,pa);return this.handleQuotaErrorResponse(o,r,"batch")||ii(ai(ni.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=zi(t);return ii(ai(r?ni.TIMEOUT:ni.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 ii(ai(ni.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))?si(u):ii(ai(ni.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=da("kv",e);return ii({...t,meta:{...t.meta,requestMayHaveDispatched:i}})}}async list(e){return this.withTelemetry("list",e?.prefix,async()=>{if("network"!==e?.source&&null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ii(Hi("kv"));if(void 0!==e?.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return ii(ai(ni.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 n=()=>this.listFromNetwork(t,e,r.signal);let s;if("network"===e?.source){const e=this.readThrough;if(null===e)s=await n();else{let r="error";const i=Date.now();try{s=await n(),r=s.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 s=null===this.readThrough?await n():await this.readThrough.list({space:this.context.session.spaceId,listPath:t,options:e,signal:r.signal,network:n});return s.ok?this.finishList(s.data,t,e?.removePrefix):s}catch(e){return ii(da("kv",e))}finally{r.dispose()}})}async listFromNetwork(e,t,r){const n=await this.invokeOperation(e,ya,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(!n.ok){if(401===n.status||403===n.status)return this.authorizationFailure("Failed to list keys",n,await this.readAuthorizationText(n),[e],ya);const t=await n.text(),r=`Failed to list keys: ${n.status} - ${t}`,s=Zi("kv",r,n,t);return ii(s||ai(ni.NETWORK_ERROR,r,"kv",{meta:{status:n.status,statusText:n.statusText}}))}return si({keys:await this.parseResponse(n,t?.raw)??[],...null===n.headers.get("x-tinycloud-truncated")?{}:{truncated:"true"===n.headers.get("x-tinycloud-truncated")},...null===n.headers.get("x-tinycloud-next-cursor")?{}:{nextCursor:n.headers.get("x-tinycloud-next-cursor")??void 0}})}finishList(e,t,r){let n=e.keys;if(r&&t){const e=t.endsWith("/")?t:`${t}/`;n=n.map(t=>t.startsWith(e)?t.slice(e.length):t)}return si({keys:n,...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 ii(Hi("kv"));if("string"!=typeof e?.prefix||0===e.prefix.length)return ii(ai(ni.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 ii(ai(ni.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 n=this.createRequestSignal(e.signal,e.timeout);try{const s=await this.invokeOperation(t,va,void 0,n.signal,r);if(!s.ok)return await this.changesFailure(s,e.prefix,n.signal);const i=await s.text();let a;try{a=JSON.parse(i)}catch{a=void 0}const o=this.normalizeChangesResponse(a,e.prefix);return o?si(o):ii(ai(ni.NETWORK_ERROR,"KV changes response was not a tinycloud.kv/sync page","kv",{meta:{status:s.status,statusText:s.statusText}}))}catch(e){return ii(da("kv",e))}finally{n.dispose()}})}async changesFailure(e,t,r){if(404===e.status)return this.classifyNotFound(e,t);let n;try{n=await e.text()}catch(e){if(r.aborted)throw e;n=""}const s={status:e.status,statusText:e.statusText};let i,a;try{const e=JSON.parse(n),t=_a(e)?e.error:void 0;_a(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 ii(ai(ni.KV_SYNC_RESET_REQUIRED,`${o}: the node requires a reset (${i??"reason not given"}); discard sync state and restart without a cursor`,"kv",{meta:{...s,reason:i}}));if(403===e.status&&"RETENTION_GRANT_REFUSED"===a)return ii(ai(ni.KV_RETENTION_GRANT_REFUSED,`${o}: the retention grant was refused (${i??"reason not given"})`,"kv",{meta:{...s,reason:i}}));if(401===e.status){const e=function(e){const t=wa.exec(e.trim());if(null!==t)return void 0!==t[1]?ni.AUTH_DELEGATION_REVOKED:ni.AUTH_DELEGATION_ANCESTOR_REVOKED}(n);if(void 0!==e)return ii(ai(e,`${o}: 401 - ${n}`,"kv",{meta:s}))}return 401===e.status||403===e.status?this.authorizationFailure(o,e,n,[t],va):ii(ai(400===e.status?ni.INVALID_INPUT:ni.NETWORK_ERROR,`${o}: ${e.status} - ${n}`,"kv",{meta:s}))}normalizeChangesResponse(e,t){if(!_a(e))return;const{changes:r,more:n,cursor:s,source:i,authority:a}=e;if(!Array.isArray(r)||"boolean"!=typeof n||"string"!=typeof s||!_a(i)||"string"!=typeof i.nodeDid||"string"!=typeof i.space||"string"!=typeof i.prefix||!_a(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(!_a(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||!_a(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:n,cursor:s,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 ii(Hi("kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const s=()=>this.deleteFromNetwork(e,r,t,n.signal);return null===this.readThrough?await s():await this.readThrough.write({op:"delete",space:this.context.session.spaceId,entries:[{path:r}],signal:n.signal,conditional:void 0!==t?.ifMatch,network:s})}catch(e){return ii(da("kv",e))}finally{n.dispose()}})}async deleteFromNetwork(e,t,r,n){const s=await this.invokeOperation(t,ga,void 0,n,void 0===r?.ifMatch?void 0:{"if-match":r.ifMatch});if(!s.ok){if(401===s.status||403===s.status)return this.authorizationFailure(`Failed to delete key ${JSON.stringify(e)}`,s,await this.readAuthorizationText(s),[t],ga);if(404===s.status)return this.classifyNotFound(s,e);const r=await s.text();if(412===s.status)return ii(ai(ni.KV_PRECONDITION_FAILED,`KV precondition failed for key ${JSON.stringify(e)}`,"kv",{meta:{status:s.status,statusText:s.statusText}}));const n=`Failed to delete key ${JSON.stringify(e)}: ${s.status} - ${r}`,i=Zi("kv",n,s,r);return ii(i||ai(ni.NETWORK_ERROR,n,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return si({data:void 0,headers:this.createResponseHeaders(s.headers),...s.retry&&{retry:s.retry}})}async head(e,t){return this.withTelemetry("head",e,async()=>{if(!this.requireAuth())return ii(Hi("kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeOperation(r,ma,void 0,n.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],ma);if(404===t.status)return await this.classifyNotFound(t,e);const n=await t.text(),s=`Failed to get metadata for key ${JSON.stringify(e)}: ${t.status} - ${n}`,i=Zi("kv",s,t,n);return ii(i||ai(ni.NETWORK_ERROR,s,"kv",{meta:{status:t.status,statusText:t.statusText}}))}return si({data:void 0,headers:this.createResponseHeaders(t.headers)})}catch(e){return ii(da("kv",e))}finally{n.dispose()}})}async batchHead(e,t){return this.withTelemetry("batchHead",String(e.length),()=>this.batchRead(e,ma,t))}async createSignedReadUrl(e,t){return this.withTelemetry("createSignedReadUrl",e,async()=>{if(!this.requireAuth())return ii(Hi("kv"));const r=this.getFullPath(e,t?.prefix),n=this.context.session,s={space:n.spaceId,path:r,ttl_seconds:t?.expiresInSeconds??Math.ceil(300)};void 0!==t?.contentHash&&(s.content_hash=t.contentHash),void 0!==t?.etag&&(s.etag=t.etag);const i=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeWithRetry(`${this.host}/signed/kv`,()=>this.context.invoke(n,"kv",r,fa),{headers:{"content-type":"application/json"},body:JSON.stringify(s),signal:i.signal});if(!t.ok)return await this.createSignedReadUrlError(t,e,r);const a=this.normalizeSignedReadUrlResponse(await t.json());return a?si(a):ii(ai(ni.NETWORK_ERROR,"Signed read URL response did not include url, ticketId, and expiresAt","kv"))}catch(e){return ii(da("kv",e))}finally{i.dispose()}})}withPrefix(e){return new ha(this,e)}}).serviceName="kv";var Ta=class{constructor(e,t){this.service=e,this.dbName=t}apply(e){return this.service.applyMigrationsOnDb(this.dbName,e)}},xa=class{constructor(e,t){this.service=e,this.name=t,this.migrations=new Ta(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)}},Oa={READ:et.READ,WRITE:et.WRITE,SCHEMA:et.SCHEMA,ADMIN:et.ADMIN,SELECT:et.SELECT,EXECUTE:et.EXECUTE,EXPORT:et.EXPORT,ALL:et.ALL},Ra=new Set(["alter","create","drop"]),Na="__tinycloud_sql_migrations",Aa=`CREATE TABLE IF NOT EXISTS ${Na} (\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)`,Ia="tinycloud.sql.migrations",Sa="000_metadata";function Da(e){return e.map(e=>e instanceof Uint8Array?Array.from(e):e)}function Ua(e){return/no such table/i.test(e)}function Pa(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function La(e,t){return Array.isArray(e)?e[t]:e&&"object"==typeof e?Object.values(e)[t]:void 0}(class extends la{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 xa(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 ii(ai(ni.INVALID_INPUT,r,"sql"));const n=`${e}\0${t.namespace}`,s=this.migrationLocks.get(n);if(s)return s;const i=this.applyMigrationsOnDbUnlocked(e,t);this.migrationLocks.set(n,i);try{return await i}finally{this.migrationLocks.delete(n)}}async queryOnDb(e,t,r,n){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return ii(Hi("sql"));const s=this.createRequestSignal(n?.signal);try{const i={action:"query",sql:t,params:Da(r??[])};void 0!==n?.maxRows&&(i.maxRows=n.maxRows),void 0!==n?.maxBytes&&(i.maxBytes=n.maxBytes);const a=this.actionForSql(t,Oa.READ),o=await this.invokeSQL(e,a,i,s.signal);if(!o.ok){const t=await this.handleErrorResponse(o,"query",e,[a]);return this.redactFailure(t,n?.redactErrors,o.status)}return si(await o.json())}catch(e){return this.redactFailure(ii(da("sql",e)),n?.redactErrors)}finally{s.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return ii(Hi("sql"));const s=this.createRequestSignal(n?.signal);try{const i={action:"execute",sql:t,params:Da(r??[])};n?.schema&&(i.schema=n.schema);const a=[this.actionForSql(t,Oa.WRITE),...(n?.schema??[]).map(e=>this.actionForSql(e,Oa.SCHEMA))],o=this.dedupeActions(a),c=await this.invokeSQL(e,o,i,s.signal);if(!c.ok){const t=await this.handleErrorResponse(c,"execute",e,o);return this.redactFailure(t,n?.redactErrors,c.status)}return si(await c.json())}catch(e){return this.redactFailure(ii(da("sql",e)),n?.redactErrors)}finally{s.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return ii(Hi("sql"));const n=this.createRequestSignal(r?.signal);try{const s=this.actionsForSqlBatch(t),i=await this.invokeSQL(e,s,{action:"batch",statements:t},n.signal);if(!i.ok){const t=await this.handleErrorResponse(i,"batch",e,s);return this.redactFailure(t,r?.redactErrors,i.status)}return si(await i.json())}catch(e){return this.redactFailure(ii(da("sql",e)),r?.redactErrors)}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return ii(Hi("sql"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeSQL(e,Oa.WRITE,{action:"execute_statement",name:t,params:r??[]},s.signal);return n.ok?si(await n.json()):await this.handleErrorResponse(n,"executeStatement",e,[Oa.WRITE])}catch(e){return ii(da("sql",e))}finally{s.dispose()}})}async exportDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return ii(Hi("sql"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeSQL(e,Oa.READ,{action:"export"},r.signal);if(!t.ok)return await this.handleErrorResponse(t,"export",e,[Oa.READ]);const n=t;return"function"==typeof n.blob?si(await n.blob()):si(await t.text())}catch(e){return ii(da("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='${Na}'`,[],{signal:t.signal});let n=r.ok?0===r.data.rows.length:r.error.code===ni.SQL_DATABASE_NOT_FOUND||Ua(r.error.message);if(!r.ok&&!n)return r;const s=new Set;if(!n){const r=await this.queryOnDb(e,`SELECT id FROM ${Na} WHERE namespace = ? ORDER BY applied_at, id`,[t.namespace],{signal:t.signal});if(n=!r.ok&&(r.error.code===ni.SQL_DATABASE_NOT_FOUND||Ua(r.error.message)),!r.ok&&!n)return r;if(r.ok)for(const e of r.data.rows){const t=La(e,0);"string"==typeof t&&s.add(t)}}const i=t.migrations.filter(e=>s.has(e.id)).map(e=>e.id),a=t.migrations.filter(e=>!s.has(e.id)),o=[];if(a.length>0&&n){const r=await this.ensureMigrationsTable(e,t.signal);if(!r.ok)return r}for(const r of a){const n=await this.applyOneMigration(e,t.namespace,r,t.signal);if(!n.ok)return n;o.push(r.id)}return si({database:e,namespace:t.namespace,status:o.length>0?"applied":"already_current",applied:o,skipped:i})})}async applyOneMigration(e,t,r,n){const s=[...r.sql.map(e=>"string"==typeof e?{sql:e}:e),{sql:`INSERT OR REPLACE INTO ${Na} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[Pa(t,r.id),t,r.id,(new Date).toISOString(),r.sql.length]}],i=await this.batchOnDb(e,s,{signal:n});return i.ok?si(void 0):i}async ensureMigrationsTable(e,t){const r=await this.batchOnDb(e,[{sql:Aa},{sql:`INSERT OR REPLACE INTO ${Na} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[Pa(Ia,Sa),Ia,Sa,(new Date).toISOString(),1]}],{signal:t});return r.ok?si(void 0):r}async invokeSQL(e,t,r,n){const s=Array.isArray(t)?t:[t];return this.invokeWithRetry(`${this.host}/invoke`,()=>{const t=this.context.session;return 1===s.length?this.context.invoke(t,"sql",e,s[0]):this.invokeSQLAny(t,e,s)},{headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n})}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?Oa.ADMIN:void 0!==r&&Ra.has(r)?Oa.SCHEMA:t}actionsForSqlBatch(e){return this.dedupeActions(e.map(e=>this.actionForSql(e.sql,Oa.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 n=e.error.code,s="string"==typeof n&&Object.prototype.hasOwnProperty.call(ni,n)?n:ni.SQL_ERROR,i="number"==typeof r&&Number.isInteger(r)&&r>=400&&r<=599?r:void 0;return ii(ai(s,"SQL operation failed","sql",void 0===i?void 0:{meta:{status:i}}))}async handleErrorResponse(e,t,r,n){const s=await e.text(),i=Di(e.status,e.statusText,s);if(402===e.status)return ii(ua("sql",402,i,s));if(413===e.status&&ca(s))return ii(ua("sql",413,i,s));const a=Zi("sql",`SQL ${t} failed: ${e.status} - ${s}`,e,s);if(a)return ii(a);const o=Ii(s),c=ba("sql",t,e.status,s)??this.mapHttpStatusToErrorCode(e.status,o.error),u=Si("SQL",t,e.status,s,o);if(401===e.status){const{action:e}=Ji(s);e&&n.includes(e)&&(i.requiredAction=e,i.resource=`${this.context.session.spaceId}/sql/${r}`)}return ii(ai(c,u,"sql",{meta:i}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return ni.SQL_ERROR;case 401:return ni.AUTH_UNAUTHORIZED;case 403:return"sql_readonly_violation"===t?ni.SQL_READONLY_VIOLATION:ni.SQL_PERMISSION_DENIED;case 404:return ni.SQL_DATABASE_NOT_FOUND;case 413:return ni.SQL_RESPONSE_TOO_LARGE;case 429:return ni.SQL_QUOTA_EXCEEDED;default:return ni.NETWORK_ERROR}}}).serviceName="sql";var Ca=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)}},Ka={READ:tt.READ,WRITE:tt.WRITE,ADMIN:tt.ADMIN,DESCRIBE:tt.DESCRIBE,EXPORT:tt.EXPORT,IMPORT:tt.IMPORT,EXECUTE:tt.EXECUTE,ALL:tt.ALL};(class extends la{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 Ca(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,n){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return ii(Hi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Ka.READ,{action:"query",sql:t,params:r??[]},s.signal);return n.ok?si(await n.json()):await this.handleErrorResponse(n,"query")}catch(e){return ii(da("duckdb",e))}finally{s.dispose()}})}async queryArrowOnDb(e,t,r,n){return this.withTelemetry("queryArrow",e,async()=>{if(!this.requireAuth())return ii(Hi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Ka.READ,{action:"query",sql:t,params:r??[]},s.signal,{Accept:"application/vnd.apache.arrow.stream"});return n.ok?si(await n.arrayBuffer()):await this.handleErrorResponse(n,"queryArrow")}catch(e){return ii(da("duckdb",e))}finally{s.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return ii(Hi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const i={action:"execute",sql:t,params:r??[]};n?.schema&&(i.schema=n.schema);const a=await this.invokeDuckDb(e,Ka.WRITE,i,s.signal);return a.ok?si(await a.json()):await this.handleErrorResponse(a,"execute")}catch(e){return ii(da("duckdb",e))}finally{s.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return ii(Hi("duckdb"));const n=this.createRequestSignal(r?.signal);try{const s={action:"batch",statements:t};void 0!==r?.transactional&&(s.transactional=r.transactional);const i=await this.invokeDuckDb(e,Ka.WRITE,s,n.signal);return i.ok?si(await i.json()):await this.handleErrorResponse(i,"batch")}catch(e){return ii(da("duckdb",e))}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return ii(Hi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Ka.WRITE,{action:"executeStatement",name:t,params:r??[]},s.signal);return n.ok?si(await n.json()):await this.handleErrorResponse(n,"executeStatement")}catch(e){return ii(da("duckdb",e))}finally{s.dispose()}})}async describeDb(e,t){return this.withTelemetry("describe",e,async()=>{if(!this.requireAuth())return ii(Hi("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,Ka.READ,{action:"describe"},r.signal);return t.ok?si(await t.json()):await this.handleErrorResponse(t,"describe")}catch(e){return ii(da("duckdb",e))}finally{r.dispose()}})}async exportOnDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return ii(Hi("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,Ka.EXPORT,{action:"export"},r.signal);return t.ok?si(await t.blob()):await this.handleErrorResponse(t,"export")}catch(e){return ii(da("duckdb",e))}finally{r.dispose()}})}async importOnDb(e,t,r){return this.withTelemetry("import",e,async()=>{if(!this.requireAuth())return ii(Hi("duckdb"));const n=this.createRequestSignal(r?.signal);try{const r=await this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,Ka.IMPORT),{headers:{"Content-Type":"application/x-duckdb"},body:new Blob([t]),signal:n.signal});return r.ok?si(void 0):await this.handleErrorResponse(r,"import")}catch(e){return ii(da("duckdb",e))}finally{n.dispose()}})}async invokeDuckDb(e,t,r,n,s){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,t),{headers:{"Content-Type":"application/json",...s},body:JSON.stringify(r),signal:n})}async handleErrorResponse(e,t){const r=await e.text(),n=Di(e.status,e.statusText,r);if(402===e.status)return ii(ua("duckdb",402,n,r));if(413===e.status&&ca(r))return ii(ua("duckdb",413,n,r));const s=Zi("duckdb",`DuckDB ${t} failed: ${e.status} - ${r}`,e,r);if(s)return ii(s);const i=Ii(r),a=ba("duckdb",t,e.status,r)??this.mapHttpStatusToErrorCode(e.status,i.error),o=Si("DuckDB",t,e.status,r,i);if(401===e.status){const{resource:e,action:t}=Ji(r);t&&(n.requiredAction=t),e&&(n.resource=e)}return ii(ai(a,o,"duckdb",{meta:n}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return ni.DUCKDB_ERROR;case 401:return ni.AUTH_UNAUTHORIZED;case 403:return"duckdb_readonly_violation"===t?ni.DUCKDB_READONLY_VIOLATION:ni.DUCKDB_PERMISSION_DENIED;case 404:return ni.DUCKDB_DATABASE_NOT_FOUND;case 413:return ni.DUCKDB_RESPONSE_TOO_LARGE;case 429:return ni.DUCKDB_QUOTA_EXCEEDED;default:return ni.NETWORK_ERROR}}}).serviceName="duckdb";var Ba=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 $a(e,t){const r=to(t);return r?`${e}/${r}`:e}function Va(e){return"number"==typeof e&&e>=400&&e<500&&408!==e&&429!==e}(class extends la{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(Qa),n={requested:r,signatures:r.map(Xa),ttlSeconds:t.ttlSeconds,onReady:t.onReady,queue:new Ba},s=()=>{this._subscribers.delete(n),n.queue.close(),this.wake()},{signal:i}=t;if(!i?.aborted){i?.addEventListener("abort",s,{once:!0}),this._subscribers.add(n),this.wake(),this._readyStream&&this.notifyReady(n,this._readyStream);try{for await(const e of n.queue)yield e}finally{i?.removeEventListener("abort",s),s()}}}async register(e){if(!this.requireAuth())return ii(Hi("hooks"));if("string"!=typeof e.secret||0===e.secret.trim().length)return ii(ai(ni.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",$a(e.service,e.pathPrefix)),{headers:{"content-type":"application/json"},body:JSON.stringify({space:e.space,service:e.service,pathPrefix:to(e.pathPrefix),abilities:e.abilities??[],callbackUrl:e.callbackUrl,secret:e.secret})});if(!t.ok)return ii(await ro("hooks","failed to register webhook",t));const r=io(await t.json());return r?si(r):ii(da("hooks",new Error("Webhook registration response did not include a record")))}catch(e){return ii(da("hooks",e))}}async list(e={}){if(!this.requireAuth())return ii(Hi("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=to(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?$a(e.service,e.pathPrefix):"webhooks"),{method:"GET"});if(!r.ok)return ii(await ro("hooks","failed to list webhooks",r));const n=function(e){if(Array.isArray(e))return e.map(e=>io(e)).filter(e=>null!==e);if(!e||"object"!=typeof e)return null;const t=e,r=ao(t.webhooks)??ao(t.subscriptions)??ao(t.hooks)??ao(t.data);if(r)return r;const n=oo(t);return n?[n]:null}(await r.json());return n?si(n):ii(da("hooks",new Error("Webhook list response did not include records")))}catch(e){return ii(da("hooks",e))}}async unregister(e,t={}){if(!this.requireAuth())return ii(Hi("hooks"));try{const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks/${encodeURIComponent(e)}`,()=>this.createHookHeaders("tinycloud.hooks/unregister",t.target?$a(t.target.service,t.target.pathPrefix):`webhooks/${e}`),{method:"DELETE"});return r.ok?si(void 0):ii(await ro("hooks","failed to unregister webhook",r))}catch(e){return ii(da("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},n=await this.phase(t.key,e=>this.attempt(t,e,r));(r.delivered||r.openedAt>0&&performance.now()-r.openedAt>=5e3)&&(e=0),n&&this.plan()?.key===t.key&&("stopped"!==n.kind?"refused"===n.kind&&n.terminal?(this.release(n.error),this.report(n.error)):("ended"!==n.kind&&this.report(n.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 n=await t(r.signal);return r.signal.aborted?void 0:n}finally{this._phase=void 0,r.abort()}}async attempt(e,t,r){let n,s="mint";const i=++this._streamGeneration,a=()=>!t.aborted&&!n?.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"};n=this.createRequestSignal(t,0);const u=this.host,d=await Fa(n.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:n.signal});var t});if(!a())return{kind:"stopped"};if(!d.ok){const e=d.status,t=await Fa(n.signal,()=>ro("hooks","failed to mint hook ticket",d));return a()?{kind:"refused",terminal:Va(e),error:t}:{kind:"stopped"}}const l=await Fa(n.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(s="open",!a())return{kind:"stopped"};const f=await Fa(n.signal,()=>o.fetch(`${u}/hooks/events?ticket=${encodeURIComponent(h)}`,{method:"GET",headers:{accept:"text/event-stream"},signal:n.signal}));if(!a())return{kind:"stopped"};if(!f.ok)return{kind:"refused",terminal:!1,error:ja(f.status)};r.openedAt=performance.now();const p=async function*(e,t){if(!e)throw new Error("Hook stream response does not expose a readable body");const r=new TextDecoder;let n="";for await(const s of async function*(e,t){const r=e;if("function"==typeof r?.[Symbol.asyncIterator]){const e=r[Symbol.asyncIterator](),n=()=>{try{const t=e.return?.();t&&Promise.resolve(t).then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",n,{once:!0});try{for(;!t?.aborted;){const t=await e.next();if(t.done)break;yield t.value}}finally{t?.removeEventListener("abort",n),n()}return}const n=e;if("function"!=typeof n.getReader)throw new Error("Unsupported hook stream body type");const s=n.getReader(),i=()=>{try{const e=s.cancel?.();e&&e.then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",i,{once:!0});try{for(;!t?.aborted;){const{done:e,value:t}=await s.read();if(e)break;t&&(yield t)}}finally{t?.removeEventListener("abort",i),i(),s.releaseLock?.()}}(e,t)){n+=r.decode(s,{stream:!0}).replace(/\r\n/g,"\n");let e=n.indexOf("\n\n");for(;e>=0;){const t=n.slice(0,e);n=n.slice(e+2);const r=no(t);r&&(yield r),e=n.indexOf("\n\n")}}n+=r.decode();const s=no(n.trim());s&&(yield s)}(f.body,n.signal)[Symbol.asyncIterator]();try{for(;;){const t=await Fa(n.signal,()=>p.next());if(!a())return{kind:"stopped"};if(t.done)break;const s=t.value;if(!s.data)continue;if("ready"===s.event){const t=JSON.parse(s.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=so(s);if(!a())return{kind:"stopped"};this.dispatch(o),r.delivered=!0}}finally{const e=p.return?.();e&&Promise.resolve(e).then(()=>{},()=>{})}return a()?{kind:"ended"}:{kind:"stopped"}}catch(e){return n?.signal.aborted||e===qa?{kind:"stopped"}:{kind:"failed",error:Za(s,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,n=[],s=[];try{const r=this._config.streamRetry,s=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);n.push((r?.wait??Ja)(s,e,t))}catch{n.push(Promise.resolve())}s.push(Ya(t)),r&&s.push(Ya(r));try{await Promise.race([...n,...s.map(({promise:e})=>e)])}catch{}finally{for(const e of s)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,n)=>e.set(r.signatures[n],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(ai(ni.INVALID_INPUT,"Hook readiness callback failed","hooks"))}}}dispatch(e){for(const t of this._subscribers)eo(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=ai(ni.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 qa=Symbol("hooks attempt superseded");async function Fa(e,t){if(e.aborted)throw"function"!=typeof t&&t.then(Ma,()=>{}),qa;const r="function"==typeof t?t():t;return new Promise((t,n)=>{let s=!1;const i=()=>e.removeEventListener("abort",a),a=()=>{s||(s=!0,i(),n(qa))};e.addEventListener("abort",a,{once:!0}),r.then(e=>{s?Ma(e):(s=!0,i(),t(e))},e=>{s||(s=!0,i(),n(e))})})}function Ma(e){if(e instanceof Response&&e.body)try{e.body.cancel().then(()=>{},()=>{})}catch{}}function ja(e){const t="number"==typeof e?e:void 0;return ai(ni.NETWORK_ERROR,`hook stream open refused: ${t??"unknown status"}`,"hooks",{meta:{phase:"open",status:t}})}var Ha=new Set(["Error","TypeError","AbortError","TimeoutError","SyntaxError","RangeError","NetworkError"]);function Za(e,t){const r=Ga(t,"name"),n="string"==typeof r&&Ha.has(r)?r:"Error",s=za(Ga(t,"code"))??za(Ga(Ga(t,"cause"),"code"));return ai(ni.NETWORK_ERROR,`hook stream ${e} failed: ${n}${s?` (${s})`:""}`,"hooks",{meta:{phase:e,errorName:n,...s?{errorCode:s}:{}}})}var Wa=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 za(e){return"string"==typeof e&&Wa.has(e)?e:void 0}function Ga(e,t){if(null!==e&&("object"==typeof e||"function"==typeof e))try{return Reflect.get(e,t)}catch{return}}var Ja=(e,t,r)=>((e,t,r=!1)=>new Promise(n=>{const s=()=>{clearTimeout(i),t.removeEventListener("abort",s),n()},i=setTimeout(s,e);r&&i.unref?.(),t.aborted?s():t.addEventListener("abort",s)}))(e,r,!0);function Ya(e){let t;const r=new Promise(e=>{t=e}),n=()=>t();return e.aborted?t():e.addEventListener("abort",n,{once:!0}),{promise:r,dispose:()=>e.removeEventListener("abort",n)}}function Qa(e){return{...e,pathPrefix:"kv"===e.service?to(e.pathPrefix):e.pathPrefix?.replace(/^\/+/,"")||void 0,abilities:e.abilities?[...e.abilities]:[]}}function Xa(e){return JSON.stringify({space:e.space,service:e.service,pathPrefix:e.pathPrefix??"",abilities:[...e.abilities??[]].sort()})}function eo(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,n=e.databasePath??e.path;if(r&&"/"!==r&&(!n||(r.endsWith("/")?!n.startsWith(r):n!==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 to(e){if(!e)return;const t=e.replace(/^\/+|\/+$/g,"");return t.length>0?t:void 0}async function ro(e,t,r){let n=r.statusText;try{const e=await r.text();e&&(n=e)}catch{}return ai(408===r.status||504===r.status?ni.TIMEOUT:ni.NETWORK_ERROR,`${t}: ${r.status} ${n}`,e,{meta:{status:r.status,statusText:r.statusText}})}function no(e){if(!e)return null;let t,r="message";const n=[];for(const s of e.split("\n")){if(!s||s.startsWith(":"))continue;const[e,...i]=s.split(":"),a=i.join(":").replace(/^ /,"");switch(e){case"event":r=a;break;case"id":t=a;break;case"data":n.push(a)}}return 0===n.length?null:{event:r,id:t,data:n.join("\n")}}function so(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 io(e){if(!e||"object"!=typeof e)return null;const t=e;return oo(t)??io(t.webhook)??io(t.hook)??io(t.subscription)??io(t.data)??null}function ao(e){return Array.isArray(e)?e.map(e=>io(e)).filter(e=>null!==e):null}function oo(e){const t=co(e,"id"),r=co(e,"space")??co(e,"spaceId"),n=co(e,"service"),s=co(e,"callbackUrl")??co(e,"callback_url");return t&&r&&n&&s?{id:t,space:r,service:n,pathPrefix:uo(e,"pathPrefix")??uo(e,"path_prefix"),abilities:ho(e,"abilities")??fo(e,"abilitiesJson")??fo(e,"abilities_json"),callbackUrl:s,active:lo(e,"active")??!0,createdAt:co(e,"createdAt")??co(e,"created_at")??(new Date).toISOString(),subscriberDid:uo(e,"subscriberDid")??uo(e,"subscriber_did")}:null}function co(e,t){const r=e[t];return"string"==typeof r?r:void 0}function uo(e,t){return co(e,t)}function lo(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function ho(e,t){const r=e[t];if(!Array.isArray(r))return;const n=r.filter(e=>"string"==typeof e);return n.length===r.length?n:void 0}function fo(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 po(e){return void 0===e?"":yo(e)}function yo(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(yo).join(",")}]`;const t=Object.keys(e).sort(),r=[];for(const n of t){const t=e[n];void 0!==t&&r.push(`${JSON.stringify(n)}:${yo(t)}`)}return`{${r.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}var go="0123456789abcdef";function mo(e){let t="";for(let r=0;r<e.length;r++){const n=e[r];t+=go[n>>4&15]+go[15&n]}return t}function vo(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let n=0;n<e.length;n+=3){const s=e[n],i=n+1<e.length?e[n+1]:0,a=n+2<e.length?e[n+2]:0;r+=t[s>>2&63],r+=t[63&(s<<4|i>>4)],r+=n+1<e.length?t[63&(i<<2|a>>6)]:"=",r+=n+2<e.length?t[63&a]:"="}return r}function _o(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),r=t.length;if(r%4!=0)throw new Error("invalid base64 input");const n=r/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),s=new Uint8Array(n),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<n&&(s[a++]=u),a<n&&(s[a++]=d),a<n&&(s[a++]=l)}return s}function ko(e){return(new TextEncoder).encode(e)}function wo(e,t){return mo(e(ko(po(t))))}var Eo={masterMessage:e=>`tinycloud-vault-master-v1:${e}`,identityMessage:"tinycloud-encryption-identity-v1"},bo="x-vault-version",To="x-vault-cipher",xo="x-vault-key-id",Oo="x-vault-content-type",Ro="x-vault-kdf",No="x-vault-key-rotation",Ao="x-vault-grant-version",Io="x-vault-grantor",So="signatures",Do="__wrap_key__";function Uo(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof crypto&&void 0!==crypto.subtle}catch{return!1}}function Po(){return new Promise((e,t)=>{const r=indexedDB.open("tinycloud-vault-cache",1);r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains(So)||e.createObjectStore(So)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}function Lo(e,t){return new Promise((r,n)=>{const s=e.transaction(So,"readonly").objectStore(So).get(t);s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}function Co(e,t,r){return new Promise((n,s)=>{const i=e.transaction(So,"readwrite").objectStore(So).put(r,t);i.onsuccess=()=>n(),i.onerror=()=>s(i.error)})}function Ko(e,t){return new Promise((r,n)=>{const s=e.transaction(So,"readwrite").objectStore(So).delete(t);s.onsuccess=()=>r(),s.onerror=()=>n(s.error)})}async function Bo(e){const t=await Lo(e,Do);if(t)return t;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Co(e,Do,r),r}function $o(e){return`sig:${e}`}async function Vo(e){if(!Uo())return null;try{const t=await Po(),r=await Lo(t,$o(e));if(!r)return null;const n=await Bo(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)}(n,r)}catch{return null}}async function qo(e,t){if(Uo())try{const r=await Po(),n=await Bo(r),s=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))}}(n,t);await Co(r,$o(e),s)}catch{}}async function Fo(e){if(Uo())try{const t=await Po();if(e)await Ko(t,$o(e));else{const e=await function(e){return new Promise((t,r)=>{const n=e.transaction(So,"readonly").objectStore(So).getAllKeys();n.onsuccess=()=>t(n.result.filter(e=>"string"==typeof e)),n.onerror=()=>r(n.error)})}(t);for(const r of e)r.startsWith("sig:")&&await Ko(t,r)}}catch{}}function Mo(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function jo(e){return(new TextEncoder).encode(e)}function Ho(e){return(new TextDecoder).decode(e)}function Zo(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}function Wo(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function zo(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 Go(e){return null!==e&&"object"==typeof e&&"data"in e?e.data:e}function Jo(e){return"number"==typeof e.meta?.status}function Yo(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 Qo(e){return{ok:!1,error:{...e,service:"vault",message:Yo(e)}}}function Xo(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 ec(e){return e.replace(/0x[0-9a-fA-F]{40}/g,e=>e.toLowerCase())}function tc(e,t,r){const n=e;if("object"!=typeof n||null===n||Array.isArray(n)||!["networkId","alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"].every(e=>"string"==typeof n[e]&&""!==n[e])||!Number.isInteger(n.keyVersion)||void 0!==n.aad&&"string"!=typeof n.aad)return"corrupt";let s="";try{"string"==typeof n.aad&&(s=Ho(_o(n.aad)))}catch{}const i=`:${r}`;return s.endsWith(i)&&ec(s.slice(0,-i.length))===ec(`tinycloud.vault:${t}`)?"ok":"mismatch"}var rc=[500,502,503,504,520,522,524];function nc(e,t){const r=Mi(t);if(r)return Qo(r);if(t.code===ni.STORAGE_QUOTA_EXCEEDED||t.code===ni.STORAGE_LIMIT_REACHED)return Qo({code:t.code,message:t.message,meta:t.meta});const n=`${e}: ${t.message}`;return t.code===ni.AUTH_UNAUTHORIZED?Qo({code:"unauthenticated"===na(t)?"AUTH_UNAUTHORIZED":"PERMISSION_DENIED",message:n,...void 0!==t.meta?{meta:t.meta}:{},cause:Xo(t)}):Qo({code:"STORAGE_ERROR",cause:new Error(n,{cause:Xo(t)}),...void 0!==t.meta?{meta:t.meta}:{}})}(class extends la{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):jo("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(Ho(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=Eo,n=`vault-master:${e}`,s=`vault-identity:${this.tc.address}`;try{if(!this.masterKey){let s=await Vo(n);if(!s){if(!t)return Qo({code:"VAULT_LOCKED",message:"Signer is required when no cached master signature exists"});s=jo(await t.signMessage(r.masterMessage(e))),await qo(n,s)}this.masterKey=this.crypto.deriveKey(s,this.crypto.sha256(jo(e)),jo("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:zo(a),privateKey:new Uint8Array(0)};else{let e=await Vo(s);if(!e){if(!t)return this.encryptionIdentity=null,this._isUnlocked=!0,si(void 0);e=jo(await t.signMessage(r.identityMessage)),await qo(s,e)}const n=this.crypto.deriveKey(e,jo("tinycloud-x25519"),jo("encryption-identity"));this.encryptionIdentity=this.crypto.x25519FromSeed(n);try{const e=Wo(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,si(void 0)}catch(e){return this.masterKey=null,this.encryptionIdentity=null,Qo({code:"STORAGE_ERROR",cause:Mo(e)})}});try{return await this.unlockInFlight}finally{this.unlockInFlight=null}}async clearCache(e){e?await Fo(`vault-master:${e}`):await Fo()}lock(){this.masterKey=null,this.encryptionIdentity=null,this._isUnlocked=!1}onSignOut(){this.lock(),super.onSignOut()}async putNetworkEncrypted(e,t,r){const n=this.networkEncryption;if(!n)return Qo({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});if(void 0!==r?.ifMatch){if(void 0!==r.ifNoneMatch)return Qo({code:"STORAGE_ERROR",cause:new Error("ifMatch cannot be combined with ifNoneMatch")});if(!/^"[^"\s]+"$/.test(r.ifMatch))return Qo({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:s,contentType:i}=this.serializeValue(t,r),a={[bo]:"2",[To]:"tinycloud-network-envelope",[Oo]:i,...r?.metadata??{}},o=jo(`tinycloud.vault:${this.vaultConfig.spaceId}:${e}`),c=await n.service.encryptToNetwork(n.networkId,s,{aad:o,metadata:a});if(!c.ok){const e=Mi(c.error);return Qo(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===ni.KV_PRECONDITION_FAILED)return Qo({code:"ALREADY_EXISTS",key:e,...void 0!==h.error.meta?{meta:h.error.meta}:{},cause:Xo(h.error)});if(void 0!==r?.ifMatch){const t=function(e,t){const r=t.meta?.status,n=t.code===ni.KV_PRECONDITION_FAILED?"ETAG_MISMATCH":t.code===ni.KV_WRITE_FAILED&&400===r?"INVALID_ETAG":t.code===ni.OUTCOME_UNKNOWN||t.code===ni.KV_WRITE_FAILED&&"number"==typeof r&&rc.includes(r)||(t.code===ni.NETWORK_ERROR||t.code===ni.TIMEOUT)&&void 0===r&&!1!==t.meta?.requestMayHaveDispatched?"OUTCOME_UNKNOWN":t.code===ni.NODE_BUSY||t.code===ni.REQUEST_TIMEOUT?"NODE_BUSY":void 0;if(void 0!==n)return Qo({code:n,key:e,message:t.message,...void 0!==t.meta?{meta:t.meta}:{},cause:Xo(t)})}(e,h.error);if(void 0!==t)return t}return nc("Failed to store encrypted value",h.error)}return{ok:!0,data:void 0}}catch(e){const t=Mi(e);return Qo(t||{code:"STORAGE_ERROR",cause:Mo(e)})}}async getNetworkEncrypted(e,t){const r=this.networkEncryption;if(!r)return Qo({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!n.ok){const t=Mi(n.error);return Qo(t||{code:"KEY_NOT_FOUND",key:e})}const s=Go(n.data),i="string"==typeof s?JSON.parse(s):s;if(!0===t?.expectAad){const t=tc(i,this.vaultConfig.spaceId,e);if("corrupt"===t)return Qo({code:"DECRYPTION_FAILED",message:"envelope is malformed"});if("mismatch"===t)return Qo({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=Mi(o.error);return Qo(e||{code:"DECRYPTION_FAILED",message:o.error.message})}const c=i.metadata??{},u=c[Oo]??"application/json",d=c[xo]??i.encryptedSymmetricKeyHash.slice(0,16),l=this.deserializeValue(o.data,u,t),h="network"===t?.source?n.data.headers?.etag:void 0;return{ok:!0,data:{value:l,metadata:c,keyId:d,...void 0===h?{}:{etag:h}}}}catch(e){const t=Mi(e);return Qo(t||{code:"STORAGE_ERROR",cause:Mo(e)})}}async readNetworkEncrypted(e,t){const r=this.networkEncryption;if(!r||!this.requireAuth())return{status:"read_failed"};let n,s,i;try{n=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"})}catch(e){if(Mi(e))throw e;return{status:"node_unreachable"}}if(!n.ok){if(Mi(n.error))throw n.error;const e=ji(n.error.meta?.permissionHint);return"AUTH_UNAUTHORIZED"===n.error.code&&void 0!==e?{status:"permission_required",hint:e}:"NOT_FOUND"!==n.error.code&&"KV_NOT_FOUND"!==n.error.code||Jo(n.error)?"NODE_NOT_RESPONDING"===n.error.code||"NETWORK_ERROR"===n.error.code||"TIMEOUT"===n.error.code||"ABORTED"===n.error.code?Jo(n.error)?{status:"read_failed"}:{status:"node_unreachable"}:{status:"read_failed"}:{status:"not_found"}}try{const e=Go(n.data);s="string"==typeof e?JSON.parse(e):e}catch{return{status:"corrupt_envelope"}}if(!0===t?.expectAad){const t=tc(s,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(s,e)}catch(e){if(Mi(e))throw e;return{status:"decrypt_failed"}}if(!i.ok){if(Mi(i.error))throw i.error;const e=ji(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=s.metadata??{},r=e[Oo]??"application/json",a=e[xo]??s.encryptedSymmetricKeyHash.slice(0,16),o=this.deserializeValue(i.data,r,t),c=n.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 Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"});if(!t.ok)return Qo({code:"KEY_NOT_FOUND",key:e});const r=Go(t.data);return{ok:!0,data:("string"==typeof r?JSON.parse(r):r).metadata??{}}}catch(e){return Qo({code:"STORAGE_ERROR",cause:Mo(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 Qo({code:"STORAGE_ERROR",cause:new Error("ifNoneMatch is only supported by network-encrypted vaults")});if(void 0!==r?.ifMatch)return Qo({code:"STORAGE_ERROR",cause:new Error("ifMatch is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return Qo({code:"VAULT_LOCKED",message:"Vault must be unlocked before storing data"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{let n;n=t instanceof Uint8Array?t:r?.serialize?r.serialize(t):jo("string"==typeof t?t:JSON.stringify(t));const s=r?.contentType??(t instanceof Uint8Array?"application/octet-stream":"application/json"),i=this.crypto.randomBytes(32),a=Zo(this.crypto.sha256(i)).slice(0,16),o=this.crypto.encrypt(i,n),c=this.crypto.encrypt(this.masterKey,i),u={[bo]:"1",[To]:"aes-256-gcm",[xo]:a,[Oo]:s,[Ro]:"hkdf-sha256",[No]:this.vaultConfig.keyRotation??"per-write",...r?.metadata??{}},d=JSON.stringify({keyId:a,contentType:s,...u}),l=JSON.stringify({key:Wo(c),metadata:d}),h=await this.tc.kv.put(`keys/${e}`,l);if(!h.ok)return nc("Failed to store key blob",h.error);const f=JSON.stringify({data:Wo(o),metadata:u}),p=await this.tc.kv.put(`vault/${e}`,f);return p.ok?si(void 0):nc("Failed to store encrypted value",p.error)}catch(e){return Qo({code:"STORAGE_ERROR",cause:Mo(e)})}})}async get(e,t){return this.withTelemetry("get",e,async()=>{if(this.usesNetworkEncryption)return this.getNetworkEncrypted(e,t);if(!0===t?.expectAad)return Qo({code:"STORAGE_ERROR",cause:new Error("expectAad is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return Qo({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading data"});if(!this.requireAuth())return Qo({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 Qo({code:"KEY_NOT_FOUND",key:e});const n=zo(JSON.parse(r.data.data).key),s=this.crypto.decrypt(this.masterKey,n),i=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!i.ok)return Qo({code:"KEY_NOT_FOUND",key:e});const a=JSON.parse(i.data.data),o=zo(a.data),c=this.crypto.decrypt(s,o),u=a.metadata??{},d=u[Oo]??"application/json",l=u[xo]??"";let h;return h=t?.raw?c:t?.deserialize?t.deserialize(c):"application/json"===d?JSON.parse(Ho(c)):c,si({value:h,metadata:u,keyId:l})}catch(e){return e instanceof Error&&e.message.includes("decryption")?Qo({code:"DECRYPTION_FAILED",message:e.message}):Qo({code:"STORAGE_ERROR",cause:Mo(e)})}})}async delete(e){return this.withTelemetry("delete",e,async()=>{if(!this.isUnlocked)return Qo({code:"VAULT_LOCKED",message:"Vault must be unlocked before deleting data"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{if(this.usesNetworkEncryption){const t=await this.tc.kv.delete(`vault/${e}`);if(!t.ok){const r=Mi(t.error);return Qo(r||{code:"KEY_NOT_FOUND",key:e})}return si(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 n=Mi(t.error)??Mi(r.error);return Qo(n||{code:"KEY_NOT_FOUND",key:e})}return si(void 0)}catch(e){const t=Mi(e);return Qo(t||{code:"STORAGE_ERROR",cause:Mo(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 Qo({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing data"});if(!this.requireAuth())return Qo({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=Mi(r.error);return Qo(e||{code:"STORAGE_ERROR",cause:new Error(`Failed to list vault keys: ${r.error.message}`)})}let n=r.data.keys;if(e?.removePrefix&&e.prefix){const t=e.prefix.endsWith("/")?e.prefix:`${e.prefix}/`;n=n.map(e=>e.startsWith(t)?e.slice(t.length):e)}return si({keys:n,truncated:!0===r.data.truncated,...void 0===r.data.nextCursor?{}:{nextCursor:r.data.nextCursor}})}catch(e){const t=Mi(e);return Qo(t||{code:"STORAGE_ERROR",cause:Mo(e)})}})}async head(e){return this.withTelemetry("head",e,async()=>{if(this.usesNetworkEncryption)return this.headNetworkEncrypted(e);if(!this._isUnlocked)return Qo({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading metadata"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0});if(!t.ok)return Qo({code:"KEY_NOT_FOUND",key:e});return si(JSON.parse(t.data.data).metadata??{})}catch(e){return Qo({code:"STORAGE_ERROR",cause:Mo(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 Qo({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 Qo({code:"VAULT_LOCKED",message:"Vault must be unlocked before granting access"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=await this.resolvePublicKey(t);if(!n.ok)return n;const s=n.data,i=await this.tc.kv.get(`keys/${e}`,{raw:!0});if(!i.ok)return Qo({code:"KEY_NOT_FOUND",key:e});const a=zo(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,s),l=this.crypto.deriveKey(d,jo("tinycloud-x25519"),jo("vault-grant")),h=this.crypto.encrypt(l,o),f=function(...e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}(u.publicKey,h),p=JSON.stringify({grant:Wo(f),spaceId:this.vaultConfig.spaceId,metadata:{[Ao]:"1",[Io]:this.tc.did,...r?.metadata??{}}}),y=await this.tc.kv.put(`grants/${t}/${e}`,p);return y.ok?si(void 0):nc("Failed to store grant",y.error)}catch(e){return Qo({code:"STORAGE_ERROR",cause:Mo(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 Qo({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 Qo({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv.")});const n=this.networkEncryption;if(!n)return Qo({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=await e.get(`vault/${t}`,{raw:!0});if(!s.ok)return Qo({code:"KEY_NOT_FOUND",key:t});const i=Go(s.data),a="string"==typeof i?JSON.parse(i):i,o=await this.decryptCapabilityProof(),c=await n.service.decryptEnvelope(a,o);if(!c.ok)return Qo({code:"DECRYPTION_FAILED",message:c.error.message});const u=a.metadata??{},d=u[Oo]??"application/json",l=u[xo]??a.encryptedSymmetricKeyHash.slice(0,16);return{ok:!0,data:{value:this.deserializeValue(c.data,d,r),metadata:u,keyId:l}}}catch(e){return Qo({code:"STORAGE_ERROR",cause:Mo(e)})}}if(!this._isUnlocked||!this.masterKey||!this.encryptionIdentity)return Qo({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading shared data"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=this.tc.did,s=r?.kv;if(!s)return Qo({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 s.get(`grants/${n}/${t}`,{raw:!0});if(!i.ok)return Qo({code:"GRANT_NOT_FOUND",grantor:e,key:t});const a=zo(("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,jo("tinycloud-x25519"),jo("vault-grant")),l=this.crypto.decrypt(d,c),h=await s.get(`vault/${t}`,{raw:!0});if(!h.ok)return Qo({code:"KEY_NOT_FOUND",key:t});const f="string"==typeof h.data?.data?JSON.parse(h.data.data):h.data?.data,p=zo(f.data),y=this.crypto.decrypt(l,p),g=f.metadata??{},m=g[Oo]??"application/json",v=g[xo]??"";let _;return _=r?.raw?y:r?.deserialize?r.deserialize(y):"application/json"===m?JSON.parse(Ho(y)):y,si({value:_,metadata:g,keyId:v})}catch(e){return e instanceof Error&&e.message.includes("decryption")?Qo({code:"DECRYPTION_FAILED",message:e.message}):Qo({code:"STORAGE_ERROR",cause:Mo(e)})}})}async resolvePublicKey(e){try{const t=this.parseDID(e);if(!t)return Qo({code:"PUBLIC_KEY_NOT_FOUND",did:e});const r=this.tc.makePublicSpaceId(t.address,t.chainId),n=await this.tc.readPublicSpace(this.host,r,".well-known/vault-pubkey");return n.ok?{ok:!0,data:zo(n.data)}:Qo({code:"PUBLIC_KEY_NOT_FOUND",did:e})}catch(t){return Qo({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 Qo({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing grants"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.list({prefix:"grants/",removePrefix:!0});if(!t.ok)return Qo({code:"STORAGE_ERROR",cause:new Error(`Failed to list grants: ${t.error.message}`)});const r=[];for(const n of t.data.keys)if(n.endsWith(`/${e}`)){const t=n.slice(0,n.length-e.length-1);t&&r.push(t)}return si(r)}catch(e){return Qo({code:"STORAGE_ERROR",cause:Mo(e)})}})}async revoke(e,t){return this.withTelemetry("revoke",e,async()=>{if(this.usesNetworkEncryption)return Qo({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 Qo({code:"VAULT_LOCKED",message:"Vault must be unlocked before revoking access"});if(!this.requireAuth())return Qo({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.listGrants(e);if(!r.ok)return r;const n=r.data.filter(e=>e!==t),s=(await this.tc.kv.delete(`grants/${t}/${e}`),await this.get(e));if(!s.ok)return s;const i=s.data,a=this.crypto.randomBytes(32),o=Zo(this.crypto.sha256(a)).slice(0,16);let c;c=i.value instanceof Uint8Array?i.value:jo(JSON.stringify(i.value));const u=this.crypto.encrypt(a,c),d=this.crypto.encrypt(this.masterKey,a),l={...i.metadata,[xo]:o},h=JSON.stringify({key:Wo(d),metadata:JSON.stringify({keyId:o,...l})}),f=await this.tc.kv.put(`keys/${e}`,h);if(!f.ok)return nc("Failed to store rotated key blob",f.error);const p=JSON.stringify({data:Wo(u),metadata:l}),y=await this.tc.kv.put(`vault/${e}`,p);if(!y.ok)return nc("Failed to store re-encrypted value",y.error);for(const t of n)(await this.reencrypt(e,t)).ok;return si(void 0)}catch(e){return Qo({code:"STORAGE_ERROR",cause:Mo(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),n=t[4];return isNaN(r)||!n?null:{address:n,chainId:r}}}).serviceName="vault",Object.freeze(["default","global","scoped"]);var sc="tinycloud.encryption.decrypt/v1",ic="tinycloud.encryption.decrypt-result/v1";function ac(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 oc(e){return{...e,service:"encryption",message:ac(e)}}function cc(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function uc(e,t,r,n){let s;try{s=Bi(e.networkId)}catch(e){return{ok:!1,error:oc({code:"INVALID_NETWORK_ID",message:`descriptor networkId is malformed: ${e instanceof Error?e.message:String(e)}`})}}if(s.name!==n||!qi(s.ownerDid,r))return{ok:!1,error:oc({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&&qi(i,r)&&qi(i,s.ownerDid)?e.name!==n?{ok:!1,error:oc({code:"INVALID_NETWORK_ID",message:"descriptor name does not match networkId name"})}:"string"!=typeof e.publicEncryptionKey||0===e.publicEncryptionKey.length?{ok:!1,error:oc({code:"INVALID_NETWORK_ID",message:"descriptor publicEncryptionKey must be a non-empty string"})}:{ok:!0,data:{...e,ownerDid:i}}:{ok:!1,error:oc({code:"INVALID_NETWORK_ID",message:"descriptor ownerDid does not match networkId ownerDid"})}}function dc(e){return"active"===e.state||"rotating"===e.state?{ok:!0,data:e}:{ok:!1,error:oc({code:"NETWORK_NOT_ACTIVE",state:e.state})}}var lc="x25519-hkdf-aes256gcm/v2",hc=ko("TCW2"),fc=ko("tinycloud.encryption.key-wrap/v2");function pc(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let r=0;for(const n of e)t.set(n,r),r+=n.length;return t}function yc(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}function gc(e){if("string"!=typeof e)throw new Error("Invalid key wrap encoding");const t=_o(e);if(32!==t.length||vo(t)!==e)throw new Error("Invalid key wrap encoding");return t}function mc(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=55296&&r<=56319){const r=e.charCodeAt(++t);if(!(r>=56320&&r<=57343))return!1}else if(r>=56320&&r<=57343)return!1}return!0}function vc(e){if("network-key"!==e.purpose&&"receiver-key"!==e.purpose||"string"!=typeof e.networkId||"string"!=typeof e.keyPath||!mc(e.networkId)||!mc(e.keyPath)||!Number.isSafeInteger(e.keyVersion)||e.keyVersion<=0||!e.metadata||"object"!=typeof e.metadata||Array.isArray(e.metadata)||Object.entries(e.metadata).some(([e,t])=>!mc(e)||"string"!=typeof t||!mc(t)))throw new Error("Invalid key wrap context");if(""!==e.networkId){const t=$i(""===e.keyPath?e.networkId:`${e.networkId}/${e.keyPath}`);if(t.networkId!==e.networkId||(t.keyPath??"")!==e.keyPath||e.keyPath.endsWith("/"))throw new Error("Invalid key wrap resource")}}function _c(e){return e.length>=4&&hc.every((t,r)=>e[r]===t)}function kc(e){if(!_c(e)||e.length<8)throw new Error("Invalid v2 key wrap frame");const t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(4);if(0===t||t>65536||e.length<8+t+12+16)throw new Error("Invalid v2 key wrap length");const r=e.subarray(8,8+t),n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r)),s=["v","alg","kdf","aead","salt","ephemeralPublicKey","recipientPublicKey","purpose","networkId","keyPath","keyVersion","metadata"].sort();if(!n||"object"!=typeof n||Array.isArray(n)||Object.keys(n).sort().join(",")!==s.join(",")||2!==n.v||n.alg!==lc||"hkdf-sha256"!==n.kdf||"aes-256-gcm"!==n.aead)throw new Error("Invalid v2 key wrap header");if(vc(n),gc(n.salt),gc(n.ephemeralPublicKey),gc(n.recipientPublicKey),!yc(r,ko(po({...n}))))throw new Error("Non-canonical v2 key wrap header");const i=8+t;return{header:n,aad:e.subarray(0,i),nonce:e.subarray(i,i+12),ciphertext:e.subarray(i+12)}}function wc(e,t){vc(t);for(const r of["purpose","networkId","keyPath","keyVersion"])if(e[r]!==t[r])throw new Error("Key wrap context mismatch");if(po(e.metadata)!==po(t.metadata))throw new Error("Key wrap metadata mismatch")}function Ec(e,t,r=!1){if("x25519-aes256gcm/v1"!==t&&t!==lc)throw new Error("Unsupported key wrap algorithm");if(r&&t!==lc)throw new Error("V2 network key wrap required");if(_c(e)!==(t===lc))throw new Error("Key wrap algorithm mismatch");t===lc&&kc(e)}function bc(e,t=!1){const r=_o(e.encryptedSymmetricKey);Ec(r,e.alg,t),e.alg===lc&&wc(kc(r).header,{purpose:"network-key",networkId:e.networkId,keyPath:e.keyPath??"",keyVersion:e.keyVersion,metadata:e.metadata??{}})}function Tc(e){return{ok:!0,data:e}}function xc(e){return{ok:!1,error:e}}function Oc(e){return oc("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 la{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,n;try{if(e.identifier.startsWith("urn:tinycloud:encryption:")){const s=Bi(e.identifier);t=s.networkId,r=s.ownerDid,n=s.name}else{if(void 0===e.ownerDid)return{ok:!1,error:oc({code:"INVALID_INPUT",message:"discoverNetwork requires `ownerDid` when identifier is a bare network name"})};t=`urn:tinycloud:encryption:${e.ownerDid}:${e.identifier}`;const s=Bi(t);r=s.ownerDid,n=s.name}}catch(e){if(e instanceof Ki)return{ok:!1,error:oc({code:"INVALID_NETWORK_ID",message:e.message})};throw e}if(void 0!==e.node)try{const s=await e.node.fetchByNetworkId(t);if(null!==s){const e=uc(s,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"node"}}:e}}catch(e){const t=Mi(e);return t?{ok:!1,error:oc(t)}:{ok:!1,error:oc({code:"TRANSPORT_ERROR",cause:e instanceof Error?e:new Error(String(e))})}}if(void 0!==e.wellKnown)try{const s=await e.wellKnown.fetchWellKnown(r,function(e){if(!Li.test(e))throw new Ki(`network name ${JSON.stringify(e)} must match ${Li.source}`);return`.well-known/encryption/network/${e}`}(n));if(null!==s){const e=uc(s,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"well-known"}}:e}}catch(e){const t=Mi(e);if(t)return{ok:!1,error:oc(t)}}return{ok:!1,error:oc({code:"NETWORK_NOT_FOUND",networkId:t,name:n})}}({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?Tc(r.data.descriptor):r}async encryptToNetwork(e,t,r){try{this.assertActive();const n=await this.discoverNetwork(e);if(!n.ok)return n;const s=dc(n.data);if(!s.ok)return s;const i=s.data,a=_o(i.publicEncryptionKey);return Tc(function(e,t){if($i(void 0===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`).keyPath!==t.keyPath||t.keyPath?.endsWith("/"))throw new Ki("keyPath must name an exact encryption key");const r=t.keyWrapV2?lc:"x25519-aes256gcm/v1";if(void 0!==t.alg&&t.alg!==r)throw new Error("Algorithm does not match keyWrapV2");const n=t.keyVersion??1,s=e.randomBytes(32),i=e.authEncrypt(s,t.plaintext,t.aad),a=t.keyWrapV2?function(e,t,r){if(vc(r),32!==e.length)throw new Error("Invalid recipient public key");const n=Cr(32),s=$s.getPublicKey(n),i=Cr(32),a=ko(po({...{...r,v:2,alg:lc,kdf:"hkdf-sha256",aead:"aes-256-gcm",salt:vo(i),ephemeralPublicKey:vo(s),recipientPublicKey:vo(e)}}));if(a.length>65536)throw new Error("Key wrap header too large");const o=new Uint8Array(8);o.set(hc),new DataView(o.buffer).setUint32(4,a.length);const c=pc(o,a),u=Cr(12);let d;try{const r=$s.getSharedSecret(n,e);try{if(r.every(e=>0===e))throw new Error("Invalid key agreement");d=ei(ti,r,i,pc(fc,s,e),32)}finally{r.fill(0)}return pc(c,u,yr(d,u,c).encrypt(t))}finally{n.fill(0),d?.fill(0)}}(t.networkPublicKey,s,{purpose:"network-key",networkId:t.networkId,keyPath:t.keyPath??"",keyVersion:n,metadata:t.metadata??{}}):e.sealToNetworkKey(t.networkPublicKey,s),o=vo(a),c=wo(e.sha256,o);return{envelope:{v:1,networkId:t.networkId,...void 0!==t.keyPath?{keyPath:t.keyPath}:{},alg:r,keyVersion:n,encryptedSymmetricKey:o,encryptedSymmetricKeyHash:c,ciphertext:vo(i),...void 0!==t.aad?{aad:vo(t.aad)}:{},...void 0!==t.metadata?{metadata:t.metadata}:{}},symmetricKey:s}}(this.crypto,{networkId:i.networkId,...void 0!==r?.keyPath?{keyPath:r.keyPath}:{},networkPublicKey:a,plaintext:t,...void 0!==r?.aad?{aad:r.aad}:{},keyWrapV2:r?.keyWrapV2??this._config.keyWrapV2??!1,...void 0!==r?.alg?{alg:r.alg}:{},keyVersion:r?.keyVersion??i.keyVersion,...void 0!==r?.metadata?{metadata:r.metadata}:{}}).envelope)}catch(e){const t=Mi(e);return xc(oc(t||{code:"TRANSPORT_ERROR",cause:cc(e)}))}}async decryptEnvelope(e,t,r){try{this.assertActive();const s=function(e,t,r=!1){if(null===t||"object"!=typeof t)return{ok:!1,error:oc({code:"INVALID_ENVELOPE",message:"envelope must be an object"})};const n=t;if(1!==n.v)return{ok:!1,error:oc({code:"INVALID_ENVELOPE",message:`envelope.v must be 1 (got ${n.v})`})};try{if(void 0!==$i(n.networkId).keyPath)throw new Error("networkId must identify the network root");if(void 0!==n.keyPath){if("string"!=typeof n.keyPath)throw new Error("keyPath must be a string");if($i(`${n.networkId}/${n.keyPath}`).keyPath!==n.keyPath||n.keyPath.endsWith("/"))throw new Error("keyPath must name an exact encryption key")}}catch(e){return{ok:!1,error:oc({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 n[e]||0===n[e].length)return{ok:!1,error:oc({code:"INVALID_ENVELOPE",message:`envelope.${e} must be a non-empty string`})};if("number"!=typeof n.keyVersion||!Number.isInteger(n.keyVersion))return{ok:!1,error:oc({code:"INVALID_ENVELOPE",message:"envelope.keyVersion must be an integer"})};if(wo(e.sha256,n.encryptedSymmetricKey)!==n.encryptedSymmetricKeyHash)return{ok:!1,error:oc({code:"INVALID_ENVELOPE",message:"envelope.encryptedSymmetricKeyHash does not match canonical hash of encryptedSymmetricKey"})};try{bc(n,r)}catch{return{ok:!1,error:oc({code:"INVALID_ENVELOPE",message:"Envelope key wrap context is invalid"})}}return{ok:!0,data:n}}(this.crypto,e,this._config.requireKeyWrapV2??!1);if(!s.ok)return s;if(void 0!==r?.aad&&s.data.aad!==vo(r.aad))return xc(oc({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 xc(Oc(t.error));i=t.data}const a=dc(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 xc(oc({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 xc(oc({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=vo(c.publicKey),d=wo(this.crypto.sha256,u),l={type:sc,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:po((n={crypto:this.crypto,body:l,receiverPublicKey:c.publicKey}).body),bodyHash:wo(n.crypto.sha256,n.body),receiverPublicKeyHash:wo(n.crypto.sha256,n.body.receiverPublicKey)},f=function(e){const t=void 0!==e.canonicalBody?mo(e.crypto.sha256(ko(e.canonicalBody))):wo(e.crypto.sha256,e.body),r=wo(e.crypto.sha256,e.body.receiverPublicKey);return{type:sc,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}),p=await async function(e,t,r){const n=function(e,t){if(t.body.type!==sc)return{ok:!1,error:oc({code:"INVALID_INPUT",message:`body.type must be ${sc}`})};if(t.facts.type!==sc)return{ok:!1,error:oc({code:"INVALID_INPUT",message:`facts.type must be ${sc}`})};if(t.facts.targetNode!==t.targetNode)return{ok:!1,error:oc({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:oc({code:"INVALID_INPUT",message:"body.targetNode must equal targetNode"})};if(t.facts.networkId!==t.networkId)return{ok:!1,error:oc({code:"INVALID_INPUT",message:"facts.networkId must equal networkId"})};if(t.body.networkId!==t.networkId)return{ok:!1,error:oc({code:"INVALID_INPUT",message:"body.networkId must equal networkId"})};if(t.facts.keyPath!==t.body.keyPath)return{ok:!1,error:oc({code:"INVALID_INPUT",message:"facts.keyPath must equal body.keyPath"})};if(t.facts.alg!==t.body.alg)return{ok:!1,error:oc({code:"INVALID_INPUT",message:"facts.alg must equal body.alg"})};if(t.facts.keyVersion!==t.body.keyVersion)return{ok:!1,error:oc({code:"INVALID_INPUT",message:"facts.keyVersion must equal body.keyVersion"})};if(t.facts.encryptedSymmetricKeyHash!==t.body.encryptedSymmetricKeyHash)return{ok:!1,error:oc({code:"INVALID_INPUT",message:"facts.encryptedSymmetricKeyHash must equal body.encryptedSymmetricKeyHash"})};if(t.facts.receiverPublicKeyHash!==t.body.receiverPublicKeyHash)return{ok:!1,error:oc({code:"INVALID_INPUT",message:"facts.receiverPublicKeyHash must equal body.receiverPublicKeyHash"})};try{if(void 0!==$i(t.networkId).keyPath)throw new Ki("networkId must identify the network root")}catch(e){return{ok:!1,error:oc({code:"INVALID_NETWORK_ID",message:e instanceof Error?e.message:String(e)})}}try{if($i(void 0===t.body.keyPath?t.body.networkId:`${t.body.networkId}/${t.body.keyPath}`).keyPath!==t.body.keyPath||t.body.keyPath?.endsWith("/"))throw new Ki("keyPath must name an exact encryption key")}catch(e){return{ok:!1,error:oc({code:"INVALID_INPUT",message:e instanceof Error?e.message:String(e)})}}const r=po(t.body);return wo(e.sha256,t.body)!==t.facts.bodyHash?{ok:!1,error:oc({code:"INVALID_INPUT",message:"facts.bodyHash does not match the canonical body hash"})}:{ok:!0,data:t,canonicalBody:r}}(e,r);if(!n.ok)return n;try{const e=await t.signDecryptInvocation(n.data);return e.authorization&&e.invocationCid?e.canonicalBody!==n.canonicalBody?{ok:!1,error:oc({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:oc({code:"INVALID_INPUT",message:"decrypt-invocation signer returned an empty authorization or invocationCid"})}}catch(e){return{ok:!1,error:oc({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:f,proof:t});if(this.assertActive(),!p.ok)return"TRANSPORT_ERROR"!==p.error.code?p:xc(oc({code:"INVALID_INPUT",message:"Unable to build decrypt request"}));let y;try{y=await this._config.transport.postDecrypt({targetNode:o,networkId:e.networkId,authorization:p.data.authorization,canonicalBody:p.data.canonicalBody,signal:this.abortSignal}),this.assertActive()}catch(t){const r=Mi(t);return r?xc(Oc(r)):t instanceof ri.DecryptTransportResponseError?xc(oc(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"})):xc(Oc({code:"TRANSPORT_ERROR",cause:cc(t)}))}const g=function(e){const{crypto:t,request:r,facts:n,invocationCid:s,requestBodyHash:i,response:a}=e;if(a.type!==ic)return{ok:!1,error:oc({code:"INVALID_RESPONSE",message:`response.type must be ${ic}`})};if(a.targetNode!==r.targetNode)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(a.networkId!==r.networkId)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(a.nodeId!==r.targetNode)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if("x25519-aes256gcm/v1"!==a.alg&&a.alg!==lc)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(a.keyVersion!==r.keyVersion)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(a.encryptedSymmetricKeyHash!==r.encryptedSymmetricKeyHash)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(a.receiverPublicKeyHash!==r.receiverPublicKeyHash)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(a.invocationCid!==s)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const o=mo(t.sha256(ko(`${s}${i}`)));if(a.requestHash!==o)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(n.encryptedSymmetricKeyHash!==a.encryptedSymmetricKeyHash||n.receiverPublicKeyHash!==a.receiverPublicKeyHash||n.networkId!==a.networkId||n.targetNode!==a.targetNode||n.alg!==r.alg||n.keyVersion!==a.keyVersion)return{ok:!1,error:oc({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const c=(new TextEncoder).encode(function(e){const{nodeSignature:t,...r}=e;return po(r)}(a)),u=_o(a.nodeSignature);return t.verifyNodeSignature(a.nodeId,c,u)?{ok:!0,data:a}:{ok:!1,error:oc({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:this.crypto,request:l,facts:f,invocationCid:p.data.invocationCid,requestBodyHash:f.bodyHash,response:y});if(!g.ok)return g;const m=function(e,t,r,n){const s=_o(r.wrappedKey);if(Ec(s,r.alg),r.alg===lc){if(!n)throw new Error("V2 response requires expected key context");return function(e,t,r){const{header:n,aad:s,nonce:i,ciphertext:a}=kc(t);wc(n,r);const o=$s.getPublicKey(e);if(!yc(o,gc(n.recipientPublicKey)))throw new Error("Key wrap recipient mismatch");const c=function(e,t,r,n){const s=$s.getSharedSecret(e,t);if(s.every(e=>0===e))throw new Error("Invalid key agreement");try{return ei(ti,s,n,pc(fc,t,r),32)}finally{s.fill(0)}}(e,gc(n.ephemeralPublicKey),o,gc(n.salt));try{return yr(c,i,s).decrypt(a)}finally{c.fill(0)}}(t,s,n)}return e.openWithReceiverKey(t,s)}(this.crypto,c.privateKey,g.data,{purpose:"receiver-key",networkId:l.networkId,keyPath:l.keyPath??"",keyVersion:l.keyVersion,metadata:{}}),v=function(e,t,r){bc(t);const n=_o(t.ciphertext),s=void 0!==t.aad?_o(t.aad):void 0;return e.authDecrypt(r,n,s)}(this.crypto,e,m);return Tc(v)}catch(e){const t=Mi(e);return xc(t?Oc(t):oc({code:"INVALID_RESPONSE",message:"Local decryption failed"}))}var n}assertActive(){this._config.assertActive?.()}}).serviceName="encryption";var Rc=Fe({kty:Ke(),crv:Ke().optional(),x:Ke().optional(),y:Ke().optional(),d:Ke().optional(),e:Ke().optional(),n:Ke().optional(),kid:Ke().optional(),alg:Ke().optional(),use:Ke().optional(),key_ops:qe(Ke()).optional()}),Nc=Ze(["main","session","ingested"]),Ac=Fe({id:Ke(),did:Ke(),type:Nc,jwk:Rc.optional(),priority:Be()}),Ic=(Fe({code:Ke(),message:Ke(),service:He("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>Le(t=>t instanceof e,t))(Error).optional(),meta:je(Ke(),Ve()).optional()}),"NOT_INITIALIZED"),Sc="NETWORK_ERROR",Dc="INVALID_INPUT",Uc="INVALID_TOKEN",Pc=Fe({cid:Ke(),delegateDID:Ke(),spaceId:Ke(),path:Ke(),actions:qe(Ke()),caveats:qe(je(Ke(),Ve())).optional(),expiry:We(),isRevoked:$e(),delegatorDID:Ke().optional(),createdAt:We().optional(),parentCid:Ke().optional(),allowSubDelegation:$e().optional(),authHeader:Ke().optional()}),Lc=Fe({cid:Ke().min(1),lease_cid:Ke().min(1),generation:Be().int().nonnegative().safe(),previous_stamp_cid:Ke().min(1),new_end:Be().int().nonnegative().safe(),signed_bytes:Ke().min(1),signature:Ke().min(1)}).strict(),Cc=(Fe({cid:Ke().min(1),status:Ze(["active","revoked","expired","unavailable","not_found"]),exists:$e(),active:$e(),revoked:$e(),expired:$e(),effective_expiry:Be().int().nullable().optional(),renewal_history:qe(Lc).optional()}).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:o.custom,message:"delegation status flags do not match status"})}),Fe({revoked:He(!0),cid:Ke().min(1)}).strict()),Kc=Fe({resource:Ke().min(1),actions:qe(Ke()),caveats:qe(je(Ke(),Ve()))}).strict(),Bc=Ke().datetime({offset:!0}).transform(e=>new Date(e)),$c=Fe({cid:Ke().min(1),direction:Ze(["granted","received"]),delegatorDid:Ke().min(1),delegateDid:Ke().min(1),resources:qe(Kc),parents:qe(Ke()),issuedAt:Bc.nullable(),notBefore:Bc.nullable(),expiresAt:Bc.nullable(),status:Ze(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:Bc.nullable().optional(),revokedBy:Ke().optional(),revokedAncestorCid:Ke().optional()}).strict(),Vc=Fe({schemaVersion:He(2),items:qe($c),nextCursor:Ke().optional()}).strict(),qc=(Fe({direction:Ze(["granted","received","all","issued"]).optional(),status:Ze(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:Ke().trim().min(1).optional(),limit:Be().int().min(1).max(100).optional(),cursor:Ke().min(1).optional()}).strict(),Fe({resource:Ke(),action:Ke(),keys:qe(Ac),delegation:Pc,expiresAt:We().optional()}),Fe({cid:Ke(),spaceId:Ke(),delegator:Ke(),delegatee:Ke(),keyId:Ke().optional(),path:Ke(),actions:qe(Ke()),expiry:We().optional(),notBefore:We().optional(),isRevoked:$e(),createdAt:We(),parentCid:Ke().optional()}),Fe({delegateDID:Ke(),path:Ke(),actions:qe(Ke()),expiry:We().optional(),disableSubDelegation:$e().optional(),statement:Ke().optional()}),qe(Pc),Fe({root:Pc,chain:qe(Pc),leaf:Pc}),Ze(["granted","received","all"])),Fc=(Fe({direction:qc.optional(),path:Ke().optional(),actions:qe(Ke()).optional(),includeRevoked:$e().optional(),delegator:Ke().optional(),delegatee:Ke().optional(),validAt:We().optional(),limit:Be().optional(),cursor:Ke().optional()}),Ze(["owned","delegated"])),Mc=(Fe({id:Ke(),name:Ke().optional(),owner:Ke(),type:Fc,permissions:qe(Ke()).optional(),expiresAt:We().optional()}),Ze(["base64","compact","ipfs"]));Fe({token:Ke(),url:Ke(),delegation:Pc,schema:Mc,expiresAt:We().optional(),description:Ke().optional()}),function(e){Fe({data:e,delegation:Pc,spaceId:Ke(),path:Ke()})}(Ve()),Fe({persist:$e().optional(),validateChain:$e().optional(),keyName:Ke().optional(),createSessionKey:$e().optional(),priority:Be().optional()}),Fe({includePlacement:$e().optional(),path:Ke().optional(),actions:qe(Ke()).optional(),resources:qe(Fe({path:Ke(),actions:qe(Ke()).optional()})).optional(),expiry:We().optional(),schema:Mc.optional(),description:Ke().optional(),baseUrl:Ke().optional(),allowSubDelegation:$e().optional()}),Fe({hosts:qe(Ke()),accountSpaceId:Ke().min(1).optional(),session:Ve().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),invoke:Ve().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),invokeAny:Ve().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:Ve().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),Fe({createSessionKey:Ve().refine(e=>"function"==typeof e,{message:"Expected a function"}),getJWK:Ve().refine(e=>"function"==typeof e,{message:"Expected a function"}),getDID:Ve().refine(e=>"function"==typeof e,{message:"Expected a function"})}),Fe({siwe:Ke(),signature:Ke(),version:Be(),cid:Ke().optional()});var jc=Fe({service:Ke(),space:Ke(),path:Ke(),actions:qe(Ke()),caveats:qe(je(Ke(),Ve())).optional()}),Hc=(Fe({session:Ve().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:Ke(),spaceId:Ke(),abilities:je(Ke(),je(Ke(),qe(Ke()))),expirationSecs:Be(),notBeforeSecs:Be().optional(),disableSubDelegation:$e().optional()}),Fe({delegation:Ke(),cid:Ke(),delegateDID:Ke(),expiry:We(),resources:qe(jc)}),"tinycloud.delegation/revoke"),Zc="tinycloud.delegation/list";function Wc(e,t,r,n){return{code:e,message:t,service:"delegation",cause:r,meta:n}}var zc="delegation-issued-query-v1";async function Gc(e){return(await e.text()).replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,200)}async function Jc(e,t,r,n){const s=n??await Gc(e),i={...r,status:e.status};return 401===e.status||403===e.status?Wc("PERMISSION_DENIED",""===s?"The node refused the request":s,void 0,i):400===e.status&&s.includes("invalid delegation query cursor")?Wc("INVALID_CURSOR","The node rejected the page cursor; list again from the start",void 0,i):503===e.status?Wc("CHAIN_TOO_DEEP","This delegation chain is too long for the node to check right now; try again later",void 0,{...i,retryable:!0}):Wc(Sc,`${t}: ${e.status} - ${s}`,void 0,i)}var Yc=class extends Error{};function Qc(){return{ok:!1,error:Wc("UNSUPPORTED_OPERATION","This node doesn't support listing issued delegations yet",void 0,{feature:zc})}}async function Xc(e,t){const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:Wc(Ic,"Listing issued delegations needs a session key signer")};const n=r.did().split("#",1)[0];if(!/^did:key:z[1-9A-HJ-NP-Za-km-z]+$/.test(n))return{ok:!1,error:Wc(Dc,"Issued queries require the session key's did:key")};try{const s=async(e,s,i)=>e(`${s}/delegation/query`,{method:"POST",headers:{Authorization:await r.sign({[`tinycloud:${n.slice(4)}:agent/delegation`]:{[Zc]:[{}]}},i),"content-type":"application/json"},body:JSON.stringify(t),redirect:"error"});let i;if(e.resourceTransport)i=await e.resourceTransport([{resource:e.spaceId??"",access:"read"}],e=>{const t=e.nodeInfo.features;if(!Array.isArray(t)||!t.includes(zc))throw new Yc;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:Wc(Sc,`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(zc),{ok:!0,data:e.state.issuedQuerySupported}}(e);if(!t.ok)return t;if(!t.data)return Qc();i=await s(e.fetchFn,e.host)}if(!i.ok)return{ok:!1,error:await Jc(i,"Failed to query issued delegations",{})};const a=Vc.safeParse(await i.json());return a.success?{ok:!0,data:a.data}:{ok:!1,error:Wc(Uc,"Node returned an invalid delegation query response")}}catch(e){return Mi(e)?{ok:!1,error:{...da("delegation",e),service:"delegation"}}:e instanceof Yc?Qc():{ok:!1,error:Wc(Sc,`Network error during delegation query: ${String(e)}`,e instanceof Error?e:void 0)}}}async function eu(e,t){const{pageSize:r=100,maxItems:n,untilCid:s,...i}=t;if(void 0!==n&&(!Number.isInteger(n)||n<1))return{ok:!1,error:Wc(Dc,"maxItems must be a positive integer")};const a=[],o=new Set;let c;do{const t=Math.min(r,void 0===n?r:n-a.length),s=await e({...i,direction:"issued",limit:t,...void 0===c?{}:{cursor:c}});if(!s.ok)return s;if(a.push(...s.data.items),c=s.data.nextCursor,void 0!==c){if(o.has(c))return{ok:!1,error:Wc(Uc,"The node returned the same page cursor twice while listing issued delegations")};o.add(c)}}while(void 0!==c&&(void 0===n||a.length<n)&&(void 0===s||!a.some(e=>e.cid===s)));return{ok:!0,data:void 0===n?a:a.slice(0,n)}}async function tu(e,t){if(!t)return{ok:!1,error:Wc(Dc,"cid is required")};const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:Wc(Ic,"Revoking an issued delegation needs a session key signer")};try{const n=async(e,n,s)=>e(`${n}/revoke`,{method:"POST",headers:{Authorization:await r.sign({[`urn:cid:${t}`]:{[Hc]:[{}]}},s)},redirect:"error"}),s=e.resourceTransport?await e.resourceTransport([{resource:e.spaceId??"",access:"read"}],e=>n(e.fetch,e.url,e.nodeDid),{nodeLocal:!0}):await n(e.fetchFn,e.host);if(!s.ok){if(404===s.status){const e=await Gc(s);return{ok:!1,error:"space not found"===e.toLowerCase()?Wc("NOT_FOUND",`Delegation not found: ${t}`,void 0,{cid:t,status:404}):await Jc(s,"Failed to revoke delegation",{cid:t},e)}}return{ok:!1,error:await Jc(s,"Failed to revoke delegation",{cid:t})}}const i=Cc.safeParse(await s.json());return i.success&&i.data.cid===t?{ok:!0,data:i.data}:{ok:!1,error:Wc("REVOCATION_FAILED","Node returned an invalid delegation revocation receipt",void 0,{cid:t})}}catch(e){return Mi(e)?{ok:!1,error:{...da("delegation",e),service:"delegation"}}:{ok:!1,error:Wc(Sc,`Network error during delegation revocation: ${String(e)}`,e instanceof Error?e:void 0)}}}export{eu as queryAllIssued,Xc as queryIssued,tu as revokeIssued};
2
+ var e,t,r={4290(e){var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,i={};((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(i,{DecryptTransportResponseError:()=>a}),e.exports=(e=>((e,i,a,o)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let a of n(i))s.call(e,a)||void 0===a||t(e,a,{get:()=>i[a],enumerable:!(o=r(i,a))||o.enumerable});return e})(t({},"__esModule",{value:!0}),e))(i);var a=class extends Error{constructor(e,t,r){super("Node decrypt request failed"),this.status=e,this.permissionHint=t,this.notFoundMessage=r,this.name="DecryptTransportResponseError"}}}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var i=n[e]={exports:{}};return r[e](i,i.exports,s),i.exports}s.d=(e,t)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),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]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},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}(e||(e={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(t||(t={}));const i=e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),a=e=>{switch(typeof e){case"undefined":return i.undefined;case"string":return i.string;case"number":return Number.isNaN(e)?i.nan:i.number;case"boolean":return i.boolean;case"function":return i.function;case"bigint":return i.bigint;case"symbol":return i.symbol;case"object":return Array.isArray(e)?i.array:null===e?i.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?i.promise:"undefined"!=typeof Map&&e instanceof Map?i.map:"undefined"!=typeof Set&&e instanceof Set?i.set:"undefined"!=typeof Date&&e instanceof Date?i.date:i.object;default:return i.unknown}},o=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 c 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:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){const r=s.path[n];n===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof c))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={},r=[];for(const n of this.issues)if(n.path.length>0){const r=n.path[0];t[r]=t[r]||[],t[r].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}c.create=e=>new c(e);const u=(t,r)=>{let n;switch(t.code){case o.invalid_type:n=t.received===i.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case o.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,e.jsonStringifyReplacer)}`;break;case o.unrecognized_keys:n=`Unrecognized key(s) in object: ${e.joinValues(t.keys,", ")}`;break;case o.invalid_union:n="Invalid input";break;case o.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${e.joinValues(t.options)}`;break;case o.invalid_enum_value:n=`Invalid enum value. Expected ${e.joinValues(t.options)}, received '${t.received}'`;break;case o.invalid_arguments:n="Invalid function arguments";break;case o.invalid_return_type:n="Invalid function return type";break;case o.invalid_date:n="Invalid date";break;case o.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:e.assertNever(t.validation):n="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case o.too_small:n="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 o.too_big:n="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 o.custom:n="Invalid input";break;case o.invalid_intersection_types:n="Intersection results could not be merged";break;case o.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case o.not_finite:n="Number must be finite";break;default:n=r.defaultError,e.assertNever(t)}return{message:n}};let d=u;var l;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(l||(l={}));function h(e,t){const r=d,n=(e=>{const{data:t,path:r,errorMaps:n,issueData:s}=e,i=[...r,...s.path||[]],a={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...s,path:i,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===u?void 0:u].filter(e=>!!e)});e.common.issues.push(n)}class f{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 n of t){if("aborted"===n.status)return p;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return f.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return p;if("aborted"===s.status)return p;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const p=Object.freeze({status:"aborted"}),y=e=>({status:"dirty",value:e}),m=e=>({status:"valid",value:e}),g=e=>"aborted"===e.status,v=e=>"dirty"===e.status,_=e=>"valid"===e.status,k=e=>"undefined"!=typeof Promise&&e instanceof Promise;class w{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}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 E=(e,t)=>{if(_(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 c(e.common.issues);return this._error=t,this._error}}};function b(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:s}:{errorMap:(t,s)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??s.defaultError}:void 0===s.data?{message:i??n??s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:i??r??s.defaultError}},description:s}}class T{get description(){return this._def.description}_getType(e){return a(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new f,ctx:{common:e.parent.common,data:e.data,parsedType:a(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(k(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:a(e)},n=this._parseSync({data:e,path:r.path,parent:r});return E(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:a(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return _(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=>_(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:a(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(k(n)?n:Promise.resolve(n));return E(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,n)=>{const s=e(t),i=()=>n.addIssue({code:o.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then(e=>!!e||(i(),!1)):!!s||(i(),!1)})}refinement(e,t){return this._refinement((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}_refinement(e){return new Ne({schema:this,typeName:Ce.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 Oe.create(this,this._def)}nullable(){return xe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oe.create(this)}promise(){return Te.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return pe.create(this,e,this._def)}transform(e){return new Ne({...b(this._def),schema:this,typeName:Ce.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Re({...b(this._def),innerType:this,defaultValue:t,typeName:Ce.ZodDefault})}brand(){return new Se({typeName:Ce.ZodBranded,type:this,...b(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ae({...b(this._def),innerType:this,catchValue:t,typeName:Ce.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return De.create(this,e)}readonly(){return Pe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const N=/^c[^\s-]{8,}$/i,O=/^[0-9a-z]+$/,x=/^[0-9A-HJKMNP-TV-Z]{26}$/i,R=/^[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,A=/^[a-z0-9_-]{21}$/i,I=/^[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)?)??$/,D=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let P;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])$/,C=/^(([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]))$/,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]))\/(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}=))?$/,B=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,V="((\\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])))",q=new RegExp(`^${V}$`);function F(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(`^${F(e)}$`)}function j(e){let t=`${V}T${F(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 H(e,t){return!("v4"!==t&&t||!U.test(e))||!("v6"!==t&&t||!C.test(e))}function Z(e,t){if(!I.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!("object"!=typeof s||null===s||"typ"in s&&"JWT"!==s?.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function W(e,t){return!("v4"!==t&&t||!L.test(e))||!("v6"!==t&&t||!K.test(e))}class z extends T{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==i.string){const e=this._getOrReturnCtx(t);return h(e,{code:o.invalid_type,expected:i.string,received:e.parsedType}),p}const r=new f;let n;for(const s of this._def.checks)if("min"===s.kind)t.data.length<s.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:o.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if("max"===s.kind)t.data.length>s.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:o.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if("length"===s.kind){const e=t.data.length>s.value,i=t.data.length<s.value;(e||i)&&(n=this._getOrReturnCtx(t,n),e?h(n,{code:o.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&h(n,{code:o.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if("email"===s.kind)D.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"email",code:o.invalid_string,message:s.message}),r.dirty());else if("emoji"===s.kind)P||(P=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),P.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"emoji",code:o.invalid_string,message:s.message}),r.dirty());else if("uuid"===s.kind)R.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"uuid",code:o.invalid_string,message:s.message}),r.dirty());else if("nanoid"===s.kind)A.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"nanoid",code:o.invalid_string,message:s.message}),r.dirty());else if("cuid"===s.kind)N.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"cuid",code:o.invalid_string,message:s.message}),r.dirty());else if("cuid2"===s.kind)O.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"cuid2",code:o.invalid_string,message:s.message}),r.dirty());else if("ulid"===s.kind)x.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"ulid",code:o.invalid_string,message:s.message}),r.dirty());else if("url"===s.kind)try{new URL(t.data)}catch{n=this._getOrReturnCtx(t,n),h(n,{validation:"url",code:o.invalid_string,message:s.message}),r.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"regex",code:o.invalid_string,message:s.message}),r.dirty())):"trim"===s.kind?t.data=t.data.trim():"includes"===s.kind?t.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):"toLowerCase"===s.kind?t.data=t.data.toLowerCase():"toUpperCase"===s.kind?t.data=t.data.toUpperCase():"startsWith"===s.kind?t.data.startsWith(s.value)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):"endsWith"===s.kind?t.data.endsWith(s.value)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):"datetime"===s.kind?j(s).test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:"datetime",message:s.message}),r.dirty()):"date"===s.kind?q.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:"date",message:s.message}),r.dirty()):"time"===s.kind?M(s).test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{code:o.invalid_string,validation:"time",message:s.message}),r.dirty()):"duration"===s.kind?S.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"duration",code:o.invalid_string,message:s.message}),r.dirty()):"ip"===s.kind?H(t.data,s.version)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"ip",code:o.invalid_string,message:s.message}),r.dirty()):"jwt"===s.kind?Z(t.data,s.alg)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"jwt",code:o.invalid_string,message:s.message}),r.dirty()):"cidr"===s.kind?W(t.data,s.version)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"cidr",code:o.invalid_string,message:s.message}),r.dirty()):"base64"===s.kind?$.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"base64",code:o.invalid_string,message:s.message}),r.dirty()):"base64url"===s.kind?B.test(t.data)||(n=this._getOrReturnCtx(t,n),h(n,{validation:"base64url",code:o.invalid_string,message:s.message}),r.dirty()):e.assertNever(s);return{status:r.value,value:t.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:o.invalid_string,...l.errToObj(r)})}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...l.errToObj(e)})}url(e){return this._addCheck({kind:"url",...l.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...l.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...l.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...l.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...l.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...l.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...l.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...l.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...l.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...l.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...l.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...l.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,...l.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,...l.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...l.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...l.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...l.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...l.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...l.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...l.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...l.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...l.errToObj(t)})}nonempty(e){return this.min(1,l.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 G(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}z.create=e=>new z({checks:[],typeName:Ce.ZodString,coerce:e?.coerce??!1,...b(e)});class J extends T{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)!==i.number){const e=this._getOrReturnCtx(t);return h(e,{code:o.invalid_type,expected:i.number,received:e.parsedType}),p}let r;const n=new f;for(const s of this._def.checks)"int"===s.kind?e.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),h(r,{code:o.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):"min"===s.kind?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):"multipleOf"===s.kind?0!==G(t.data,s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):"finite"===s.kind?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),h(r,{code:o.not_finite,message:s.message}),n.dirty()):e.assertNever(s);return{status:n.value,value:t.data}}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,n){return new J({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(n)}]})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:l.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:l.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.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 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)}}J.create=e=>new J({checks:[],typeName:Ce.ZodNumber,coerce:e?.coerce||!1,...b(e)});class Y extends T{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)!==i.bigint)return this._getInvalidInput(t);let r;const n=new f;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"max"===s.kind?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):"multipleOf"===s.kind?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),h(r,{code:o.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):e.assertNever(s);return{status:n.value,value:t.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.bigint,received:t.parsedType}),p}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,r,n){return new Y({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:l.toString(n)}]})}_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:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.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:Ce.ZodBigInt,coerce:e?.coerce??!1,...b(e)});class Q extends T{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==i.boolean){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.boolean,received:t.parsedType}),p}return m(e.data)}}Q.create=e=>new Q({typeName:Ce.ZodBoolean,coerce:e?.coerce||!1,...b(e)});class X extends T{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==i.date){const e=this._getOrReturnCtx(t);return h(e,{code:o.invalid_type,expected:i.date,received:e.parsedType}),p}if(Number.isNaN(t.data.getTime()))return h(this._getOrReturnCtx(t),{code:o.invalid_date}),p;const r=new f;let n;for(const s of this._def.checks)"min"===s.kind?t.data.getTime()<s.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:o.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):"max"===s.kind?t.data.getTime()>s.value&&(n=this._getOrReturnCtx(t,n),h(n,{code:o.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):e.assertNever(s);return{status:r.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:l.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:l.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:Ce.ZodDate,...b(e)});class ee extends T{_parse(e){if(this._getType(e)!==i.symbol){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.symbol,received:t.parsedType}),p}return m(e.data)}}ee.create=e=>new ee({typeName:Ce.ZodSymbol,...b(e)});class te extends T{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.undefined,received:t.parsedType}),p}return m(e.data)}}te.create=e=>new te({typeName:Ce.ZodUndefined,...b(e)});class re extends T{_parse(e){if(this._getType(e)!==i.null){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.null,received:t.parsedType}),p}return m(e.data)}}re.create=e=>new re({typeName:Ce.ZodNull,...b(e)});class ne extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return m(e.data)}}ne.create=e=>new ne({typeName:Ce.ZodAny,...b(e)});class se extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return m(e.data)}}se.create=e=>new se({typeName:Ce.ZodUnknown,...b(e)});class ie extends T{_parse(e){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.never,received:t.parsedType}),p}}ie.create=e=>new ie({typeName:Ce.ZodNever,...b(e)});class ae extends T{_parse(e){if(this._getType(e)!==i.undefined){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.void,received:t.parsedType}),p}return m(e.data)}}ae.create=e=>new ae({typeName:Ce.ZodVoid,...b(e)});class oe extends T{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==i.array)return h(t,{code:o.invalid_type,expected:i.array,received:t.parsedType}),p;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(h(t,{code:e?o.too_big:o.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(h(t,{code:o.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(h(t,{code:o.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type._parseAsync(new w(t,e,t.path,r)))).then(e=>f.mergeArray(r,e));const s=[...t.data].map((e,r)=>n.type._parseSync(new w(t,e,t.path,r)));return f.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new oe({...this._def,minLength:{value:e,message:l.toString(t)}})}max(e,t){return new oe({...this._def,maxLength:{value:e,message:l.toString(t)}})}length(e,t){return new oe({...this._def,exactLength:{value:e,message:l.toString(t)}})}nonempty(e){return this.min(1,e)}}function ce(e){if(e instanceof ue){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Oe.create(ce(n))}return new ue({...e._def,shape:()=>t})}return e instanceof oe?new oe({...e._def,type:ce(e.element)}):e instanceof Oe?Oe.create(ce(e.unwrap())):e instanceof xe?xe.create(ce(e.unwrap())):e instanceof ye?ye.create(e.items.map(e=>ce(e))):e}oe.create=(e,t)=>new oe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ce.ZodArray,...b(t)});class ue extends T{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(),r=e.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(e){if(this._getType(e)!==i.object){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),p}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ie&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||a.push(e);const c=[];for(const e of s){const t=n[e],s=r.data[e];c.push({key:{status:"valid",value:e},value:t._parse(new w(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ie){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)c.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(h(r,{code:o.unrecognized_keys,keys:a}),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 a){const n=r.data[t];c.push({key:{status:"valid",value:t},value:e._parse(new w(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of c){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>f.mergeObjectSync(t,e)):f.mergeObjectSync(t,c)}get shape(){return this._def.shape()}strict(e){return l.errToObj,new ue({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:l.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new ue({...this._def,unknownKeys:"strip"})}passthrough(){return new ue({...this._def,unknownKeys:"passthrough"})}extend(e){return new ue({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ue({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ce.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ue({...this._def,catchall:e})}pick(t){const r={};for(const n of e.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new ue({...this._def,shape:()=>r})}omit(t){const r={};for(const n of e.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new ue({...this._def,shape:()=>r})}deepPartial(){return ce(this)}partial(t){const r={};for(const n of e.objectKeys(this.shape)){const e=this.shape[n];t&&!t[n]?r[n]=e:r[n]=e.optional()}return new ue({...this._def,shape:()=>r})}required(t){const r={};for(const n of e.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof Oe;)e=e._def.innerType;r[n]=e}return new ue({...this._def,shape:()=>r})}keyof(){return we(e.objectKeys(this.shape))}}ue.create=(e,t)=>new ue({shape:()=>e,unknownKeys:"strip",catchall:ie.create(),typeName:Ce.ZodObject,...b(t)}),ue.strictCreate=(e,t)=>new ue({shape:()=>e,unknownKeys:"strict",catchall:ie.create(),typeName:Ce.ZodObject,...b(t)}),ue.lazycreate=(e,t)=>new ue({shape:e,unknownKeys:"strip",catchall:ie.create(),typeName:Ce.ZodObject,...b(t)});class de extends T{_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 c(e.ctx.common.issues));return h(t,{code:o.invalid_union,unionErrors:r}),p});{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=s._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&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map(e=>new c(e));return h(t,{code:o.invalid_union,unionErrors:s}),p}}get options(){return this._def.options}}de.create=(e,t)=>new de({options:e,typeName:Ce.ZodUnion,...b(t)});const le=t=>t instanceof _e?le(t.schema):t instanceof Ne?le(t.innerType()):t instanceof ke?[t.value]:t instanceof Ee?t.options:t instanceof be?e.objectValues(t.enum):t instanceof Re?le(t._def.innerType):t instanceof te?[void 0]:t instanceof re?[null]:t instanceof Oe?[void 0,...le(t.unwrap())]:t instanceof xe?[null,...le(t.unwrap())]:t instanceof Se||t instanceof Pe?le(t.unwrap()):t instanceof Ae?le(t._def.innerType):[];class he extends T{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.object)return h(t,{code:o.invalid_type,expected:i.object,received:t.parsedType}),p;const r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),p)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=le(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 s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new he({typeName:Ce.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...b(r)})}}function fe(t,r){const n=a(t),s=a(r);if(t===r)return{valid:!0,data:t};if(n===i.object&&s===i.object){const n=e.objectKeys(r),s=e.objectKeys(t).filter(e=>-1!==n.indexOf(e)),i={...t,...r};for(const e of s){const n=fe(t[e],r[e]);if(!n.valid)return{valid:!1};i[e]=n.data}return{valid:!0,data:i}}if(n===i.array&&s===i.array){if(t.length!==r.length)return{valid:!1};const e=[];for(let n=0;n<t.length;n++){const s=fe(t[n],r[n]);if(!s.valid)return{valid:!1};e.push(s.data)}return{valid:!0,data:e}}return n===i.date&&s===i.date&&+t===+r?{valid:!0,data:t}:{valid:!1}}class pe extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(g(e)||g(n))return p;const s=fe(e.value,n.value);return s.valid?((v(e)||v(n))&&t.dirty(),{status:t.value,value:s.data}):(h(r,{code:o.invalid_intersection_types}),p)};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])=>n(e,t)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}pe.create=(e,t,r)=>new pe({left:e,right:t,typeName:Ce.ZodIntersection,...b(r)});class ye extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.array)return h(r,{code:o.invalid_type,expected:i.array,received:r.parsedType}),p;if(r.data.length<this._def.items.length)return h(r,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),p;!this._def.rest&&r.data.length>this._def.items.length&&(h(r,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new w(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>f.mergeArray(t,e)):f.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ye({...this._def,rest:e})}}ye.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ye({items:e,typeName:Ce.ZodTuple,rest:null,...b(t)})};class me extends T{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!==i.object)return h(r,{code:o.invalid_type,expected:i.object,received:r.parsedType}),p;const n=[],s=this._def.keyType,a=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new w(r,e,r.path,e)),value:a._parse(new w(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?f.mergeObjectAsync(t,n):f.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new me(t instanceof T?{keyType:e,valueType:t,typeName:Ce.ZodRecord,...b(r)}:{keyType:z.create(),valueType:e,typeName:Ce.ZodRecord,...b(t)})}}class ge extends T{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!==i.map)return h(r,{code:o.invalid_type,expected:i.map,received:r.parsedType}),p;const n=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([e,t],i)=>({key:n._parse(new w(r,e,r.path,[i,"key"])),value:s._parse(new w(r,t,r.path,[i,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of a){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return p;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of a){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return p;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}ge.create=(e,t,r)=>new ge({valueType:t,keyType:e,typeName:Ce.ZodMap,...b(r)});class ve extends T{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==i.set)return h(r,{code:o.invalid_type,expected:i.set,received:r.parsedType}),p;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(h(r,{code:o.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(h(r,{code:o.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function a(e){const r=new Set;for(const n of e){if("aborted"===n.status)return p;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const c=[...r.data.values()].map((e,t)=>s._parse(new w(r,e,r.path,t)));return r.common.async?Promise.all(c).then(e=>a(e)):a(c)}min(e,t){return new ve({...this._def,minSize:{value:e,message:l.toString(t)}})}max(e,t){return new ve({...this._def,maxSize:{value:e,message:l.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ve.create=(e,t)=>new ve({valueType:e,minSize:null,maxSize:null,typeName:Ce.ZodSet,...b(t)});class _e extends T{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:Ce.ZodLazy,...b(t)});class ke extends T{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),p}return{status:"valid",value:e.data}}get value(){return this._def.value}}function we(e,t){return new Ee({values:e,typeName:Ce.ZodEnum,...b(t)})}ke.create=(e,t)=>new ke({value:e,typeName:Ce.ZodLiteral,...b(t)});class Ee extends T{_parse(t){if("string"!=typeof t.data){const r=this._getOrReturnCtx(t),n=this._def.values;return h(r,{expected:e.joinValues(n),received:r.parsedType,code:o.invalid_type}),p}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const e=this._getOrReturnCtx(t),r=this._def.values;return h(e,{received:e.data,code:o.invalid_enum_value,options:r}),p}return m(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 Ee.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ee.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ee.create=we;class be extends T{_parse(t){const r=e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==i.string&&n.parsedType!==i.number){const t=e.objectValues(r);return h(n,{expected:e.joinValues(t),received:n.parsedType,code:o.invalid_type}),p}if(this._cache||(this._cache=new Set(e.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const t=e.objectValues(r);return h(n,{received:n.data,code:o.invalid_enum_value,options:t}),p}return m(t.data)}get enum(){return this._def.values}}be.create=(e,t)=>new be({values:e,typeName:Ce.ZodNativeEnum,...b(t)});class Te extends T{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==i.promise&&!1===t.common.async)return h(t,{code:o.invalid_type,expected:i.promise,received:t.parsedType}),p;const r=t.parsedType===i.promise?t.data:Promise.resolve(t.data);return m(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Te.create=(e,t)=>new Te({type:e,typeName:Ce.ZodPromise,...b(t)});class Ne extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ce.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:e=>{h(n,e),e.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===s.type){const e=s.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===r.value)return p;const t=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?y(t.value):t});{if("aborted"===r.value)return p;const t=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===t.status?p:"dirty"===t.status||"dirty"===r.value?y(t.value):t}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,i);if(n.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===n.common.async){const t=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value),{status:r.value,value:t.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(t=>"aborted"===t.status?p:("dirty"===t.status&&r.dirty(),e(t.value).then(()=>({status:r.value,value:t.value}))))}if("transform"===s.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!_(e))return p;const t=s.transform(e.value,i);if(t instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:t}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>_(e)?Promise.resolve(s.transform(e.value,i)).then(e=>({status:r.value,value:e})):p)}e.assertNever(s)}}Ne.create=(e,t,r)=>new Ne({schema:e,typeName:Ce.ZodEffects,effect:t,...b(r)}),Ne.createWithPreprocess=(e,t,r)=>new Ne({schema:t,effect:{type:"preprocess",transform:e},typeName:Ce.ZodEffects,...b(r)});class Oe extends T{_parse(e){return this._getType(e)===i.undefined?m(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Oe.create=(e,t)=>new Oe({innerType:e,typeName:Ce.ZodOptional,...b(t)});class xe extends T{_parse(e){return this._getType(e)===i.null?m(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}xe.create=(e,t)=>new xe({innerType:e,typeName:Ce.ZodNullable,...b(t)});class Re extends T{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===i.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:Ce.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...b(t)});class Ae extends T{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return k(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new c(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Ce.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...b(t)});class Ie extends T{_parse(e){if(this._getType(e)!==i.nan){const t=this._getOrReturnCtx(e);return h(t,{code:o.invalid_type,expected:i.nan,received:t.parsedType}),p}return{status:"valid",value:e.data}}}Ie.create=e=>new Ie({typeName:Ce.ZodNaN,...b(e)}),Symbol("zod_brand");class Se extends T{_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 De extends T{_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?p:"dirty"===e.status?(t.dirty(),y(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?p:"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 De({in:e,out:t,typeName:Ce.ZodPipeline})}}class Pe extends T{_parse(e){const t=this._def.innerType._parse(e),r=e=>(_(e)&&(e.value=Object.freeze(e.value)),e);return k(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((n,s)=>{const i=e(n);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Ue(t,n),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Ue(t,n),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}}):ne.create()}var Ce;Pe.create=(e,t)=>new Pe({innerType:e,typeName:Ce.ZodReadonly,...b(t)}),ue.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"}(Ce||(Ce={}));const Ke=z.create,$e=J.create,Be=(Ie.create,Y.create,Q.create),Ve=(X.create,ee.create,te.create,re.create,ne.create,se.create),qe=(ie.create,ae.create,oe.create),Fe=ue.create,Me=(ue.strictCreate,de.create,he.create),je=(pe.create,ye.create,me.create),He=(ge.create,ve.create,_e.create,ke.create),Ze=Ee.create,We=(be.create,Te.create,Ne.create,Oe.create,xe.create,Ne.createWithPreprocess,De.create,e=>X.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 Ge(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function Je(e){return e.slice(10,e.indexOf("/"))}function Ye(e){return e.slice(e.indexOf("/")+1)}function Qe(e){const t={};for(const r of ze)Je(r.urn)===e&&(t[Ge(Ye(r.urn))]=r.urn);return t}var Xe=Qe("kv"),et={...Qe("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},tt={...Qe("duckdb"),DESCRIBE:"tinycloud.duckdb/describe",EXECUTE:"tinycloud.duckdb/execute"},rt=Qe("capabilities"),nt=(Qe("hooks"),Qe("encryption")),st=Qe("space"),it=ze;["tinychat-4jq","share-2fz","tinycloud-secrets","openkey-tinycloud-demo"].map(e=>new RegExp(`^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)?${e}\\.pages\\.dev$`));var at="applications",ot="account",ct="applications/",ut="secrets",dt="default",lt="public",ht="agents",ft="tinycloud.encryption",pt=nt.NETWORK_CREATE,yt=[dt,at,ot,ut,lt,ht],mt={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:dt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:dt,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:dt,path:"",actions:["read","write"]}]},gt={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:at,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:at,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:at,path:"",actions:["read","write"]}]},vt={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ot,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ot,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ot,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ot,path:"account",actions:["read","write","schema"]}]},_t={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:ut,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:ut,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:ut,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:ut,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:ut,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:ut,path:"",actions:["read"],skipPrefix:!0}]},kt={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:lt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:lt,path:"",actions:["get","list","metadata"]}]},wt={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:ht,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ht,path:"",actions:["get","put","del","list","metadata"]}]},Et={[dt]:mt,[at]:gt,[ot]:vt,[ut]:_t,[lt]:kt,[ht]:wt};function bt(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Tt(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 Nt(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,n="read"===r||"get"===r?Xe.GET:"write"===r||"put"===r?Xe.PUT:"delete"===r||"del"===r?Xe.DEL:"list"===r?Xe.LIST:"metadata"===r?Xe.METADATA:void 0;if(void 0===n)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const s=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${s}`,actions:[n],skipPrefix:!0}})}(e).flatMap(e=>Nt(e,t,r));const n=!0===e.skipPrefix||e.service===ft;return[{service:e.service,space:e.service===ft?"encryption":e.space??r,path:Tt(t,e.path,n),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 Ot(e){const t=new Set(e.filter(e=>e.service!==ft).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}`,n=t.get(e);if(n)for(const e of r.actions)n.actions.includes(e)||n.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:[rt.READ]}))])}function xt(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,n=e.map(bt),s=n.flatMap(e=>{const t=e.prefix??e.app_id,r=e.space??at;return(e.permissions??[]).flatMap(e=>Nt(e,t,r))});r&&s.push(...Rt.map(e=>({...e,actions:[...e.actions]})));const i=new Map;for(const e of n){const t=i.get(e.app_id)??[];t.push(bt(e)),i.set(e.app_id,t)}return{manifests:n,resources:Ot(s),delegationTargets:[],registryRecords:r?[...i.entries()].map(([e,t])=>({key:`${ct}${e}`,app_id:e,manifests:t})):[],expiryMs:6048e5,includePublicSpace:n.some(e=>e.includePublicSpace??!0)}}([Et[e]],{includeAccountRegistryPermissions:!1})}yt.map(e=>({name:e,manifest:Et[e],persistedAsApplication:e===ut}));var Rt=Object.freeze([{service:"tinycloud.kv",space:ot,path:ct,actions:[Xe.GET,Xe.PUT,Xe.LIST]},{service:"tinycloud.kv",space:ot,path:"spaces/",actions:[Xe.GET,Xe.PUT,Xe.LIST]},{service:"tinycloud.kv",space:ot,path:"system/bootstrap/complete",actions:[Xe.GET,Xe.PUT]},{service:"tinycloud.delegation",space:ot,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ot,path:"account",actions:[et.READ,et.WRITE,et.SCHEMA]},{service:"tinycloud.capabilities",space:ot,path:"",actions:[rt.READ]}]),At=xt(dt),It={...At,resources:[...At.resources,...Rt.map(e=>({...e,actions:[...e.actions]}))]},St=Object.freeze(Object.fromEntries(yt.map(e=>[e,e===dt?It:xt(e)]))),Dt=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[pt]}]);function Pt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Ut(e,...t){if(!Pt(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Lt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ct(e,t){Ut(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Kt(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function $t(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Bt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}Object.freeze(yt.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:St[e].resources,...e===ot?{rawAbilities:Dt}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[st.HOST]}]));const Vt=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function qt(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Pt(e))throw new Error("Uint8Array expected, got "+typeof e);e=Ht(e)}return e}const Ft=(e,t)=>{function r(r,...n){if(Ut(r),!Vt)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?Ut(t):Ut(t,e.nonceLength)}const s=e.tagLength;s&&void 0!==n[1]&&Ut(n[1]);const i=t(r,...n),a=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Ut(t)}};let o=!1;return{encrypt(e,t){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Ut(e),a(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(Ut(e),s&&e.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(r,e),r};function Mt(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),a=Number(r>>s&i),o=Number(r&i),c=n?4:0,u=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+u,o,n)}function jt(e){return e.byteOffset%4==0}function Ht(e){return Uint8Array.from(e)}const Zt=16,Wt=new Uint8Array(16),zt=Kt(Wt),Gt=(e,t,r,n)=>({s3:r<<31|n>>>1,s2:t<<31|r>>>1,s1:e<<31|t>>>1,s0:e>>>1^225<<24&-(1&n)}),Jt=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Yt{constructor(e,t){this.blockLen=Zt,this.outputLen=Zt,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,Ut(e=qt(e),16);const r=Bt(e);let n=r.getUint32(0,!1),s=r.getUint32(4,!1),i=r.getUint32(8,!1),a=r.getUint32(12,!1);const o=[];for(let e=0;e<128;e++)o.push({s0:Jt(n),s1:Jt(s),s2:Jt(i),s3:Jt(a)}),({s0:n,s1:s,s2:i,s3:a}=Gt(n,s,i,a));const c=(u=t||1024)>65536?8:u>1024?4:2;var u;if(![1,2,4,8].includes(c))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=c;const d=128/c,l=this.windowSize=2**c,h=[];for(let e=0;e<d;e++)for(let t=0;t<l;t++){let r=0,n=0,s=0,i=0;for(let a=0;a<c;a++){if(!(t>>>c-a-1&1))continue;const{s0:u,s1:d,s2:l,s3:h}=o[c*e+a];r^=u,n^=d,s^=l,i^=h}h.push({s0:r,s1:n,s2:s,s3:i})}this.t=h}_updateBlock(e,t,r,n){e^=this.s0,t^=this.s1,r^=this.s2,n^=this.s3;const{W:s,t:i,windowSize:a}=this;let o=0,c=0,u=0,d=0;const l=(1<<s)-1;let h=0;for(const f of[e,t,r,n])for(let e=0;e<4;e++){const t=f>>>8*e&255;for(let e=8/s-1;e>=0;e--){const r=t>>>s*e&l,{s0:n,s1:f,s2:p,s3:y}=i[h*a+r];o^=n,c^=f,u^=p,d^=y,h+=1}}this.s0=o,this.s1=c,this.s2=u,this.s3=d}update(e){Lt(this),Ut(e=qt(e));const t=Kt(e),r=Math.floor(e.length/Zt),n=e.length%Zt;for(let e=0;e<r;e++)this._updateBlock(t[4*e+0],t[4*e+1],t[4*e+2],t[4*e+3]);return n&&(Wt.set(e.subarray(r*Zt)),this._updateBlock(zt[0],zt[1],zt[2],zt[3]),$t(zt)),this}destroy(){const{t:e}=this;for(const t of e)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(e){Lt(this),Ct(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:s}=this,i=Kt(e);return i[0]=t,i[1]=r,i[2]=n,i[3]=s,e}digest(){const e=new Uint8Array(Zt);return this.digestInto(e),this.destroy(),e}}class Qt extends Yt{constructor(e,t){Ut(e=qt(e));const r=function(e){e.reverse();const t=1&e[15];let r=0;for(let t=0;t<e.length;t++){const n=e[t];e[t]=n>>>1|r,r=(1&n)<<7}return e[0]^=225&-t,e}(Ht(e));super(r,t),$t(r)}update(e){e=qt(e),Lt(this);const t=Kt(e),r=e.length%Zt,n=Math.floor(e.length/Zt);for(let e=0;e<n;e++)this._updateBlock(Jt(t[4*e+3]),Jt(t[4*e+2]),Jt(t[4*e+1]),Jt(t[4*e+0]));return r&&(Wt.set(e.subarray(n*Zt)),this._updateBlock(Jt(zt[3]),Jt(zt[2]),Jt(zt[1]),Jt(zt[0])),$t(zt)),this}digestInto(e){Lt(this),Ct(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:s}=this,i=Kt(e);return i[0]=t,i[1]=r,i[2]=n,i[3]=s,e.reverse()}}function Xt(e){const t=(t,r)=>e(r,t.length).update(qt(t)).digest(),r=e(new Uint8Array(16),0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=(t,r)=>e(t,r),t}const er=Xt((e,t)=>new Yt(e,t)),tr=(Xt((e,t)=>new Qt(e,t)),16),rr=new Uint8Array(tr);function nr(e){return e<<1^283&-(e>>7)}function sr(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=nr(e);return r}const ir=e=>e<<24|e>>>8,ar=e=>e<<8|e>>>24;function or(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const r=new Uint32Array(256).map((r,n)=>t(e[n])),n=r.map(ar),s=n.map(ar),i=s.map(ar),a=new Uint32Array(65536),o=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let u=0;u<256;u++){const d=256*t+u;a[d]=r[t]^n[u],o[d]=s[t]^i[u],c[d]=e[t]<<8|e[u]}return{sbox:e,sbox2:c,T0:r,T1:n,T2:s,T3:i,T01:a,T23:o}}const cr=or((()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=nr(r))e[t]=r;const t=new Uint8Array(256);t[0]=99;for(let r=0;r<255;r++){let n=e[255-r];n|=n<<8,t[e[r]]=255&(n^n>>4^n>>5^n>>6^n>>7^99)}return $t(e),t})(),e=>sr(e,3)<<24|e<<16|e<<8|sr(e,2)),ur=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=nr(r))e[t]=r;return e})();function dr(e,t,r,n,s,i){return e[r<<8&65280|n>>>8&255]^t[s>>>8&65280|i>>>24&255]}function lr(e,t,r,n,s){return e[255&t|65280&r]|e[n>>>16&255|s>>>16&65280]<<16}function hr(e,t,r,n,s){const{sbox2:i,T01:a,T23:o}=cr;let c=0;t^=e[c++],r^=e[c++],n^=e[c++],s^=e[c++];const u=e.length/4-2;for(let i=0;i<u;i++){const i=e[c++]^dr(a,o,t,r,n,s),u=e[c++]^dr(a,o,r,n,s,t),d=e[c++]^dr(a,o,n,s,t,r),l=e[c++]^dr(a,o,s,t,r,n);t=i,r=u,n=d,s=l}return{s0:e[c++]^lr(i,t,r,n,s),s1:e[c++]^lr(i,r,n,s,t),s2:e[c++]^lr(i,n,s,t,r),s3:e[c++]^lr(i,s,t,r,n)}}function fr(e,t,r,n,s){Ut(r,tr),Ut(n),s=function(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&!jt(t))throw new Error("invalid output, must be aligned");return t}(n.length,s);const i=r,a=Kt(i),o=Bt(i),c=Kt(n),u=Kt(s),d=t?0:12,l=n.length;let h=o.getUint32(d,t),{s0:f,s1:p,s2:y,s3:m}=hr(e,a[0],a[1],a[2],a[3]);for(let r=0;r+4<=c.length;r+=4)u[r+0]=c[r+0]^f,u[r+1]=c[r+1]^p,u[r+2]=c[r+2]^y,u[r+3]=c[r+3]^m,h=h+1>>>0,o.setUint32(d,h,t),({s0:f,s1:p,s2:y,s3:m}=hr(e,a[0],a[1],a[2],a[3]));const g=tr*Math.floor(c.length/4);if(g<l){const e=new Uint32Array([f,p,y,m]),t=(v=e,new Uint8Array(v.buffer,v.byteOffset,v.byteLength));for(let e=g,r=0;e<l;e++,r++)s[e]=n[e]^t[r];$t(e)}var v;return s}function pr(e,t,r,n,s){const i=s?s.length:0,a=e.create(r,n.length+i);s&&a.update(s);const o=function(e,t,r){!function(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}(r);const n=new Uint8Array(16),s=Bt(n);return Mt(s,0,BigInt(t),r),Mt(s,8,BigInt(e),r),n}(8*n.length,8*i,t);a.update(n),a.update(o);const c=a.digest();return $t(o),c}const yr=Ft({blockSize:16,nonceLength:12,tagLength:16,varSizeNonce:!0},function(e,t,r){if(t.length<8)throw new Error("aes/gcm: invalid nonce length");function n(e,t,n){const s=pr(er,!1,e,n,r);for(let e=0;e<t.length;e++)s[e]^=t[e];return s}function s(){const r=function(e){Ut(e);const t=e.length;if(![16,24,32].includes(t))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+t);const{sbox2:r}=cr,n=[];jt(e)||n.push(e=Ht(e));const s=Kt(e),i=s.length,a=e=>lr(r,e,e,e,e),o=new Uint32Array(t+28);o.set(s);for(let e=i;e<o.length;e++){let t=o[e-1];e%i===0?t=a(ir(t))^ur[e/i-1]:i>6&&e%i===4&&(t=a(t)),o[e]=o[e-i]^t}return $t(...n),o}(e),n=rr.slice(),s=rr.slice();if(fr(r,!1,s,s,n),12===t.length)s.set(t);else{const e=rr.slice();Mt(Bt(e),8,BigInt(8*t.length),!1);const r=er.create(n).update(t).update(e);r.digestInto(s),r.destroy()}return{xk:r,authKey:n,counter:s,tagMask:fr(r,!1,s,rr)}}return{encrypt(e){const{xk:t,authKey:r,counter:i,tagMask:a}=s(),o=new Uint8Array(e.length+16),c=[t,r,i,a];jt(e)||c.push(e=Ht(e)),fr(t,!1,i,e,o.subarray(0,e.length));const u=n(r,a,o.subarray(0,o.length-16));return c.push(u),o.set(u,e.length),$t(...c),o},decrypt(e){const{xk:t,authKey:r,counter:i,tagMask:a}=s(),o=[t,r,a,i];jt(e)||o.push(e=Ht(e));const c=e.subarray(0,-16),u=e.subarray(-16),d=n(r,a,c);if(o.push(d),!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(d,u))throw new Error("aes/gcm: invalid ghash tag");const l=fr(t,!1,i,c);return $t(...o),l}}}),mr=()=>"undefined"!=typeof globalThis&&globalThis.crypto?globalThis.crypto:"undefined"!=typeof window&&window.crypto?window.crypto:"undefined"!=typeof self&&self.crypto?self.crypto:void 0,gr={web:mr(),node:void 0,getRandomValues:function(e){const t=mr();if(t&&t.getRandomValues)return t.getRandomValues(e);throw new Error("crypto.getRandomValues is unavailable")}};function vr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function _r(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function kr(e,...t){if(!vr(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function wr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");_r(e.outputLen),_r(e.blockLen)}function Er(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function br(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Tr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Nr(e,t){return e<<32-t|e>>>t}const Or=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),xr=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Rr(e){if(kr(e),Or)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=xr[e[r]];return t}function Ar(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Ir(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Or)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=Ar(e.charCodeAt(s)),i=Ar(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}function Sr(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Dr(e){return"string"==typeof e&&(e=Sr(e)),kr(e),e}function Pr(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];kr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}class Ur{}function Lr(e){const t=t=>e().update(Dr(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Cr(e=32){if(gr&&"function"==typeof gr.getRandomValues)return gr.getRandomValues(new Uint8Array(e));if(gr&&"function"==typeof gr.randomBytes)return Uint8Array.from(gr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Kr(e,t,r){return e&t^~e&r}function $r(e,t,r){return e&t^e&r^t&r}class Br extends Ur{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Tr(this.buffer)}update(e){Er(this),kr(e=Dr(e));const{view:t,buffer:r,blockLen:n}=this,s=e.length;for(let i=0;i<s;){const a=Math.min(n-this.pos,s-i);if(a===n){const t=Tr(e);for(;n<=s-i;i+=n)this.process(t,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Er(this),function(e,t){kr(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:s}=this;let{pos:i}=this;t[i++]=128,br(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),a=Number(r>>s&i),o=Number(r&i),c=n?4:0,u=n?0:4;e.setUint32(t+c,a,n),e.setUint32(t+u,o,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const a=Tr(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)a.setUint32(4*e,u[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=n,e.pos=a,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Vr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Fr=BigInt(2**32-1),Mr=BigInt(32);function jr(e,t=!1){return t?{h:Number(e&Fr),l:Number(e>>Mr&Fr)}:{h:0|Number(e>>Mr&Fr),l:0|Number(e&Fr)}}const Hr=(e,t,r)=>e>>>r,Zr=(e,t,r)=>e<<32-r|t>>>r,Wr=(e,t,r)=>e>>>r|t<<32-r,zr=(e,t,r)=>e<<32-r|t>>>r,Gr=(e,t,r)=>e<<64-r|t>>>r-32,Jr=(e,t,r)=>e>>>r-32|t<<64-r;function Yr(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}}const Qr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Xr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,en=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),tn=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,rn=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),nn=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,sn=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),an=new Uint32Array(64);class on extends Br{constructor(e=32){super(64,e,8,!1),this.A=0|Vr[0],this.B=0|Vr[1],this.C=0|Vr[2],this.D=0|Vr[3],this.E=0|Vr[4],this.F=0|Vr[5],this.G=0|Vr[6],this.H=0|Vr[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:i,G:a,H:o}=this;return[e,t,r,n,s,i,a,o]}set(e,t,r,n,s,i,a,o){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|i,this.G=0|a,this.H=0|o}process(e,t){for(let r=0;r<16;r++,t+=4)an[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=an[e-15],r=an[e-2],n=Nr(t,7)^Nr(t,18)^t>>>3,s=Nr(r,17)^Nr(r,19)^r>>>10;an[e]=s+an[e-7]+n+an[e-16]|0}let{A:r,B:n,C:s,D:i,E:a,F:o,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(Nr(a,6)^Nr(a,11)^Nr(a,25))+Kr(a,o,c)+sn[e]+an[e]|0,d=(Nr(r,2)^Nr(r,13)^Nr(r,22))+$r(r,n,s)|0;u=c,c=o,o=a,a=i+t|0,i=s,s=n,n=r,r=t+d|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,s,i,a,o,c,u)}roundClean(){br(an)}destroy(){this.set(0,0,0,0,0,0,0,0),br(this.buffer)}}const cn=(()=>function(e,t=!1){const r=e.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:r,l:a}=jr(e[i],t);[n[i],s[i]]=[r,a]}return[n,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),un=(()=>cn[0])(),dn=(()=>cn[1])(),ln=new Uint32Array(80),hn=new Uint32Array(80);class fn extends Br{constructor(e=64){super(128,e,16,!1),this.Ah=0|qr[0],this.Al=0|qr[1],this.Bh=0|qr[2],this.Bl=0|qr[3],this.Ch=0|qr[4],this.Cl=0|qr[5],this.Dh=0|qr[6],this.Dl=0|qr[7],this.Eh=0|qr[8],this.El=0|qr[9],this.Fh=0|qr[10],this.Fl=0|qr[11],this.Gh=0|qr[12],this.Gl=0|qr[13],this.Hh=0|qr[14],this.Hl=0|qr[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:i,Dh:a,Dl:o,Eh:c,El:u,Fh:d,Fl:l,Gh:h,Gl:f,Hh:p,Hl:y}=this;return[e,t,r,n,s,i,a,o,c,u,d,l,h,f,p,y]}set(e,t,r,n,s,i,a,o,c,u,d,l,h,f,p,y){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|i,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|u,this.Fh=0|d,this.Fl=0|l,this.Gh=0|h,this.Gl=0|f,this.Hh=0|p,this.Hl=0|y}process(e,t){for(let r=0;r<16;r++,t+=4)ln[r]=e.getUint32(t),hn[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ln[e-15],r=0|hn[e-15],n=Wr(t,r,1)^Wr(t,r,8)^Hr(t,0,7),s=zr(t,r,1)^zr(t,r,8)^Zr(t,r,7),i=0|ln[e-2],a=0|hn[e-2],o=Wr(i,a,19)^Gr(i,a,61)^Hr(i,0,6),c=zr(i,a,19)^Jr(i,a,61)^Zr(i,a,6),u=en(s,c,hn[e-7],hn[e-16]),d=tn(u,n,o,ln[e-7],ln[e-16]);ln[e]=0|d,hn[e]=0|u}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:a,Cl:o,Dh:c,Dl:u,Eh:d,El:l,Fh:h,Fl:f,Gh:p,Gl:y,Hh:m,Hl:g}=this;for(let e=0;e<80;e++){const t=Wr(d,l,14)^Wr(d,l,18)^Gr(d,l,41),v=zr(d,l,14)^zr(d,l,18)^Jr(d,l,41),_=d&h^~d&p,k=rn(g,v,l&f^~l&y,dn[e],hn[e]),w=nn(k,m,t,_,un[e],ln[e]),E=0|k,b=Wr(r,n,28)^Gr(r,n,34)^Gr(r,n,39),T=zr(r,n,28)^Jr(r,n,34)^Jr(r,n,39),N=r&s^r&a^s&a,O=n&i^n&o^i&o;m=0|p,g=0|y,p=0|h,y=0|f,h=0|d,f=0|l,({h:d,l}=Yr(0|c,0|u,0|w,0|E)),c=0|a,u=0|o,a=0|s,o=0|i,s=0|r,i=0|n;const x=Qr(E,T,O);r=Xr(x,w,b,N),n=0|x}({h:r,l:n}=Yr(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=Yr(0|this.Bh,0|this.Bl,0|s,0|i)),({h:a,l:o}=Yr(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=Yr(0|this.Dh,0|this.Dl,0|c,0|u)),({h:d,l}=Yr(0|this.Eh,0|this.El,0|d,0|l)),({h,l:f}=Yr(0|this.Fh,0|this.Fl,0|h,0|f)),({h:p,l:y}=Yr(0|this.Gh,0|this.Gl,0|p,0|y)),({h:m,l:g}=Yr(0|this.Hh,0|this.Hl,0|m,0|g)),this.set(r,n,s,i,a,o,c,u,d,l,h,f,p,y,m,g)}roundClean(){br(ln,hn)}destroy(){br(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const pn=Lr(()=>new on),yn=Lr(()=>new fn),mn=BigInt(0),gn=BigInt(1);function vn(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function _n(e,t,r=""){const n=vr(e),s=e?.length,i=void 0!==t;if(!n||i&&s!==t)throw new Error((r&&`"${r}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(n?`length=${s}`:"type="+typeof e));return e}function kn(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?mn:BigInt("0x"+e)}function wn(e){return kr(e),kn(Rr(Uint8Array.from(e).reverse()))}function En(e,t){return Ir(e.toString(16).padStart(2*t,"0"))}function bn(e,t){return En(e,t).reverse()}function Tn(e,t,r){let n;if("string"==typeof t)try{n=Ir(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!vr(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const s=n.length;if("number"==typeof r&&s!==r)throw new Error(e+" of length "+r+" expected, got "+s);return n}function Nn(e){return Uint8Array.from(e)}const On=e=>"bigint"==typeof e&&mn<=e;function xn(e,t,r,n){if(!function(e,t,r){return On(e)&&On(t)&&On(r)&&t<=e&&e<r}(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}const Rn=e=>(gn<<BigInt(e))-gn;function An(e,t,r={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function n(t,r,n){const s=e[t];if(n&&void 0===s)return;const i=typeof s;if(i!==r||null===s)throw new Error(`param "${t}" is invalid: expected ${r}, got ${i}`)}Object.entries(t).forEach(([e,t])=>n(e,t,!1)),Object.entries(r).forEach(([e,t])=>n(e,t,!0))}const In=()=>{throw new Error("not implemented")};function Sn(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(void 0!==s)return s;const i=e(r,...n);return t.set(r,i),i}}const Dn=BigInt(0),Pn=BigInt(1),Un=BigInt(2),Ln=BigInt(3),Cn=BigInt(4),Kn=BigInt(5),$n=BigInt(7),Bn=BigInt(8),Vn=BigInt(9),qn=BigInt(16);function Fn(e,t){const r=e%t;return r>=Dn?r:t+r}function Mn(e,t,r){let n=e;for(;t-- >Dn;)n*=n,n%=r;return n}function jn(e,t){if(e===Dn)throw new Error("invert: expected non-zero number");if(t<=Dn)throw new Error("invert: expected positive modulus, got "+t);let r=Fn(e,t),n=t,s=Dn,i=Pn,a=Pn,o=Dn;for(;r!==Dn;){const e=n/r,t=n%r,c=s-a*e,u=i-o*e;n=r,r=t,s=a,i=o,a=c,o=u}if(n!==Pn)throw new Error("invert: does not exist");return Fn(s,t)}function Hn(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Zn(e,t){const r=(e.ORDER+Pn)/Cn,n=e.pow(t,r);return Hn(e,n,t),n}function Wn(e,t){const r=(e.ORDER-Kn)/Bn,n=e.mul(t,Un),s=e.pow(n,r),i=e.mul(t,s),a=e.mul(e.mul(i,Un),s),o=e.mul(i,e.sub(a,e.ONE));return Hn(e,o,t),o}function zn(e){if(e<Ln)throw new Error("sqrt is not defined for small field");let t=e-Pn,r=0;for(;t%Un===Dn;)t/=Un,r++;let n=Un;const s=Xn(e);for(;1===Qn(s,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Zn;let i=s.pow(n,t);const a=(t+Pn)/Un;return function(e,n){if(e.is0(n))return n;if(1!==Qn(e,n))throw new Error("Cannot find square root");let s=r,o=e.mul(e.ONE,i),c=e.pow(n,t),u=e.pow(n,a);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,r=e.sqr(c);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===s)throw new Error("Cannot find square root");const n=Pn<<BigInt(s-t-1),i=e.pow(o,n);s=t,o=e.sqr(i),c=e.mul(c,o),u=e.mul(u,i)}return u}}const Gn=(e,t)=>(Fn(e,t)&Pn)===Pn,Jn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yn(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce((t,r,s)=>e.is0(r)?t:(n[s]=t,e.mul(t,r)),e.ONE),i=e.inv(s);return t.reduceRight((t,r,s)=>e.is0(r)?t:(n[s]=e.mul(t,n[s]),e.mul(t,r)),i),n}function Qn(e,t){const r=(e.ORDER-Pn)/Un,n=e.pow(t,r),s=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),a=e.eql(n,e.neg(e.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Xn(e,t,r=!1,n={}){if(e<=Dn)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,i,a,o=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modFromBytes&&(o=e.modFromBytes),a=e.allowedLengths}else"number"==typeof t&&(s=t),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:u}=function(e,t){void 0!==t&&_r(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}(e,s);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const l=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:Rn(c),ZERO:Dn,ONE:Pn,allowedLengths:a,create:t=>Fn(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Dn<=t&&t<e},is0:e=>e===Dn,isValidNot0:e=>!l.is0(e)&&l.isValid(e),isOdd:e=>(e&Pn)===Pn,neg:t=>Fn(-t,e),eql:(e,t)=>e===t,sqr:t=>Fn(t*t,e),add:(t,r)=>Fn(t+r,e),sub:(t,r)=>Fn(t-r,e),mul:(t,r)=>Fn(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Dn)throw new Error("invalid exponent, negatives unsupported");if(r===Dn)return e.ONE;if(r===Pn)return t;let n=e.ONE,s=t;for(;r>Dn;)r&Pn&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Pn;return n}(l,e,t),div:(t,r)=>Fn(t*jn(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>jn(t,e),sqrt:i||(t=>{return d||(d=(r=e)%Cn===Ln?Zn:r%Bn===Kn?Wn:r%qn===Vn?function(e){const t=Xn(e),r=zn(e),n=r(t,t.neg(t.ONE)),s=r(t,n),i=r(t,t.neg(n)),a=(e+$n)/qn;return(e,t)=>{let r=e.pow(t,a),o=e.mul(r,n);const c=e.mul(r,s),u=e.mul(r,i),d=e.eql(e.sqr(o),t),l=e.eql(e.sqr(c),t);r=e.cmov(r,o,d),o=e.cmov(u,c,l);const h=e.eql(e.sqr(o),t),f=e.cmov(r,o,h);return Hn(e,f,t),f}}(r):zn(r)),d(l,t);var r}),toBytes:e=>r?bn(e,u):En(e,u),fromBytes:(t,n=!0)=>{if(a){if(!a.includes(t.length)||t.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+t.length);const e=new Uint8Array(u);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+t.length);let s=r?wn(t):function(e){return kn(Rr(e))}(t);if(o&&(s=Fn(s,e)),!n&&!l.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Yn(l,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(l)}const es=BigInt(0),ts=BigInt(1);function rs(e,t){const r=t.negate();return e?r:t}function ns(e,t){const r=Yn(e.Fp,t.map(e=>e.Z));return t.map((t,n)=>e.fromAffine(t.toAffine(r[n])))}function ss(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function is(e,t){ss(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Rn(e),maxNumber:r,shiftBy:BigInt(e)}}function as(e,t,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:a}=r;let o=Number(e&s),c=e>>a;o>n&&(o-=i,c+=ts);const u=t*n;return{nextN:c,offset:u+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:t%2!=0,offsetF:u}}const os=new WeakMap,cs=new WeakMap;function us(e){return cs.get(e)||1}function ds(e){if(e!==es)throw new Error("invalid wNAF")}class ls{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>es;)t&ts&&(r=r.add(n)),n=n.double(),t>>=ts;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=is(t,this.bits),s=[];let i=e,a=i;for(let e=0;e<r;e++){a=i,s.push(a);for(let e=1;e<n;e++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,s=this.BASE;const i=is(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:d,offsetF:l}=as(r,e,i);r=a,c?s=s.add(rs(d,t[l])):n=n.add(rs(u,t[o]))}return ds(r),{p:n,f:s}}wNAFUnsafe(e,t,r,n=this.ZERO){const s=is(e,this.bits);for(let e=0;e<s.windows&&r!==es;e++){const{nextN:i,offset:a,isZero:o,isNeg:c}=as(r,e,s);if(r=i,!o){const e=t[a];n=n.add(c?e.negate():e)}}return ds(r),n}getPrecomputes(e,t,r){let n=os.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),os.set(t,n))),n}cached(e,t,r){const n=us(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const s=us(e);return 1===s?this._unsafeLadder(e,t,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),t,n)}createCache(e,t){ss(t,this.bits),cs.set(e,t),os.delete(e)}hasCache(e){return 1!==us(e)}}function hs(e,t,r,n){(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)})})(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)})}(n,t);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const a=e.ZERO,o=function(e){let t;for(t=0;e>mn;e>>=gn,t+=1);return t}(BigInt(s));let c=1;o>12?c=o-3:o>4?c=o-2:o>0&&(c=2);const u=Rn(c),d=new Array(Number(u)+1).fill(a);let l=a;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){d.fill(a);for(let t=0;t<i;t++){const s=n[t],i=Number(s>>BigInt(e)&u);d[i]=d[i].add(r[t])}let t=a;for(let e=d.length-1,r=a;e>0;e--)r=r.add(d[e]),t=t.add(r);if(l=l.add(t),0!==e)for(let e=0;e<c;e++)l=l.double()}return l}function fs(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){An(e,Jn.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return Xn(e,{isLE:r})}const ps=BigInt(0),ys=BigInt(1),ms=BigInt(2),gs=BigInt(8);class vs{constructor(e){this.ep=e}static fromBytes(e){In()}static fromHex(e){In()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Rr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}}function _s(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:Xn(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(e,function(e,t,r={}){if("function"!=typeof t)throw new Error('"hash" function param is required');An(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:s,Fp:i,Fn:a}=e,o=r.randomBytes||Cr,c=r.adjustScalarBytes||(e=>e),u=r.domain||((e,t,r)=>{if(vn(r,"phflag"),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function d(e){return a.create(wn(e))}function l(e){const{head:r,prefix:n,scalar:i}=function(e){const r=m.secretKey;e=Tn("private key",e,r);const n=Tn("hashed private key",t(e),2*r),s=c(n.slice(0,r));return{head:s,prefix:n.slice(r,2*r),scalar:d(s)}}(e),a=s.multiply(i),o=a.toBytes();return{head:r,prefix:n,scalar:i,point:a,pointBytes:o}}function h(e){return l(e).pointBytes}function f(e=Uint8Array.of(),...r){const s=Pr(...r);return d(t(u(s,Tn("context",e),!!n)))}const p={zip215:!0},y=i.BYTES,m={secretKey:y,publicKey:y,signature:2*y,seed:y};function g(e=o(m.seed)){return _n(e,m.seed,"seed")}const v={getExtendedPublicKey:l,randomSecretKey:g,isValidSecretKey:function(e){return vr(e)&&e.length===a.BYTES},isValidPublicKey:function(t,r){try{return!!e.fromBytes(t,r)}catch(e){return!1}},toMontgomery(t){const{y:r}=e.fromBytes(t),n=m.publicKey,s=32===n;if(!s&&57!==n)throw new Error("only defined for 25519 and 448");const a=s?i.div(ys+r,ys-r):i.div(r-ys,r+ys);return i.toBytes(a)},toMontgomerySecret(e){const r=m.secretKey;_n(e,r);const n=t(e.subarray(0,r));return c(n).subarray(0,r)},randomPrivateKey:g,precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=v.randomSecretKey(e);return{secretKey:t,publicKey:h(t)}},getPublicKey:h,sign:function(e,t,r={}){e=Tn("message",e),n&&(e=n(e));const{prefix:i,scalar:o,pointBytes:c}=l(t),u=f(r.context,i,e),d=s.multiply(u).toBytes(),h=f(r.context,d,c,e),p=a.create(u+h*o);if(!a.isValid(p))throw new Error("sign failed: invalid s");return _n(Pr(d,a.toBytes(p)),m.signature,"result")},verify:function(t,r,i,a=p){const{context:o,zip215:c}=a,u=m.signature;t=Tn("signature",t,u),r=Tn("message",r),i=Tn("publicKey",i,m.publicKey),void 0!==c&&vn(c,"zip215"),n&&(r=n(r));const d=u/2,l=t.subarray(0,d),h=wn(t.subarray(d,u));let y,g,v;try{y=e.fromBytes(i,c),g=e.fromBytes(l,c),v=s.multiplyUnsafe(h)}catch(e){return!1}if(!c&&y.isSmallOrder())return!1;const _=f(o,g.toBytes(),y.toBytes(),r);return g.add(y.multiplyUnsafe(_)).subtract(v).clearCofactor().is0()},utils:v,Point:e,lengths:m})}(function(e,t={}){const r=function(e,t,r={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const r=t[e];if(!("bigint"==typeof r&&r>es))throw new Error(`CURVE.${e} must be positive bigint`)}const s=fs(t.p,r.Fp,n),i=fs(t.n,r.Fn,n),a=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of a)if(!s.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:s,Fn:i}}("edwards",e,t,t.FpFnLE),{Fp:n,Fn:s}=r;let i=r.CURVE;const{h:a}=i;An(t,{},{uvRatio:"function"});const o=ms<<BigInt(8*s.BYTES)-ys,c=e=>n.create(e),u=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(e){return{isValid:!1,value:ps}}});if(!function(e,t,r,n){const s=e.sqr(r),i=e.sqr(n),a=e.add(e.mul(t.a,s),i),o=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(a,o)}(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(e,t,r=!1){return xn("coordinate "+e,t,r?ys:ps,o),t}function l(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const h=Sn((e,t)=>{const{X:r,Y:s,Z:i}=e,a=e.is0();null==t&&(t=a?gs:n.inv(i));const o=c(r*t),u=c(s*t),d=n.mul(i,t);if(a)return{x:ps,y:ys};if(d!==ys)throw new Error("invZ was invalid");return{x:o,y:u}}),f=Sn(e=>{const{a:t,d:r}=i;if(e.is0())throw new Error("bad point: ZERO");const{X:n,Y:s,Z:a,T:o}=e,u=c(n*n),d=c(s*s),l=c(a*a),h=c(l*l),f=c(u*t);if(c(l*c(f+d))!==c(h+c(r*c(u*d))))throw new Error("bad point: equation left != right (1)");if(c(n*s)!==c(a*o))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(e,t,r,n){this.X=d("x",e),this.Y=d("y",t),this.Z=d("z",r,!0),this.T=d("t",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};return d("x",t),d("y",r),new p(t,r,ys,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:s,d:a}=i;e=Nn(_n(e,r,"point")),vn(t,"zip215");const d=Nn(e),l=e[r-1];d[r-1]=-129&l;const h=wn(d),f=t?o:n.ORDER;xn("point.y",h,ps,f);const y=c(h*h),m=c(y-ys),g=c(a*y-s);let{isValid:v,value:_}=u(m,g);if(!v)throw new Error("bad point: invalid y coordinate");const k=(_&ys)===ys,w=!!(128&l);if(!t&&_===ps&&w)throw new Error("bad point: x=0 and x_0=1");return w!==k&&(_=c(-_)),p.fromAffine({x:_,y:h})}static fromHex(e,t=!1){return p.fromBytes(Tn("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return y.createCache(this,e),t||this.multiply(ms),this}assertValidity(){f(this)}equals(e){l(e);const{X:t,Y:r,Z:n}=this,{X:s,Y:i,Z:a}=e,o=c(t*a),u=c(s*n),d=c(r*a),h=c(i*n);return o===u&&d===h}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=i,{X:t,Y:r,Z:n}=this,s=c(t*t),a=c(r*r),o=c(ms*c(n*n)),u=c(e*s),d=t+r,l=c(c(d*d)-s-a),h=u+a,f=h-o,y=u-a,m=c(l*f),g=c(h*y),v=c(l*y),_=c(f*h);return new p(m,g,_,v)}add(e){l(e);const{a:t,d:r}=i,{X:n,Y:s,Z:a,T:o}=this,{X:u,Y:d,Z:h,T:f}=e,y=c(n*u),m=c(s*d),g=c(o*r*f),v=c(a*h),_=c((n+s)*(u+d)-y-m),k=v-g,w=v+g,E=c(m-t*y),b=c(_*k),T=c(w*E),N=c(_*E),O=c(k*w);return new p(b,T,O,N)}subtract(e){return this.add(e.negate())}multiply(e){if(!s.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:r}=y.cached(this,e,e=>ns(p,e));return ns(p,[t,r])[0]}multiplyUnsafe(e,t=p.ZERO){if(!s.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===ps?p.ZERO:this.is0()||e===ys?this:y.unsafe(this,e,e=>ns(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return y.unsafe(this,i.n).is0()}toAffine(e){return h(this,e)}clearCofactor(){return a===ys?this:this.multiplyUnsafe(a)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&ys?128:0,r}toHex(){return Rr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return ns(p,e)}static msm(e,t){return hs(p,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,ys,c(i.Gx*i.Gy)),p.ZERO=new p(ps,ys,ys,ps),p.Fp=n,p.Fn=s;const y=new ls(p,s.BITS);return p.BASE.precompute(8),p}(t,r),n,s))}Sr("HashToScalar-");const ks=BigInt(0),ws=BigInt(1),Es=BigInt(2);const bs=BigInt(0),Ts=BigInt(1),Ns=BigInt(2),Os=BigInt(3),xs=BigInt(5),Rs=BigInt(8),As=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Is=(()=>({p:As,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Rs,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ss(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),i=As,a=e*e%i*e%i,o=Mn(a,Ns,i)*a%i,c=Mn(o,Ts,i)*e%i,u=Mn(c,xs,i)*c%i,d=Mn(u,t,i)*u%i,l=Mn(d,r,i)*d%i,h=Mn(l,n,i)*l%i,f=Mn(h,s,i)*h%i,p=Mn(f,s,i)*h%i,y=Mn(p,t,i)*u%i;return{pow_p_5_8:Mn(y,Ns,i)*e%i,b2:a}}function Ds(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ps=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Us(e,t){const r=As,n=Fn(t*t*t,r),s=Fn(n*n*t,r);let i=Fn(e*n*Ss(e*s).pow_p_5_8,r);const a=Fn(t*i*i,r),o=i,c=Fn(i*Ps,r),u=a===e,d=a===Fn(-e,r),l=a===Fn(-e*Ps,r);return u&&(i=o),(d||l)&&(i=c),Gn(i,r)&&(i=Fn(-i,r)),{isValid:u||d,value:i}}const Ls=(()=>Xn(Is.p,{isLE:!0}))(),Cs=(()=>Xn(Is.n,{isLE:!0}))(),Ks=(()=>({...Is,Fp:Ls,hash:yn,adjustScalarBytes:Ds,uvRatio:Us}))(),$s=(()=>_s(Ks))(),Bs=(()=>{const e=Ls.ORDER;return function(e){const t=(An(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r}));var r;const{P:n,type:s,adjustScalarBytes:i,powPminus2:a,randomBytes:o}=t,c="x25519"===s;if(!c&&"x448"!==s)throw new Error("invalid type");const u=o||Cr,d=c?255:448,l=c?32:56,h=c?BigInt(9):BigInt(5),f=c?BigInt(121665):BigInt(39081),p=c?Es**BigInt(254):Es**BigInt(447),y=c?BigInt(8)*Es**BigInt(251)-ws:BigInt(4)*Es**BigInt(445)-ws,m=p+y+ws,g=e=>Fn(e,n),v=_(h);function _(e){return bn(g(e),l)}function k(e,t){const r=function(e,t){xn("u",e,ks,n),xn("scalar",t,p,m);const r=t,s=e;let i=ws,o=ks,c=e,u=ws,l=ks;for(let e=BigInt(d-1);e>=ks;e--){const t=r>>e&ws;l^=t,({x_2:i,x_3:c}=E(l,i,c)),({x_2:o,x_3:u}=E(l,o,u)),l=t;const n=i+o,a=g(n*n),d=i-o,h=g(d*d),p=a-h,y=c+u,m=g((c-u)*n),v=g(y*d),_=m+v,k=m-v;c=g(_*_),u=g(s*g(k*k)),i=g(a*h),o=g(p*(a+g(f*p)))}({x_2:i,x_3:c}=E(l,i,c)),({x_2:o,x_3:u}=E(l,o,u));const h=a(o);return g(i*h)}(function(e){const t=Tn("u coordinate",e,l);return c&&(t[31]&=127),g(wn(t))}(t),function(e){return wn(i(Tn("scalar",e,l)))}(e));if(r===ks)throw new Error("invalid private or public key received");return _(r)}function w(e){return k(e,v)}function E(e,t,r){const n=g(e*(t-r));return{x_2:t=g(t-n),x_3:r=g(r+n)}}const b={secretKey:l,publicKey:l,seed:l},T=(e=u(l))=>(kr(e,b.seed),e);return{keygen:function(e){const t=T(e);return{secretKey:t,publicKey:w(t)}},getSharedSecret:(e,t)=>k(e,t),getPublicKey:e=>w(e),scalarMult:k,scalarMultBase:w,utils:{randomSecretKey:T,randomPrivateKey:T},GuBytes:v.slice(),lengths:b}}({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:r,b2:n}=Ss(t);return Fn(Mn(r,Os,e)*n,e)},adjustScalarBytes:Ds})})(),Vs=Ps,qs=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Fs=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Ms=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),js=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Hs=e=>Us(Ts,e),Zs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ws=e=>$s.Point.Fp.create(wn(e)&Zs);function zs(e){const{d:t}=Is,r=As,n=e=>Ls.create(e),s=n(Vs*e*e),i=n((s+Ts)*Ms);let a=BigInt(-1);const o=n((a-t*s)*n(s+t));let{isValid:c,value:u}=Us(i,o),d=n(u*e);Gn(d,r)||(d=n(-d)),c||(u=d),c||(a=s);const l=n(a*(s-Ts)*js-o),h=u*u,f=n((u+u)*o),p=n(l*qs),y=n(Ts-h),m=n(Ts+h);return new $s.Point(n(f*m),n(y*p),n(p*m),n(f*y))}class Gs extends vs{constructor(e){super(e)}static fromAffine(e){return new Gs($s.Point.fromAffine(e))}assertSame(e){if(!(e instanceof Gs))throw new Error("RistrettoPoint expected")}init(e){return new Gs(e)}static hashToCurve(e){return function(e){kr(e,64);const t=zs(Ws(e.subarray(0,32))),r=zs(Ws(e.subarray(32,64)));return new Gs(t.add(r))}(Tn("ristrettoHash",e,64))}static fromBytes(e){kr(e,32);const{a:t,d:r}=Is,n=As,s=e=>Ls.create(e),i=Ws(e);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(Ls.toBytes(i),e)||Gn(i,n))throw new Error("invalid ristretto255 encoding 1");const a=s(i*i),o=s(Ts+t*a),c=s(Ts-t*a),u=s(o*o),d=s(c*c),l=s(t*r*u-d),{isValid:h,value:f}=Hs(s(l*d)),p=s(f*c),y=s(f*p*l);let m=s((i+i)*p);Gn(m,n)&&(m=s(-m));const g=s(o*y),v=s(m*g);if(!h||Gn(v,n)||g===bs)throw new Error("invalid ristretto255 encoding 2");return new Gs(new $s.Point(m,g,Ts,v))}static fromHex(e){return Gs.fromBytes(Tn("ristrettoHex",e,32))}static msm(e,t){return hs(Gs,$s.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep;const s=As,i=e=>Ls.create(e),a=i(i(r+t)*i(r-t)),o=i(e*t),c=i(o*o),{value:u}=Hs(i(a*c)),d=i(u*a),l=i(u*o),h=i(d*l*n);let f;if(Gn(n*h,s)){let r=i(t*Vs),n=i(e*Vs);e=r,t=n,f=i(d*Fs)}else f=l;Gn(e*h,s)&&(t=i(-t));let p=i((r-t)*f);return Gn(p,s)&&(p=i(-p)),Ls.toBytes(p)}equals(e){this.assertSame(e);const{X:t,Y:r}=this.ep,{X:n,Y:s}=e.ep,i=e=>Ls.create(e),a=i(t*s)===i(r*n),o=i(r*s)===i(t*n);return a||o}is0(){return this.equals(Gs.ZERO)}}Gs.BASE=(()=>new Gs($s.Point.BASE))(),Gs.ZERO=(()=>new Gs($s.Point.ZERO))(),Gs.Fp=(()=>Ls)(),Gs.Fn=(()=>Cs)();class Js extends Ur{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,wr(e);const r=Dr(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),br(s)}update(e){return Er(this),this.iHash.update(e),this}digestInto(e){Er(this),kr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:i,outputLen:a}=this;return e.finished=n,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ys=(e,t,r)=>new Js(e,t).update(r).digest();Ys.create=(e,t)=>new Js(e,t);const Qs=Uint8Array.from([0]),Xs=Uint8Array.of(),ei=(e,t,r,n,s)=>function(e,t,r,n=32){wr(e),_r(n);const s=e.outputLen;if(n>255*s)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/s);void 0===r&&(r=Xs);const a=new Uint8Array(i*s),o=Ys.create(e,t),c=o._cloneInto(),u=new Uint8Array(o.outputLen);for(let e=0;e<i;e++)Qs[0]=e+1,c.update(0===e?Xs:u).update(r).update(Qs).digestInto(u),a.set(u,s*e),o._cloneInto(c);return o.destroy(),c.destroy(),br(u,Qs),a.slice(0,n)}(e,function(e,t,r){return wr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Ys(e,Dr(r),Dr(t))}(e,t,r),n,s),ti=pn;var ri=s(4290),ni={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"};function si(e){return{ok:!0,data:e}}function ii(e){return{ok:!1,error:e}}function ai(e,t,r,n){return{code:e,message:t,service:r,cause:n?.cause,meta:n?.meta}}var oi="[REDACTED]",ci=new Set(["duration","durationMs","endedAt","startedAt","status","timestamp","latencyMs","stalenessMs","count","changes","deleted","fetched","pages","lagMs","pendingCleared","partitions","remaining","expiryMs"]),ui=new Set(["authenticated","ok","persisted","purgePending"]),di={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 li(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function hi(e,t){try{return e[t]}catch{return oi}}function fi(e){if(null==e)return e;if("object"!=typeof e)return oi;try{if(function(e){try{return Array.isArray(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}catch{return!0}}(e))return oi;const t={};for(const r of ci){const n=li(hi(e,r));void 0!==n&&(t[r]=n)}for(const r of ui){const n=hi(e,r);"boolean"==typeof n&&(t[r]=n)}for(const[r,n]of Object.entries(di)){const s=hi(e,r);"string"==typeof s&&n.includes(s)&&(t[r]=s)}void 0!==hi(e,"url")&&(t.url=oi);const r=hi(e,"error");return void 0!==r&&(t.error=function(e){if("object"!=typeof e||null===e)return{};const t=li(hi(e,"status"));return void 0!==t&&t>=100&&t<=599?{status:t}:{}}(r)),t}catch{return oi}}var pi="TinyCloud_debug";function yi(){return globalThis}function mi(){const e=globalThis.performance?.now?.bind(globalThis.performance);return"function"==typeof e?e():Date.now()}function gi(e){return!0===e||"true"===e||"1"===e}function vi(){const e=globalThis.process;return e?.env?.[pi]}function _i(){if(yi().window===globalThis)try{return globalThis.localStorage}catch{return}}function ki(e){const t=_i();if(t)try{e?t.setItem(pi,"true"):t.removeItem(pi)}catch{}}var wi=new class{constructor(){this.enabled=gi(yi()[pi])||gi(function(){const e=_i();if(e)try{return e.getItem(pi)}catch{return}}())||gi(vi()),this.sequence=0,this.events=[],this.maxEvents=1e3}isEnabled(){return this.enabled||gi(yi()[pi])||gi(vi())}enable(e={}){this.enabled=!0,yi()[pi]=!0,!1!==e.persist&&ki(!0),this.log("debug.enabled",{persisted:!1!==e.persist})}disable(e={}){this.log("debug.disabled",{persisted:!1!==e.persist}),this.enabled=!1,yi()[pi]=!1,!1!==e.persist&&ki(!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=mi();return this.log(`${e}.start`,t),{stop:t=>{const n=mi();return this.record({event:`${e}.end`,data:t,durationMs:n-r,startedAt:r,endedAt:n,level:"debug",timestamp:Date.now(),timestampIso:(new Date).toISOString()})}}}async timeAsync(e,t,r){if(!this.isEnabled())return t();const n=this.startTimer(e,r);try{const e=await t();return n.stop({ok:!0}),e}catch(e){throw n.stop({ok:!1,error:e}),e}}time(e,t,r){if(!this.isEnabled())return t();const n=this.startTimer(e,r);try{const e=t();return n.stop({ok:!0}),e}catch(e){throw n.stop({ok:!1,error:e}),e}}record(e){const t={...e,...void 0===e.data?{}:{data:fi(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 Ei(e){return wi.enable(e),wi}function bi(e){return wi.disable(e),wi}function Ti(){return wi.getLogs()}function Ni(){wi.clear()}!function(){const e=yi();e.TinyCloudDebug=wi,e.enableTinyCloudDebug=Ei,e.disableTinyCloudDebug=bi,e.getTinyCloudDebugLogs=Ti,e.clearTinyCloudDebugLogs=Ni}();var Oi=Fe({code:Ke(),message:Ke(),service:Ke(),cause:Ve().optional(),meta:Fe({}).passthrough().optional()});function xi(e,t=Oi){return Me("ok",[Fe({ok:He(!0),data:e}),Fe({ok:He(!1),error:t})])}xi(Ve(),Oi);var Ri,Ai=Fe({etag:Ke().optional(),contentType:Ke().optional(),lastModified:Ke().optional(),contentLength:$e().optional()});function Ii(e){try{return JSON.parse(e)}catch{return{}}}function Si(e,t,r,n,s){return s.message?Pi(s.message):/<!doctype html/i.test(i=n)||/<html[\s>]/i.test(i)?524===r||/524\s*[:-]/i.test(n)||/a timeout occurred/i.test(n)?`${e} ${t} failed: upstream request timed out. Please retry.`:`${e} ${t} failed: upstream service returned an HTML error page (${r}).`:`${e} ${t} failed: ${r} - ${Pi(n)}`;var i}function Di(e,t,r){const n={status:e,statusText:t},s=Pi(r);return s&&(n.responseSnippet=s.slice(0,300)),n}function Pi(e){const t=e.replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,500)}...`:t}Ri=Ve(),Fe({data:Ri,headers:Ai}),xi(Fe({keys:qe(Ke()),truncated:Be().optional(),nextCursor:Ke().optional()})),Fe({service:Ke(),action:Ke(),span:Ke().optional(),key:Ke().optional(),timestamp:$e()}),Fe({service:Ke(),action:Ke(),span:Ke().optional(),ok:Be(),duration:$e(),durationMs:$e().optional(),status:$e().optional()}),Fe({service:Ke(),span:Ke().optional(),error:Oi}),Fe({service:Ke(),attempt:$e().int().positive(),maxAttempts:$e().int().positive(),error:Oi}),Fe({span:Ke(),ok:Be(),durationMs:$e(),service:Ke().optional(),action:Ke().optional(),status:$e().optional(),error:Oi.optional()}),Fe({maxAttempts:$e().int().positive(),backoff:Ze(["none","linear","exponential"]),baseDelayMs:$e().nonnegative(),maxDelayMs:$e().nonnegative(),retryableErrors:qe(Ke()),maxTotalMs:$e().positive().optional()}),Fe({delegationHeader:Fe({Authorization:Ke()}),delegationCid:Ke(),spaceId:Ke(),verificationMethod:Ke(),jwk:Fe({}).passthrough()});var Ui="urn:tinycloud:encryption:",Li=/^[a-z0-9][a-z0-9-]*$/,Ci=/^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/,Ki=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function $i(e){if("string"!=typeof e||0===e.length)throw new Ki("networkId must be a non-empty string");if(!e.startsWith(Ui))throw new Ki(`networkId must start with ${Ui} (got ${JSON.stringify(e)})`);const t=e.slice(25),r=t.lastIndexOf(":");if(r<=0||r===t.length-1)throw new Ki(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const n=t.slice(0,r),s=t.slice(r+1);if(!n.startsWith("did:"))throw new Ki(`networkId ownerDid must be a DID (got ${JSON.stringify(n)})`);const i=n.split(":");if(i.length<3||i.some(e=>0===e.length))throw new Ki(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(n)})`);if(!Li.test(s))throw new Ki(`networkId name ${JSON.stringify(s)} must match ${Li.source}`);return{networkId:e,ownerDid:n,name:s}}function Bi(e){const t=e.lastIndexOf(":"),r=e.slice(t+1),n=r.indexOf("/"),s=-1===n?r:r.slice(0,n),i=$i(-1===n?e:`${e.slice(0,t+1)}${s}`);if(-1===n)return i;const a=r.slice(n+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 Ki(`encryption resource has an invalid keyPath (got ${JSON.stringify(e)})`);return{...i,keyPath:a}}function Vi(e){const t=e.match(Ci);return t?{chainId:t[1],address:t[2].toLowerCase()}:null}function qi(e,t){const r=Vi(e),n=Vi(t);return r&&n?r.chainId===n.chainId&&r.address===n.address:e===t}var Fi=Symbol(),Mi=new WeakMap;function ji(e,t){return e===Fi||"Invocation expired or not yet valid"===t.trim()?{invocationTimeRefused:!0}:void 0===e?void 0:{invocationProofCid:e}}Error,Error,Error,Error;var Hi={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 Zi(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(Hi,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 Wi(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 n="string"==typeof t.space?t.space:void 0;return{service:t.service,...void 0===n?{}:{space:n},path:t.path,actions:[t.actions[0]]}}function zi(e){return{code:ni.AUTH_REQUIRED,message:"Authentication required. Please sign in first.",service:e}}function Gi(e,t,r,n){const s=n.trim(),[,i,a]=/^([a-z_]+)(?::\s*([a-z_]+):)?/.exec(s)??[];let o;if(503!==r.status||"sql_busy"!==i&&"unavailable_retryable"!==i&&"read_audit_busy"!==i)if(503===r.status&&"request_timeout"===i)o=ni.REQUEST_TIMEOUT;else{if(500!==r.status||"outcome_unknown"!==i)return;o=ni.OUTCOME_UNKNOWN}else o=ni.NODE_BUSY;const c=o!==ni.OUTCOME_UNKNOWN,u=r.headers.get("retry-after")?.trim();return ai(o,t,e,{meta:{...Di(r.status,r.statusText,n),retryable:c,..."sql_busy"===i&&a?{stage:a}:{},...c&&u&&/^\d{1,9}$/.test(u)?{retryAfterMs:1e3*Number(u)}:{}}})}var Ji=class extends Error{constructor(e){super(`Request timed out after ${e}ms.`),this.name="TimeoutError",this.timeoutMs=e}};function Yi(e){return e instanceof Ji||e instanceof Error&&"TimeoutError"===e.name&&"number"==typeof e.timeoutMs}function Qi(e,t,r){return void 0===t?{code:ni.TIMEOUT,message:"Request timed out.",service:e,...void 0===r?{}:{cause:r}}:{code:ni.TIMEOUT,message:`Request timed out after ${t}ms.`,service:e,...void 0===r?{}:{cause:r},meta:{timeoutMs:t}}}function Xi(e){const t=e.match(/^Unauthorized Action:\s*(.+?)\s*\/\s*(tinycloud\.\S+)$/m);return t?{resource:t[1].trim(),action:t[2].trim()}:{}}var ea=new Set(it.map(({urn:e})=>e).filter(e=>!e.endsWith("/*"))),ta=new Set(it.map(({service:e})=>e.slice(10)));function ra(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 $i(e),!0}catch{return!1}}const n=function(e,t){if(0===e.length||e.length>1024||!ta.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 n=r.findIndex((e,t)=>t>0&&ta.has(e));if(n<1||r[n]!==t)return;if(r.slice(1,n).some(e=>0===e.length||"."===e||".."===e))return;const s=r.slice(n+1);return s.some(e=>"."===e||".."===e)||"kv"!==t&&(0===s.length||""===s[s.length-1])?void 0:{space:r.slice(0,n).join("/"),path:s.join("/")}}(e,t);return void 0!==n&&(!n.path.endsWith("/")||"kv"===t&&"tinycloud.kv/list"===r)&&(""!==n.path||"kv"===t&&"tinycloud.kv/list"===r)}function na(e){const t=aa(e);if("unauthenticated"!==t&&"forbidden"!==t)return;const r=new Set;let n=e;for(let e=0;e<sa&&"object"==typeof n&&null!==n&&!r.has(n);e+=1){r.add(n);const e=n,t=ia(e),s=e.meta;if((401===t||403===t||void 0===t&&e.code===ni.AUTH_UNAUTHORIZED)&&"object"==typeof s&&null!==s&&!Array.isArray(s)){const t=s,{resource:r,requiredAction:n}=t;if("string"==typeof n&&ea.has(n)){const s=n.slice(10,n.indexOf("/")),i=void 0===e.service?t.service:e.service;if(ra(r,s,n)&&(void 0===i||i===s||i===`tinycloud.${s}`))return{resource:r,requiredAction:n}}}n=e.cause}}var sa=8;function ia(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 aa(e){const t=new Set;let r=!1,n=e;for(let e=0;e<sa&&"object"==typeof n&&null!==n&&!t.has(n);e+=1){t.add(n);const e=n,s=ia(e);if(401===s)return"unauthenticated";if(403===s)return"forbidden";if(void 0!==s)return"other";e.code===ni.AUTH_UNAUTHORIZED&&(r=!0),n=e.cause}return r?"forbidden":void 0}function oa(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 ca={storage_quota_exceeded:!0,storage_limit_reached:!0};function ua(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=0}function da(e){if("object"!=typeof e||null===e)return;const{usedBytes:t,limitBytes:r}=e;return ua(t)&&ua(r)?{usedBytes:t,limitBytes:r}:void 0}function la(e){let t;try{t=JSON.parse(e)}catch{return oa(e)}if("object"!=typeof t||null===t)return;const r=t,n="string"==typeof r.message?r.message:"",s=da(r.space)??oa(n),i="string"==typeof r.error&&!0===ca[r.error];if(!s&&!i)return;const a={...s},o=da(r.account);if(o){const e=r.account.plan;a.account="string"==typeof e&&""!==e?{...o,plan:e}:o}return a}function ha(e,t,r,n){const s={...r,...la(n)};return 402===t?function(e,t,r){return{code:ni.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,s):function(e,t,r){return{code:ni.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,s)}function fa(e,t,r=ni.NETWORK_ERROR){const n=Zi(t);return n?{...n,service:e}:t instanceof Error?Yi(t)?Qi(e,t.timeoutMs,t):"AbortError"===t.name?function(e){return{code:ni.ABORTED,message:"Request was aborted.",service:e}}(e):"TimeoutError"===t.name||t.message.toLowerCase().includes("timeout")?Qi(e):{code:r,message:t.message,service:e,cause:t}:{code:r,message:String(t),service:e}}var pa=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,n){const s=this.getServiceName(),i=Date.now()-r,a=this.spanName(e);this.emit("service.response",{service:s,action:e,span:a,ok:t,duration:i,durationMs:i,status:n}),this.emit("telemetry.span",{span:a,service:s,action:e,ok:t,durationMs:i,status:n})}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,...n}={}){const s=()=>{const e=t();return{method:"POST",...n,headers:Array.isArray(e)?[...e,...Object.entries(r??{})]:{...e,...r}}};return this.context.invokeWithRetry?this.context.invokeWithRetry(e,s):this.context.fetch(e,s())}createRequestSignal(e,t){const r=new AbortController,n=[];let s;const i=()=>{void 0!==s&&(clearTimeout(s),s=void 0);for(const e of n.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}),n.push(()=>e.removeEventListener("abort",t))}const u=t??this._config.timeout;return"number"==typeof u&&u>0&&u<=2147483647&&(s=setTimeout(()=>a(new Ji(u)),u)),o}async withTelemetry(e,t,r){const n=Date.now();this.emitRequest(e,t);try{const t=await r();return t.ok?this.emitResponse(e,!0,n):(this.emitResponse(e,!1,n),this.emitError(t.error,e)),t}catch(t){const r=fa(this.getServiceName(),t);return this.emitResponse(e,!1,n),this.emitError(r,e),ii(r)}}},ya=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?si({...r.data,results:r.data.results.map((t,r)=>({...t,key:e[r]}))}):r}async put(e,t,r){const n=this.getFullKey(e);return this._kv.put(n,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 ii(ai(ni.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?si({...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?si({...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}`,n=`${this._prefix}${r}`;return new e(this._kv,n)}},ma="tinycloud.kv/get",ga="tinycloud.kv/put",va="tinycloud.kv/list",_a="tinycloud.kv/del",ka="tinycloud.kv/metadata",wa="tinycloud.kv/sync";function Ea(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var ba=new TextEncoder,Ta=/^(?:Invalid invocation: )?delegation-(?:(revoked): [A-Za-z0-9]+|(ancestor-revoked): ancestor=[A-Za-z0-9]+ invoked=[A-Za-z0-9]+)$/,Na=new Set(["delegation_revoked","parent_revoked","ancestor_revoked"]);function Oa(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function xa(e,t,r,n){if(413!==r)return;const s=n.split(":",1)[0].trim();let i;return i=s===`${e}_request_too_large`||s!==`${e}_response_too_large`&&["batch","executeStatement","import"].includes(t),i?`${e.toUpperCase()}_REQUEST_TOO_LARGE`:void 0}(class extends pa{constructor(e={}){super(),this.readThrough=null,this.readThroughReady=null,this._config=e}setReadThroughReady(e){const t=()=>{"function"==typeof e&&(e=Promise.resolve().then(e));const r=()=>{this.readThroughReady===t&&(this.readThroughReady=null)};return e.then(r,r)};this.readThroughReady=t,"function"!=typeof e&&t()}get config(){return this._config}setReadThrough(e){this.readThrough=e}handleQuotaErrorResponse(e,t,r){if((402===e.status||413===e.status)&&(413!==e.status||la(t)))return ii(ha("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)?ii(ai(ni.KV_NOT_FOUND,`KV ${e.status} - ${r}`,"kv",{meta:{status:e.status,statusText:e.statusText}})):ii(ai(ni.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,n,s){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"kv",e,t),{headers:s,body:r,signal:n})}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,n=new Uint8Array(r.byteLength);return n.set(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),new Blob([n],{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,n=!1){const s=globalThis.atob(e),i=Uint8Array.from(s,e=>e.charCodeAt(0));if(n)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 n=e.results;if(!Array.isArray(n)||n.length!==t.length)return;for(const e of n){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(n.every(e=>"string"==typeof e.key)){const e=new Map(n.map(e=>[e.key,e]));if(e.size!==n.length)return;const r=[];for(const n of t){const t=e.get(n);if(!t)return;r.push(t)}return r}if(n.some(e=>void 0!==e.key))return;const s=t.map((e,t)=>t).sort((e,r)=>function(e,t){const r=ba.encode(e),n=ba.encode(t),s=Math.min(r.length,n.length);for(let e=0;e<s;e++)if(r[e]!==n[e])return r[e]-n[e];return r.length-n.length}(t[e],t[r])),i=new Array(n.length);for(let e=0;e<s.length;e++)i[s[e]]=n[e];return i}async batchRead(e,t,r){if(!this.requireAuth())return ii(zi("kv"));if(0===e.length)return si({results:[],count:0});if(e.length>100)return ii(ai(ni.INVALID_INPUT,"KV batch reads accept at most 100 keys","kv"));if(1===e.length){const n=e[0];return si({results:[{key:n,result:t===ma?await this.get(n,r):await this.head(n,r)}],count:1})}if(!this.context.invokeAny)return ii(ai(ni.INVALID_INPUT,"KV batch reads require SDK runtime support for multi-resource invocations","kv"));const n=t===ma?r:void 0;if(void 0!==n?.maxResponseBytes&&(!Number.isSafeInteger(n.maxResponseBytes)||n.maxResponseBytes<=0))return ii(ai(ni.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const s=e.map(e=>this.getFullPath(e,r?.prefix));if(new Set(s).size!==s.length)return ii(ai(ni.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!==n?.maxResponseBytes&&(r["x-tinycloud-max-response-bytes"]=String(n.maxResponseBytes));const a=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.session;return this.context.invokeAny(e,s.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,s,t):413===a.status?ii(ai(ni.KV_RESPONSE_TOO_LARGE,"A KV batch value exceeds the requested response limit","kv",{meta:{status:a.status,statusText:a.statusText}})):ii(ai(ni.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(),s,t===ma);if(!o)return ii(ai(ni.NETWORK_ERROR,"KV batch read response did not match the requested keys","kv"));const c=o.map((r,s)=>{if(!r.ok)return{key:e[s],result:ii(ai(r.error.code,r.error.message,"kv"))};const i=r.headers,a=t===ka?void 0:this.parseBatchValue(r.dataBase64,i,n?.raw,n?.binary);return{key:e[s],result:si({data:a,headers:this.createBatchResponseHeaders(i)})}});return si({results:c,count:c.length})}catch(e){return ii(fa("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 n=e.headers.get("content-type");if(n?.includes("application/json"))return await e.json();if(n?.startsWith("text/"))return await e.text();const s=await e.text();if(s)try{return JSON.parse(s)}catch{return s}}async createSignedReadUrlError(e,t,r){let n=e.statusText;try{const t=await e.text();t&&(n=t)}catch{}return 401===e.status||403===e.status?this.authorizationFailure(`Failed to create signed read URL for key ${JSON.stringify(t)}`,e,n,[r],ma):ii(ai(400===e.status?ni.INVALID_INPUT:ni.NETWORK_ERROR,`Failed to create signed read URL for key ${JSON.stringify(t)}: ${e.status} - ${n}`,"kv",{meta:{status:e.status,statusText:e.statusText}}))}async readAuthorizationText(e){try{return await e.text()}catch{return""}}authorizationFailure(e,t,r,n,s,i={}){const{resource:a,action:o}=Xi(r),c=n.find(e=>a===e||a===`${this.context.session.spaceId}/kv/${e}`),u=void 0!==c&&o===s?na({service:"kv",code:ni.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",l=ji(Mi.get(t),r);return ii((h=`${e}: ${t.status} - ${d}`,f={status:t.status,...i,...u,...l},ai(ni.AUTH_UNAUTHORIZED,h,"kv",{meta:f})));var h,f}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("network"!==t?.source&&null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ii(zi("kv"));if(void 0!==t?.maxResponseBytes&&(!Number.isSafeInteger(t.maxResponseBytes)||t.maxResponseBytes<=0))return ii(ai(ni.INVALID_INPUT,"KV maxResponseBytes must be a positive safe integer","kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const s=()=>this.getFromNetwork(e,r,t,n.signal);if("network"===t?.source){const e=this.readThrough;if(null===e)return await s();let t="error";const n=Date.now();try{const e=await s();return t=e.ok?"found":e.error.code===ni.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()-n})}catch{}}}return null===this.readThrough?await s():await this.readThrough.get({space:this.context.session.spaceId,key:e,path:r,options:t,signal:n.signal,network:s})}catch(e){return ii(fa("kv",e))}finally{n.dispose()}})}async getFromNetwork(e,t,r,n){const s=await this.invokeOperation(t,ma,void 0,n,void 0===r?.maxResponseBytes?void 0:{"x-tinycloud-max-response-bytes":String(r.maxResponseBytes)});if(!s.ok){if(401===s.status||403===s.status){const r=await this.readAuthorizationText(s),n=function(e){try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return;const r=t,n=r.error,s="object"==typeof n&&null!==n?n:void 0;return Wi(r.permissionHint)??Wi(s?.permissionHint)}catch{return}}(r),i="tinycloud.kv"===n?.service&&n.space===this.context.session.spaceId&&n.path===t?na({service:"kv",code:ni.AUTH_UNAUTHORIZED,meta:{status:s.status,resource:`${this.context.session.spaceId}/kv/${t}`,requiredAction:ma}}):void 0;return this.authorizationFailure(`Failed to get key ${JSON.stringify(e)}`,s,r,[t],ma,i?{permissionHint:n,...i}:{})}if(404===s.status)return this.classifyNotFound(s,e);const r=await s.text();if(413===s.status)return ii(ai(ni.KV_RESPONSE_TOO_LARGE,`KV value at key ${JSON.stringify(e)} exceeds the requested response limit`,"kv",{meta:{status:s.status,statusText:s.statusText}}));const n=`Failed to get key ${JSON.stringify(e)}: ${s.status} - ${r}`,i=Gi("kv",n,s,r);return ii(i||ai(ni.NETWORK_ERROR,n,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return si({data:await this.parseResponse(s,r?.raw,r?.binary),headers:this.createResponseHeaders(s.headers),...s.retry&&{retry:s.retry}})}async batchGet(e,t){return this.withTelemetry("batchGet",String(e.length),()=>this.batchRead(e,ma,t))}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ii(zi("kv"));if(void 0!==r?.ifMatch&&void 0!==r.ifNoneMatch)return ii(ai(ni.INVALID_INPUT,"KV put cannot combine ifMatch and ifNoneMatch","kv"));const n=this.getFullPath(e,r?.prefix),s=this.serializePutValue(t,r?.contentType),i=this.createRequestSignal(r?.signal,r?.timeout);try{const t=()=>this.putToNetwork(e,n,s,r,i.signal);return null===this.readThrough?await t():await this.readThrough.write({op:"put",space:this.context.session.spaceId,entries:[{path:n,body:s}],signal:i.signal,conditional:void 0!==r?.ifMatch||void 0!==r?.ifNoneMatch,network:t})}catch(e){return ii(fa("kv",e))}finally{i.dispose()}})}async putToNetwork(e,t,r,n,s){const i=await this.invokeOperation(t,ga,r,s,{...void 0===n?.ifMatch?{}:{"if-match":n.ifMatch},...void 0===n?.ifNoneMatch?{}:{"if-none-match":n.ifNoneMatch}});if(401===i.status||403===i.status)return this.authorizationFailure(`Failed to put key ${JSON.stringify(e)}`,i,await this.readAuthorizationText(i),[t],ga);if(!i.ok){const t=await i.text();if(412===i.status)return ii(ai(ni.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}`,n=Gi("kv",r,i,t);if(n)return ii(n);return this.handleQuotaErrorResponse(i,t,e)||ii(ai(ni.KV_WRITE_FAILED,r,"kv",{meta:{status:i.status,statusText:i.statusText}}))}return si({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 ii(zi("kv"));if(0===e.length)return si({written:[],count:0});if(!this.context.invokeAny)return ii(ai(ni.INVALID_INPUT,"KV batchPut requires SDK runtime support for multi-resource invocations","kv"));const r=this.context.session,n=e.map(e=>this.getFullPath(e.key,t?.prefix)),s=new Set;for(const e of n){if(s.has(e))return ii(ai(ni.INVALID_INPUT,`KV batchPut received duplicate key after prefix resolution: ${e}`,"kv"));s.add(e)}const i=this.createRequestSignal(t?.signal,t?.timeout);try{const t=()=>this.batchPutToNetwork(e,n,i.signal);if(null===this.readThrough)return await t();const s=e.map((e,t)=>({path:n[t],body:this.serializeBatchPutValue(e)}));return await this.readThrough.write({op:"batchPut",space:r.spaceId,entries:s,signal:i.signal,network:()=>this.batchPutToNetwork(e,n,i.signal,s)})}catch(e){const t=fa("kv",e);return ii({...t,meta:{...t.meta,requestMayHaveDispatched:!1}})}finally{i.dispose()}})}async batchPutToNetwork(e,t,r,n){const s=this.context.session;let i=!1;try{const a=new FormData;for(let r=0;r<e.length;r++)a.append(Oa(t[r]),n?.[r]?.body??this.serializeBatchPutValue(e[r]));const o=await this.invokeWithRetry(`${this.host}/invoke`,()=>{const e=this.context.invokeAny(s,t.map(e=>({spaceId:s.spaceId,service:"kv",path:e,action:ga})));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 ii(ai(ni.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,ga);return this.handleQuotaErrorResponse(o,r,"batch")||ii(ai(ni.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=Yi(t);return ii(ai(r?ni.TIMEOUT:ni.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 ii(ai(ni.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))?si(u):ii(ai(ni.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=fa("kv",e);return ii({...t,meta:{...t.meta,requestMayHaveDispatched:i}})}}async list(e){return this.withTelemetry("list",e?.prefix,async()=>{if("network"!==e?.source&&null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return ii(zi("kv"));if(void 0!==e?.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return ii(ai(ni.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 n=()=>this.listFromNetwork(t,e,r.signal);let s;if("network"===e?.source){const e=this.readThrough;if(null===e)s=await n();else{let r="error";const i=Date.now();try{s=await n(),r=s.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 s=null===this.readThrough?await n():await this.readThrough.list({space:this.context.session.spaceId,listPath:t,options:e,signal:r.signal,network:n});return s.ok?this.finishList(s.data,t,e?.removePrefix):s}catch(e){return ii(fa("kv",e))}finally{r.dispose()}})}async listFromNetwork(e,t,r){const n=await this.invokeOperation(e,va,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(!n.ok){if(401===n.status||403===n.status)return this.authorizationFailure("Failed to list keys",n,await this.readAuthorizationText(n),[e],va);const t=await n.text(),r=`Failed to list keys: ${n.status} - ${t}`,s=Gi("kv",r,n,t);return ii(s||ai(ni.NETWORK_ERROR,r,"kv",{meta:{status:n.status,statusText:n.statusText}}))}return si({keys:await this.parseResponse(n,t?.raw)??[],...null===n.headers.get("x-tinycloud-truncated")?{}:{truncated:"true"===n.headers.get("x-tinycloud-truncated")},...null===n.headers.get("x-tinycloud-next-cursor")?{}:{nextCursor:n.headers.get("x-tinycloud-next-cursor")??void 0}})}finishList(e,t,r){let n=e.keys;if(r&&t){const e=t.endsWith("/")?t:`${t}/`;n=n.map(t=>t.startsWith(e)?t.slice(e.length):t)}return si({keys:n,...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 ii(zi("kv"));if("string"!=typeof e?.prefix||0===e.prefix.length)return ii(ai(ni.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 ii(ai(ni.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 n=this.createRequestSignal(e.signal,e.timeout);try{const s=await this.invokeOperation(t,wa,void 0,n.signal,r);if(!s.ok)return await this.changesFailure(s,e.prefix,n.signal);const i=await s.text();let a;try{a=JSON.parse(i)}catch{a=void 0}const o=this.normalizeChangesResponse(a,e.prefix);return o?si(o):ii(ai(ni.NETWORK_ERROR,"KV changes response was not a tinycloud.kv/sync page","kv",{meta:{status:s.status,statusText:s.statusText}}))}catch(e){return ii(fa("kv",e))}finally{n.dispose()}})}async changesFailure(e,t,r){if(404===e.status)return this.classifyNotFound(e,t);let n;try{n=await e.text()}catch(e){if(r.aborted)throw e;n=""}const s={status:e.status,statusText:e.statusText};let i,a;try{const e=JSON.parse(n),t=Ea(e)?e.error:void 0;Ea(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 ii(ai(ni.KV_SYNC_RESET_REQUIRED,`${o}: the node requires a reset (${i??"reason not given"}); discard sync state and restart without a cursor`,"kv",{meta:{...s,reason:i}}));if(403===e.status&&"RETENTION_GRANT_REFUSED"===a)return ii(ai(ni.KV_RETENTION_GRANT_REFUSED,`${o}: the retention grant was refused (${i??"reason not given"})`,"kv",{meta:{...s,reason:i}}));if(401===e.status){const e=function(e){const t=Ta.exec(function(e){const t=e.trim();if(!t.startsWith("{"))return t;try{const e=JSON.parse(t);if(Ea(e)&&"string"==typeof e.code&&Na.has(e.code)&&"string"==typeof e.error)return e.error}catch{}return t}(e));if(null!==t)return void 0!==t[1]?ni.AUTH_DELEGATION_REVOKED:ni.AUTH_DELEGATION_ANCESTOR_REVOKED}(n);if(void 0!==e)return ii(ai(e,`${o}: 401 - ${n}`,"kv",{meta:s}))}return 401===e.status||403===e.status?this.authorizationFailure(o,e,n,[t],wa):ii(ai(400===e.status?ni.INVALID_INPUT:ni.NETWORK_ERROR,`${o}: ${e.status} - ${n}`,"kv",{meta:s}))}normalizeChangesResponse(e,t){if(!Ea(e))return;const{changes:r,more:n,cursor:s,source:i,authority:a}=e;if(!Array.isArray(r)||"boolean"!=typeof n||"string"!=typeof s||!Ea(i)||"string"!=typeof i.nodeDid||"string"!=typeof i.space||"string"!=typeof i.prefix||!Ea(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(!Ea(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||!Ea(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:n,cursor:s,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 ii(zi("kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const s=()=>this.deleteFromNetwork(e,r,t,n.signal);return null===this.readThrough?await s():await this.readThrough.write({op:"delete",space:this.context.session.spaceId,entries:[{path:r}],signal:n.signal,conditional:void 0!==t?.ifMatch,network:s})}catch(e){return ii(fa("kv",e))}finally{n.dispose()}})}async deleteFromNetwork(e,t,r,n){const s=await this.invokeOperation(t,_a,void 0,n,void 0===r?.ifMatch?void 0:{"if-match":r.ifMatch});if(!s.ok){if(401===s.status||403===s.status)return this.authorizationFailure(`Failed to delete key ${JSON.stringify(e)}`,s,await this.readAuthorizationText(s),[t],_a);if(404===s.status)return this.classifyNotFound(s,e);const r=await s.text();if(412===s.status)return ii(ai(ni.KV_PRECONDITION_FAILED,`KV precondition failed for key ${JSON.stringify(e)}`,"kv",{meta:{status:s.status,statusText:s.statusText}}));const n=`Failed to delete key ${JSON.stringify(e)}: ${s.status} - ${r}`,i=Gi("kv",n,s,r);return ii(i||ai(ni.NETWORK_ERROR,n,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return si({data:void 0,headers:this.createResponseHeaders(s.headers),...s.retry&&{retry:s.retry}})}async head(e,t){return this.withTelemetry("head",e,async()=>{if(!this.requireAuth())return ii(zi("kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeOperation(r,ka,void 0,n.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],ka);if(404===t.status)return await this.classifyNotFound(t,e);const n=await t.text(),s=`Failed to get metadata for key ${JSON.stringify(e)}: ${t.status} - ${n}`,i=Gi("kv",s,t,n);return ii(i||ai(ni.NETWORK_ERROR,s,"kv",{meta:{status:t.status,statusText:t.statusText}}))}return si({data:void 0,headers:this.createResponseHeaders(t.headers)})}catch(e){return ii(fa("kv",e))}finally{n.dispose()}})}async batchHead(e,t){return this.withTelemetry("batchHead",String(e.length),()=>this.batchRead(e,ka,t))}async createSignedReadUrl(e,t){return this.withTelemetry("createSignedReadUrl",e,async()=>{if(!this.requireAuth())return ii(zi("kv"));const r=this.getFullPath(e,t?.prefix),n=this.context.session,s={space:n.spaceId,path:r,ttl_seconds:t?.expiresInSeconds??Math.ceil(300)};void 0!==t?.contentHash&&(s.content_hash=t.contentHash),void 0!==t?.etag&&(s.etag=t.etag);const i=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeWithRetry(`${this.host}/signed/kv`,()=>this.context.invoke(n,"kv",r,ma),{headers:{"content-type":"application/json"},body:JSON.stringify(s),signal:i.signal});if(!t.ok)return await this.createSignedReadUrlError(t,e,r);const a=this.normalizeSignedReadUrlResponse(await t.json());return a?si(a):ii(ai(ni.NETWORK_ERROR,"Signed read URL response did not include url, ticketId, and expiresAt","kv"))}catch(e){return ii(fa("kv",e))}finally{i.dispose()}})}withPrefix(e){return new ya(this,e)}}).serviceName="kv";var Ra=class{constructor(e,t){this.service=e,this.dbName=t}apply(e){return this.service.applyMigrationsOnDb(this.dbName,e)}},Aa=class{constructor(e,t){this.service=e,this.name=t,this.migrations=new Ra(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)}},Ia={READ:et.READ,WRITE:et.WRITE,SCHEMA:et.SCHEMA,ADMIN:et.ADMIN,SELECT:et.SELECT,EXECUTE:et.EXECUTE,EXPORT:et.EXPORT,ALL:et.ALL},Sa=new Set(["alter","create","drop"]),Da="__tinycloud_sql_migrations",Pa=`CREATE TABLE IF NOT EXISTS ${Da} (\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)`,Ua="tinycloud.sql.migrations",La="000_metadata";function Ca(e){return e.map(e=>e instanceof Uint8Array?Array.from(e):e)}function Ka(e){return/no such table/i.test(e)}function $a(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ba(e,t){return Array.isArray(e)?e[t]:e&&"object"==typeof e?Object.values(e)[t]:void 0}(class extends pa{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 Aa(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 ii(ai(ni.INVALID_INPUT,r,"sql"));const n=`${e}\0${t.namespace}`,s=this.migrationLocks.get(n);if(s)return s;const i=this.applyMigrationsOnDbUnlocked(e,t);this.migrationLocks.set(n,i);try{return await i}finally{this.migrationLocks.delete(n)}}async queryOnDb(e,t,r,n){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return ii(zi("sql"));const s=this.createRequestSignal(n?.signal);try{const i={action:"query",sql:t,params:Ca(r??[])};void 0!==n?.maxRows&&(i.maxRows=n.maxRows),void 0!==n?.maxBytes&&(i.maxBytes=n.maxBytes);const a=this.actionForSql(t,Ia.READ),o=await this.invokeSQL(e,a,i,s.signal);if(!o.ok){const t=await this.handleErrorResponse(o,"query",e,[a]);return this.redactFailure(t,n?.redactErrors,o.status)}return si(await o.json())}catch(e){return this.redactFailure(ii(fa("sql",e)),n?.redactErrors)}finally{s.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return ii(zi("sql"));const s=this.createRequestSignal(n?.signal);try{const i={action:"execute",sql:t,params:Ca(r??[])};n?.schema&&(i.schema=n.schema);const a=[this.actionForSql(t,Ia.WRITE),...(n?.schema??[]).map(e=>this.actionForSql(e,Ia.SCHEMA))],o=this.dedupeActions(a),c=await this.invokeSQL(e,o,i,s.signal);if(!c.ok){const t=await this.handleErrorResponse(c,"execute",e,o);return this.redactFailure(t,n?.redactErrors,c.status)}return si(await c.json())}catch(e){return this.redactFailure(ii(fa("sql",e)),n?.redactErrors)}finally{s.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return ii(zi("sql"));const n=this.createRequestSignal(r?.signal);try{const s=this.actionsForSqlBatch(t),i=await this.invokeSQL(e,s,{action:"batch",statements:t},n.signal);if(!i.ok){const t=await this.handleErrorResponse(i,"batch",e,s);return this.redactFailure(t,r?.redactErrors,i.status)}return si(await i.json())}catch(e){return this.redactFailure(ii(fa("sql",e)),r?.redactErrors)}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return ii(zi("sql"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeSQL(e,Ia.WRITE,{action:"execute_statement",name:t,params:r??[]},s.signal);return n.ok?si(await n.json()):await this.handleErrorResponse(n,"executeStatement",e,[Ia.WRITE])}catch(e){return ii(fa("sql",e))}finally{s.dispose()}})}async exportDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return ii(zi("sql"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeSQL(e,Ia.READ,{action:"export"},r.signal);if(!t.ok)return await this.handleErrorResponse(t,"export",e,[Ia.READ]);const n=t;return"function"==typeof n.blob?si(await n.blob()):si(await t.text())}catch(e){return ii(fa("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='${Da}'`,[],{signal:t.signal});let n=r.ok?0===r.data.rows.length:r.error.code===ni.SQL_DATABASE_NOT_FOUND||Ka(r.error.message);if(!r.ok&&!n)return r;const s=new Set;if(!n){const r=await this.queryOnDb(e,`SELECT id FROM ${Da} WHERE namespace = ? ORDER BY applied_at, id`,[t.namespace],{signal:t.signal});if(n=!r.ok&&(r.error.code===ni.SQL_DATABASE_NOT_FOUND||Ka(r.error.message)),!r.ok&&!n)return r;if(r.ok)for(const e of r.data.rows){const t=Ba(e,0);"string"==typeof t&&s.add(t)}}const i=t.migrations.filter(e=>s.has(e.id)).map(e=>e.id),a=t.migrations.filter(e=>!s.has(e.id)),o=[];if(a.length>0&&n){const r=await this.ensureMigrationsTable(e,t.signal);if(!r.ok)return r}for(const r of a){const n=await this.applyOneMigration(e,t.namespace,r,t.signal);if(!n.ok)return n;o.push(r.id)}return si({database:e,namespace:t.namespace,status:o.length>0?"applied":"already_current",applied:o,skipped:i})})}async applyOneMigration(e,t,r,n){const s=[...r.sql.map(e=>"string"==typeof e?{sql:e}:e),{sql:`INSERT OR REPLACE INTO ${Da} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[$a(t,r.id),t,r.id,(new Date).toISOString(),r.sql.length]}],i=await this.batchOnDb(e,s,{signal:n});return i.ok?si(void 0):i}async ensureMigrationsTable(e,t){const r=await this.batchOnDb(e,[{sql:Pa},{sql:`INSERT OR REPLACE INTO ${Da} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[$a(Ua,La),Ua,La,(new Date).toISOString(),1]}],{signal:t});return r.ok?si(void 0):r}async invokeSQL(e,t,r,n){const s=Array.isArray(t)?t:[t];return this.invokeWithRetry(`${this.host}/invoke`,()=>{const t=this.context.session;return 1===s.length?this.context.invoke(t,"sql",e,s[0]):this.invokeSQLAny(t,e,s)},{headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:n})}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?Ia.ADMIN:void 0!==r&&Sa.has(r)?Ia.SCHEMA:t}actionsForSqlBatch(e){return this.dedupeActions(e.map(e=>this.actionForSql(e.sql,Ia.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 n=e.error.code,s="string"==typeof n&&Object.prototype.hasOwnProperty.call(ni,n)?n:ni.SQL_ERROR,i="number"==typeof r&&Number.isInteger(r)&&r>=400&&r<=599?r:void 0;return ii(ai(s,"SQL operation failed","sql",void 0===i?void 0:{meta:{status:i}}))}async handleErrorResponse(e,t,r,n){const s=await e.text(),i=Di(e.status,e.statusText,s);if(402===e.status)return ii(ha("sql",402,i,s));if(413===e.status&&la(s))return ii(ha("sql",413,i,s));const a=Gi("sql",`SQL ${t} failed: ${e.status} - ${s}`,e,s);if(a)return ii(a);const o=Ii(s),c=xa("sql",t,e.status,s)??this.mapHttpStatusToErrorCode(e.status,o.error),u=Si("SQL",t,e.status,s,o);if(401===e.status){const{action:e}=Xi(s);e&&n.includes(e)&&(i.requiredAction=e,i.resource=`${this.context.session.spaceId}/sql/${r}`)}return ii(ai(c,u,"sql",{meta:i}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return ni.SQL_ERROR;case 401:return ni.AUTH_UNAUTHORIZED;case 403:return"sql_readonly_violation"===t?ni.SQL_READONLY_VIOLATION:ni.SQL_PERMISSION_DENIED;case 404:return ni.SQL_DATABASE_NOT_FOUND;case 413:return ni.SQL_RESPONSE_TOO_LARGE;case 429:return ni.SQL_QUOTA_EXCEEDED;default:return ni.NETWORK_ERROR}}}).serviceName="sql";var Va=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)}},qa={READ:tt.READ,WRITE:tt.WRITE,ADMIN:tt.ADMIN,DESCRIBE:tt.DESCRIBE,EXPORT:tt.EXPORT,IMPORT:tt.IMPORT,EXECUTE:tt.EXECUTE,ALL:tt.ALL};(class extends pa{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 Va(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,n){return this.withTelemetry("query",e,async()=>{if(!this.requireAuth())return ii(zi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,qa.READ,{action:"query",sql:t,params:r??[]},s.signal);return n.ok?si(await n.json()):await this.handleErrorResponse(n,"query")}catch(e){return ii(fa("duckdb",e))}finally{s.dispose()}})}async queryArrowOnDb(e,t,r,n){return this.withTelemetry("queryArrow",e,async()=>{if(!this.requireAuth())return ii(zi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,qa.READ,{action:"query",sql:t,params:r??[]},s.signal,{Accept:"application/vnd.apache.arrow.stream"});return n.ok?si(await n.arrayBuffer()):await this.handleErrorResponse(n,"queryArrow")}catch(e){return ii(fa("duckdb",e))}finally{s.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return ii(zi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const i={action:"execute",sql:t,params:r??[]};n?.schema&&(i.schema=n.schema);const a=await this.invokeDuckDb(e,qa.WRITE,i,s.signal);return a.ok?si(await a.json()):await this.handleErrorResponse(a,"execute")}catch(e){return ii(fa("duckdb",e))}finally{s.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return ii(zi("duckdb"));const n=this.createRequestSignal(r?.signal);try{const s={action:"batch",statements:t};void 0!==r?.transactional&&(s.transactional=r.transactional);const i=await this.invokeDuckDb(e,qa.WRITE,s,n.signal);return i.ok?si(await i.json()):await this.handleErrorResponse(i,"batch")}catch(e){return ii(fa("duckdb",e))}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return ii(zi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,qa.WRITE,{action:"executeStatement",name:t,params:r??[]},s.signal);return n.ok?si(await n.json()):await this.handleErrorResponse(n,"executeStatement")}catch(e){return ii(fa("duckdb",e))}finally{s.dispose()}})}async describeDb(e,t){return this.withTelemetry("describe",e,async()=>{if(!this.requireAuth())return ii(zi("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,qa.READ,{action:"describe"},r.signal);return t.ok?si(await t.json()):await this.handleErrorResponse(t,"describe")}catch(e){return ii(fa("duckdb",e))}finally{r.dispose()}})}async exportOnDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return ii(zi("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,qa.EXPORT,{action:"export"},r.signal);return t.ok?si(await t.blob()):await this.handleErrorResponse(t,"export")}catch(e){return ii(fa("duckdb",e))}finally{r.dispose()}})}async importOnDb(e,t,r){return this.withTelemetry("import",e,async()=>{if(!this.requireAuth())return ii(zi("duckdb"));const n=this.createRequestSignal(r?.signal);try{const r=await this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,qa.IMPORT),{headers:{"Content-Type":"application/x-duckdb"},body:new Blob([t]),signal:n.signal});return r.ok?si(void 0):await this.handleErrorResponse(r,"import")}catch(e){return ii(fa("duckdb",e))}finally{n.dispose()}})}async invokeDuckDb(e,t,r,n,s){return this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,t),{headers:{"Content-Type":"application/json",...s},body:JSON.stringify(r),signal:n})}async handleErrorResponse(e,t){const r=await e.text(),n=Di(e.status,e.statusText,r);if(402===e.status)return ii(ha("duckdb",402,n,r));if(413===e.status&&la(r))return ii(ha("duckdb",413,n,r));const s=Gi("duckdb",`DuckDB ${t} failed: ${e.status} - ${r}`,e,r);if(s)return ii(s);const i=Ii(r),a=xa("duckdb",t,e.status,r)??this.mapHttpStatusToErrorCode(e.status,i.error),o=Si("DuckDB",t,e.status,r,i);if(401===e.status){const{resource:e,action:t}=Xi(r);t&&(n.requiredAction=t),e&&(n.resource=e)}return ii(ai(a,o,"duckdb",{meta:n}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return ni.DUCKDB_ERROR;case 401:return ni.AUTH_UNAUTHORIZED;case 403:return"duckdb_readonly_violation"===t?ni.DUCKDB_READONLY_VIOLATION:ni.DUCKDB_PERMISSION_DENIED;case 404:return ni.DUCKDB_DATABASE_NOT_FOUND;case 413:return ni.DUCKDB_RESPONSE_TOO_LARGE;case 429:return ni.DUCKDB_QUOTA_EXCEEDED;default:return ni.NETWORK_ERROR}}}).serviceName="duckdb";var Fa=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 Ma(e,t){const r=io(t);return r?`${e}/${r}`:e}function ja(e){return"number"==typeof e&&e>=400&&e<500&&408!==e&&429!==e}(class extends pa{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(ro),n={requested:r,signatures:r.map(no),ttlSeconds:t.ttlSeconds,onReady:t.onReady,queue:new Fa},s=()=>{this._subscribers.delete(n),n.queue.close(),this.wake()},{signal:i}=t;if(!i?.aborted){i?.addEventListener("abort",s,{once:!0}),this._subscribers.add(n),this.wake(),this._readyStream&&this.notifyReady(n,this._readyStream);try{for await(const e of n.queue)yield e}finally{i?.removeEventListener("abort",s),s()}}}async register(e){if(!this.requireAuth())return ii(zi("hooks"));if("string"!=typeof e.secret||0===e.secret.trim().length)return ii(ai(ni.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",Ma(e.service,e.pathPrefix)),{headers:{"content-type":"application/json"},body:JSON.stringify({space:e.space,service:e.service,pathPrefix:io(e.pathPrefix),abilities:e.abilities??[],callbackUrl:e.callbackUrl,secret:e.secret})});if(!t.ok)return ii(await ao("hooks","failed to register webhook",t));const r=uo(await t.json());return r?si(r):ii(fa("hooks",new Error("Webhook registration response did not include a record")))}catch(e){return ii(fa("hooks",e))}}async list(e={}){if(!this.requireAuth())return ii(zi("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=io(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?Ma(e.service,e.pathPrefix):"webhooks"),{method:"GET"});if(!r.ok)return ii(await ao("hooks","failed to list webhooks",r));const n=function(e){if(Array.isArray(e))return e.map(e=>uo(e)).filter(e=>null!==e);if(!e||"object"!=typeof e)return null;const t=e,r=lo(t.webhooks)??lo(t.subscriptions)??lo(t.hooks)??lo(t.data);if(r)return r;const n=ho(t);return n?[n]:null}(await r.json());return n?si(n):ii(fa("hooks",new Error("Webhook list response did not include records")))}catch(e){return ii(fa("hooks",e))}}async unregister(e,t={}){if(!this.requireAuth())return ii(zi("hooks"));try{const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks/${encodeURIComponent(e)}`,()=>this.createHookHeaders("tinycloud.hooks/unregister",t.target?Ma(t.target.service,t.target.pathPrefix):`webhooks/${e}`),{method:"DELETE"});return r.ok?si(void 0):ii(await ao("hooks","failed to unregister webhook",r))}catch(e){return ii(fa("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},n=await this.phase(t.key,e=>this.attempt(t,e,r));(r.delivered||r.openedAt>0&&performance.now()-r.openedAt>=5e3)&&(e=0),n&&this.plan()?.key===t.key&&("stopped"!==n.kind?"refused"===n.kind&&n.terminal?(this.release(n.error),this.report(n.error)):("ended"!==n.kind&&this.report(n.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 n=await t(r.signal);return r.signal.aborted?void 0:n}finally{this._phase=void 0,r.abort()}}async attempt(e,t,r){let n,s="mint";const i=++this._streamGeneration,a=()=>!t.aborted&&!n?.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"};n=this.createRequestSignal(t,0);const u=this.host,d=function(e){return Array.isArray(e)?Object.fromEntries(e):{...e}}(this.createInvokeHeaders(e.subscriptions)),l=await Za(n.signal,()=>o.fetch(`${u}/hooks/tickets`,{method:"POST",headers:{...d,"content-type":"application/json"},body:JSON.stringify({subscriptions:e.subscriptions,ttlSeconds:e.ttlSeconds}),signal:n.signal}));if(!a())return{kind:"stopped"};if(!l.ok){const e=l.status,t=Object.entries(d).find(([e])=>"authorization"===e.toLowerCase())?.[1],r=function(e,t){if((401===e||403===e)&&t)try{const e=t.split(".")[1],{prf:r,exp:n,nbf:s,iat:i}=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/"))),a=Date.now()/1e3;if(Number.isFinite(n)&&n<=a||Number.isFinite(s)&&s>a||Number.isFinite(i)&&i>a)return Fi;if(Number.isFinite(n)&&(null==s||Number.isFinite(s))&&(null==i||Number.isFinite(i))&&Array.isArray(r)&&1===r.length&&"string"==typeof r[0]&&r[0])return r[0]}catch{}}(e,t),s=await Za(n.signal,()=>ao("hooks","failed to mint hook ticket",l,r));return a()?{kind:"refused",terminal:ja(e),error:s}:{kind:"stopped"}}const h=await Za(n.signal,()=>l.json());if(!a())return{kind:"stopped"};const f=null!==h&&"object"==typeof h&&"ticket"in h?h.ticket:void 0;if("string"!=typeof f||0===f.length)throw new Error("Hook ticket response did not include a ticket");if(s="open",!a())return{kind:"stopped"};const p=await Za(n.signal,()=>o.fetch(`${u}/hooks/events?ticket=${encodeURIComponent(f)}`,{method:"GET",headers:{accept:"text/event-stream"},signal:n.signal}));if(!a())return{kind:"stopped"};if(!p.ok)return{kind:"refused",terminal:!1,error:za(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 n="";for await(const s of async function*(e,t){const r=e;if("function"==typeof r?.[Symbol.asyncIterator]){const e=r[Symbol.asyncIterator](),n=()=>{try{const t=e.return?.();t&&Promise.resolve(t).then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",n,{once:!0});try{for(;!t?.aborted;){const t=await e.next();if(t.done)break;yield t.value}}finally{t?.removeEventListener("abort",n),n()}return}const n=e;if("function"!=typeof n.getReader)throw new Error("Unsupported hook stream body type");const s=n.getReader(),i=()=>{try{const e=s.cancel?.();e&&e.then(()=>{},()=>{})}catch{}};t?.addEventListener("abort",i,{once:!0});try{for(;!t?.aborted;){const{done:e,value:t}=await s.read();if(e)break;t&&(yield t)}}finally{t?.removeEventListener("abort",i),i(),s.releaseLock?.()}}(e,t)){n+=r.decode(s,{stream:!0}).replace(/\r\n/g,"\n");let e=n.indexOf("\n\n");for(;e>=0;){const t=n.slice(0,e);n=n.slice(e+2);const r=oo(t);r&&(yield r),e=n.indexOf("\n\n")}}n+=r.decode();const s=oo(n.trim());s&&(yield s)}(p.body,n.signal)[Symbol.asyncIterator]();try{for(;;){const t=await Za(n.signal,()=>y.next());if(!a())return{kind:"stopped"};if(t.done)break;const s=t.value;if(!s.data)continue;if("ready"===s.event){const t=JSON.parse(s.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=co(s);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 n?.signal.aborted||e===Ha?{kind:"stopped"}:{kind:"failed",error:Ja(s,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,n=[],s=[];try{const r=this._config.streamRetry,s=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);n.push((r?.wait??eo)(s,e,t))}catch{n.push(Promise.resolve())}s.push(to(t)),r&&s.push(to(r));try{await Promise.race([...n,...s.map(({promise:e})=>e)])}catch{}finally{for(const e of s)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,n)=>e.set(r.signatures[n],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(ai(ni.INVALID_INPUT,"Hook readiness callback failed","hooks"))}}}dispatch(e){for(const t of this._subscribers)so(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=ai(ni.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 Ha=Symbol("hooks attempt superseded");async function Za(e,t){if(e.aborted)throw"function"!=typeof t&&t.then(Wa,()=>{}),Ha;const r="function"==typeof t?t():t;return new Promise((t,n)=>{let s=!1;const i=()=>e.removeEventListener("abort",a),a=()=>{s||(s=!0,i(),n(Ha))};e.addEventListener("abort",a,{once:!0}),r.then(e=>{s?Wa(e):(s=!0,i(),t(e))},e=>{s||(s=!0,i(),n(e))})})}function Wa(e){if(e instanceof Response&&e.body)try{e.body.cancel().then(()=>{},()=>{})}catch{}}function za(e){const t="number"==typeof e?e:void 0;return ai(ni.NETWORK_ERROR,`hook stream open refused: ${t??"unknown status"}`,"hooks",{meta:{phase:"open",status:t}})}var Ga=new Set(["Error","TypeError","AbortError","TimeoutError","SyntaxError","RangeError","NetworkError"]);function Ja(e,t){const r=Xa(t,"name"),n="string"==typeof r&&Ga.has(r)?r:"Error",s=Qa(Xa(t,"code"))??Qa(Xa(Xa(t,"cause"),"code"));return ai(ni.NETWORK_ERROR,`hook stream ${e} failed: ${n}${s?` (${s})`:""}`,"hooks",{meta:{phase:e,errorName:n,...s?{errorCode:s}:{}}})}var Ya=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 Qa(e){return"string"==typeof e&&Ya.has(e)?e:void 0}function Xa(e,t){if(null!==e&&("object"==typeof e||"function"==typeof e))try{return Reflect.get(e,t)}catch{return}}var eo=(e,t,r)=>((e,t,r=!1)=>new Promise(n=>{const s=()=>{clearTimeout(i),t.removeEventListener("abort",s),n()},i=setTimeout(s,e);r&&i.unref?.(),t.aborted?s():t.addEventListener("abort",s)}))(e,r,!0);function to(e){let t;const r=new Promise(e=>{t=e}),n=()=>t();return e.aborted?t():e.addEventListener("abort",n,{once:!0}),{promise:r,dispose:()=>e.removeEventListener("abort",n)}}function ro(e){return{...e,pathPrefix:"kv"===e.service?io(e.pathPrefix):e.pathPrefix?.replace(/^\/+/,"")||void 0,abilities:e.abilities?[...e.abilities]:[]}}function no(e){return JSON.stringify({space:e.space,service:e.service,pathPrefix:e.pathPrefix??"",abilities:[...e.abilities??[]].sort()})}function so(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,n=e.databasePath??e.path;if(r&&"/"!==r&&(!n||(r.endsWith("/")?!n.startsWith(r):n!==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 io(e){if(!e)return;const t=e.replace(/^\/+|\/+$/g,"");return t.length>0?t:void 0}async function ao(e,t,r,n){let s=r.statusText;try{const e=await r.text();e&&(s=e)}catch{}return ai(408===r.status||504===r.status?ni.TIMEOUT:ni.NETWORK_ERROR,`${t}: ${r.status} ${s}`,e,{meta:{status:r.status,statusText:r.statusText,...401===r.status||403===r.status?ji(n,s):void 0}})}function oo(e){if(!e)return null;let t,r="message";const n=[];for(const s of e.split("\n")){if(!s||s.startsWith(":"))continue;const[e,...i]=s.split(":"),a=i.join(":").replace(/^ /,"");switch(e){case"event":r=a;break;case"id":t=a;break;case"data":n.push(a)}}return 0===n.length?null:{event:r,id:t,data:n.join("\n")}}function co(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 uo(e){if(!e||"object"!=typeof e)return null;const t=e;return ho(t)??uo(t.webhook)??uo(t.hook)??uo(t.subscription)??uo(t.data)??null}function lo(e){return Array.isArray(e)?e.map(e=>uo(e)).filter(e=>null!==e):null}function ho(e){const t=fo(e,"id"),r=fo(e,"space")??fo(e,"spaceId"),n=fo(e,"service"),s=fo(e,"callbackUrl")??fo(e,"callback_url");return t&&r&&n&&s?{id:t,space:r,service:n,pathPrefix:po(e,"pathPrefix")??po(e,"path_prefix"),abilities:mo(e,"abilities")??go(e,"abilitiesJson")??go(e,"abilities_json"),callbackUrl:s,active:yo(e,"active")??!0,createdAt:fo(e,"createdAt")??fo(e,"created_at")??(new Date).toISOString(),subscriberDid:po(e,"subscriberDid")??po(e,"subscriber_did")}:null}function fo(e,t){const r=e[t];return"string"==typeof r?r:void 0}function po(e,t){return fo(e,t)}function yo(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function mo(e,t){const r=e[t];if(!Array.isArray(r))return;const n=r.filter(e=>"string"==typeof e);return n.length===r.length?n:void 0}function go(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 vo(e){return void 0===e?"":_o(e)}function _o(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(_o).join(",")}]`;const t=Object.keys(e).sort(),r=[];for(const n of t){const t=e[n];void 0!==t&&r.push(`${JSON.stringify(n)}:${_o(t)}`)}return`{${r.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}var ko="0123456789abcdef";function wo(e){let t="";for(let r=0;r<e.length;r++){const n=e[r];t+=ko[n>>4&15]+ko[15&n]}return t}function Eo(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let r="";for(let n=0;n<e.length;n+=3){const s=e[n],i=n+1<e.length?e[n+1]:0,a=n+2<e.length?e[n+2]:0;r+=t[s>>2&63],r+=t[63&(s<<4|i>>4)],r+=n+1<e.length?t[63&(i<<2|a>>6)]:"=",r+=n+2<e.length?t[63&a]:"="}return r}function bo(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),r=t.length;if(r%4!=0)throw new Error("invalid base64 input");const n=r/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),s=new Uint8Array(n),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<n&&(s[a++]=u),a<n&&(s[a++]=d),a<n&&(s[a++]=l)}return s}function To(e){return(new TextEncoder).encode(e)}function No(e,t){return wo(e(To(vo(t))))}var Oo=/^[A-Z][A-Z0-9_]{0,63}$/,xo="tinychat-bot-history",Ro=new Set(["default","global",xo]),Ao=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Io(e,t,r=!1){if(t.test(e))return{name:e};const n=e.split("/");if(3!==n.length||"scoped"!==n[0])return;const[,s,i]=n;if(i&&t.test(i)){if(r&&s&&((a=s).length>64&&Ao.test(a)))return{name:i,scope:s,scopeTooLong:!0};try{const e=function(e){if(void 0===e)return;const t=e.trim();if(""===t)throw new Error("Secret scope must be non-empty; omit scope for global secrets.");const r=t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(""===r)throw new Error("Secret scope must contain at least one letter or number.");if(Ro.has(r))throw new Error(`Secret scope ${JSON.stringify(e)} is reserved; omit scope for global secrets.`);if(r.length>64)throw new Error(`Secret scope ${JSON.stringify(r)} is longer than 64 characters.`);return r}(s);if(void 0===e||e!==s)return;return{name:i,scope:e}}catch{return}}var a}Object.freeze(["default","global","scoped",xo]);var So={masterMessage:e=>`tinycloud-vault-master-v1:${e}`,identityMessage:"tinycloud-encryption-identity-v1"},Do="x-vault-version",Po="x-vault-cipher",Uo="x-vault-key-id",Lo="x-vault-content-type",Co="x-vault-kdf",Ko="x-vault-key-rotation",$o="x-vault-grant-version",Bo="x-vault-grantor",Vo="signatures",qo="__wrap_key__";function Fo(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof crypto&&void 0!==crypto.subtle}catch{return!1}}function Mo(){return new Promise((e,t)=>{const r=indexedDB.open("tinycloud-vault-cache",1);r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains(Vo)||e.createObjectStore(Vo)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}function jo(e,t){return new Promise((r,n)=>{const s=e.transaction(Vo,"readonly").objectStore(Vo).get(t);s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}function Ho(e,t,r){return new Promise((n,s)=>{const i=e.transaction(Vo,"readwrite").objectStore(Vo).put(r,t);i.onsuccess=()=>n(),i.onerror=()=>s(i.error)})}function Zo(e,t){return new Promise((r,n)=>{const s=e.transaction(Vo,"readwrite").objectStore(Vo).delete(t);s.onsuccess=()=>r(),s.onerror=()=>n(s.error)})}async function Wo(e){const t=await jo(e,qo);if(t)return t;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ho(e,qo,r),r}function zo(e){return`sig:${e}`}async function Go(e){if(!Fo())return null;try{const t=await Mo(),r=await jo(t,zo(e));if(!r)return null;const n=await Wo(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)}(n,r)}catch{return null}}async function Jo(e,t){if(Fo())try{const r=await Mo(),n=await Wo(r),s=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))}}(n,t);await Ho(r,zo(e),s)}catch{}}async function Yo(e){if(Fo())try{const t=await Mo();if(e)await Zo(t,zo(e));else{const e=await function(e){return new Promise((t,r)=>{const n=e.transaction(Vo,"readonly").objectStore(Vo).getAllKeys();n.onsuccess=()=>t(n.result.filter(e=>"string"==typeof e)),n.onerror=()=>r(n.error)})}(t);for(const r of e)r.startsWith("sig:")&&await Zo(t,r)}}catch{}}function Qo(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function Xo(e){return(new TextEncoder).encode(e)}function ec(e){return(new TextDecoder).decode(e)}function tc(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}function rc(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function nc(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 sc(e){return null!==e&&"object"==typeof e&&"data"in e?e.data:e}function ic(e){return"number"==typeof e.meta?.status}function ac(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 oc(e){return{ok:!1,error:{...e,service:"vault",message:ac(e)}}}function cc(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 uc(e){return e.replace(/0x[0-9a-fA-F]{40}/g,e=>e.toLowerCase())}function dc(e,t,r,n){if(!0!==n?.expectAad&&void 0===n?.keyPath)return"ok";const s=function(e,t,r){const n=e;if("object"!=typeof n||null===n||Array.isArray(n)||!["networkId","alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"].every(e=>"string"==typeof n[e]&&""!==n[e])||!Number.isInteger(n.keyVersion)||void 0!==n.aad&&"string"!=typeof n.aad)return"corrupt";let s="";try{"string"==typeof n.aad&&(s=ec(bo(n.aad)))}catch{}const i=`:${r}`;return s.endsWith(i)&&uc(s.slice(0,-i.length))===uc(`tinycloud.vault:${t}`)?"ok":"mismatch"}(e,t,r);if("mismatch"!==s||void 0===n?.keyPath)return s;const{keyPath:i,aad:a}=e;return void 0===i&&void 0===a?"ok":s}var lc=[500,502,503,504,520,522,524];function hc(e,t){const r=Zi(t);if(r)return oc(r);if(t.code===ni.STORAGE_QUOTA_EXCEEDED||t.code===ni.STORAGE_LIMIT_REACHED)return oc({code:t.code,message:t.message,meta:t.meta});const n=`${e}: ${t.message}`;return t.code===ni.AUTH_UNAUTHORIZED?oc({code:"unauthenticated"===aa(t)?"AUTH_UNAUTHORIZED":"PERMISSION_DENIED",message:n,...void 0!==t.meta?{meta:t.meta}:{},cause:cc(t)}):oc({code:"STORAGE_ERROR",cause:new Error(n,{cause:cc(t)}),...void 0!==t.meta?{meta:t.meta}:{}})}function fc(e){return"not_found"===e||"permission_required"===e||"aad_mismatch"===e?e:"read_failed"}function pc(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}(class extends pa{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:[]}}async namedKeys(){const e=this.networkEncryption?.namedKeys;if(void 0===e)throw new Error("Named-key encryption is not configured");return e()}async decryptStored(e,t){const r=this.networkEncryption,{keyPath:n,networkId:s}=Object(e);if(void 0===n)return t?.namedKeyOnly?{ok:!1,error:{code:"LEGACY_ENVELOPE",message:"Envelope is sealed to the network key, not this record's own key"}}:r.service.decryptEnvelope(e,await this.decryptCapabilityProof());if(2!==e.v||n!==t?.keyPath||uc(String(s))!==uc(r.networkId))return{ok:!1,error:{code:"INVALID_ENVELOPE",message:"Envelope is sealed to another key"}};try{return{ok:!0,data:await(await this.namedKeys()).decrypt(e)}}catch(e){if(Zi(e))throw e;const{code:t,status:r,message:i}=e;return{ok:!1,error:401===r||403===r?{code:"DECRYPT_DENIED",message:String(i),permissionHint:{service:"tinycloud.encryption",path:`${s}/${n}`,actions:["tinycloud.encryption/decrypt"]}}:{code:"INVALID_ENVELOPE"===t?t:"DECRYPT_FAILED",message:String(i)}}}}serializeValue(e,t){let r;return r=e instanceof Uint8Array?e:t?.serialize?t.serialize(e):Xo("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(ec(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=So,n=`vault-master:${e}`,s=`vault-identity:${this.tc.address}`;try{if(!this.masterKey){let s=await Go(n);if(!s){if(!t)return oc({code:"VAULT_LOCKED",message:"Signer is required when no cached master signature exists"});s=Xo(await t.signMessage(r.masterMessage(e))),await Jo(n,s)}this.masterKey=this.crypto.deriveKey(s,this.crypto.sha256(Xo(e)),Xo("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:nc(a),privateKey:new Uint8Array(0)};else{let e=await Go(s);if(!e){if(!t)return this.encryptionIdentity=null,this._isUnlocked=!0,si(void 0);e=Xo(await t.signMessage(r.identityMessage)),await Jo(s,e)}const n=this.crypto.deriveKey(e,Xo("tinycloud-x25519"),Xo("encryption-identity"));this.encryptionIdentity=this.crypto.x25519FromSeed(n);try{const e=rc(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,si(void 0)}catch(e){return this.masterKey=null,this.encryptionIdentity=null,oc({code:"STORAGE_ERROR",cause:Qo(e)})}});try{return await this.unlockInFlight}finally{this.unlockInFlight=null}}async clearCache(e){e?await Yo(`vault-master:${e}`):await Yo()}lock(){this.masterKey=null,this.encryptionIdentity=null,this._isUnlocked=!1}onSignOut(){this.lock(),super.onSignOut()}async putNetworkEncrypted(e,t,r){const n=this.networkEncryption;if(!n)return oc({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});if(void 0!==r?.ifMatch){if(void 0!==r.ifNoneMatch)return oc({code:"STORAGE_ERROR",cause:new Error("ifMatch cannot be combined with ifNoneMatch")});if(!/^"[^"\s]+"$/.test(r.ifMatch))return oc({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:s,contentType:i}=this.serializeValue(t,r),a={[Do]:"2",[Po]:"tinycloud-network-envelope",[Lo]:i,...r?.metadata??{}},o=Xo(`tinycloud.vault:${this.vaultConfig.spaceId}:${e}`),c=void 0===r?.keyPath?await n.service.encryptToNetwork(n.networkId,s,{aad:o,metadata:a}):{ok:!0,data:await(await this.namedKeys()).encrypt(r.keyPath,s,{networkId:n.networkId,aad:o,metadata:a,ensureKey:!0})};if(!c.ok){const e=Zi(c.error);return oc(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===ni.KV_PRECONDITION_FAILED)return oc({code:"ALREADY_EXISTS",key:e,...void 0!==h.error.meta?{meta:h.error.meta}:{},cause:cc(h.error)});if(void 0!==r?.ifMatch){const t=function(e,t){const r=t.meta?.status,n=t.code===ni.KV_PRECONDITION_FAILED?"ETAG_MISMATCH":t.code===ni.KV_WRITE_FAILED&&400===r?"INVALID_ETAG":t.code===ni.OUTCOME_UNKNOWN||t.code===ni.KV_WRITE_FAILED&&"number"==typeof r&&lc.includes(r)||(t.code===ni.NETWORK_ERROR||t.code===ni.TIMEOUT)&&void 0===r&&!1!==t.meta?.requestMayHaveDispatched?"OUTCOME_UNKNOWN":t.code===ni.NODE_BUSY||t.code===ni.REQUEST_TIMEOUT?"NODE_BUSY":void 0;if(void 0!==n)return oc({code:n,key:e,message:t.message,...void 0!==t.meta?{meta:t.meta}:{},cause:cc(t)})}(e,h.error);if(void 0!==t)return t}return hc("Failed to store encrypted value",h.error)}return{ok:!0,data:void 0}}catch(e){const t=Zi(e);return oc(t||{code:"STORAGE_ERROR",cause:Qo(e)})}}async getNetworkEncrypted(e,t){if(!this.networkEncryption)return oc({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!r.ok){const t=Zi(r.error);return oc(t||{code:"KEY_NOT_FOUND",key:e})}const n=sc(r.data),s="string"==typeof n?JSON.parse(n):n,i=dc(s,this.vaultConfig.spaceId,e,t);if("corrupt"===i)return oc({code:"DECRYPTION_FAILED",message:"envelope is malformed"});if("mismatch"===i)return oc({code:"AAD_MISMATCH",key:e,message:`Envelope at ${e} is not bound to this space and key`});const a=await this.decryptStored(s,t);if(!a.ok){const t=Zi(a.error);if(t)return oc(t);const{code:r,message:n,permissionHint:s}=a.error;return oc("LEGACY_ENVELOPE"===r?{code:r,key:e,message:n}:"DECRYPT_DENIED"===r&&void 0!==s?{code:r,key:e,message:n,permissionHint:s}:{code:"DECRYPTION_FAILED",message:n})}const o=s.metadata??{},c=o[Lo]??"application/json",u=o[Uo]??s.encryptedSymmetricKeyHash.slice(0,16),d=this.deserializeValue(a.data,c,t),l="network"===t?.source?r.data.headers?.etag:void 0;return{ok:!0,data:{value:d,metadata:o,keyId:u,...void 0===l?{}:{etag:l}}}}catch(e){const t=Zi(e);return oc(t||{code:"STORAGE_ERROR",cause:Qo(e)})}}async readNetworkEncrypted(e,t){const r=await this.fetchNetworkEnvelope(e);if("fetched"!==r.status)return r;const{envelope:n,etag:s}=r,i=dc(n,this.vaultConfig.spaceId,e,t);if("ok"!==i)return{status:"corrupt"===i?"corrupt_envelope":"aad_mismatch"};const a=await this.openStored(n,t);if("opened"!==a.status)return a;try{const e=n.metadata??{},r=e[Lo]??"application/json",i=e[Uo]??n.encryptedSymmetricKeyHash.slice(0,16);return{status:"ok",entry:{value:this.deserializeValue(a.plaintext,r,t),metadata:e,keyId:i,...void 0===s?{}:{etag:s}}}}catch{return{status:"invalid_payload"}}}async resealToKey(e,t,r){const n=e.startsWith("secrets/")?function(e){return Io(e,Oo)}(e.slice(8)):void 0;if(void 0===n||function(e,t){if(!Oo.test(e)||void 0!==t&&(!Ao.test(t)||t.length>64))throw new Error("A secret's key needs a name and scope of at most 64 bytes, scope in canonical form");if(void 0===t&&"SCOPED"===e)throw new Error(`Secret name ${JSON.stringify(e)} is reserved.`);if(t===xo)throw new Error(`Secret scope ${JSON.stringify(t)} is reserved.`);return`${void 0===t?"secrets/":`secrets/scoped/${t}/`}${e.toLowerCase()}`}(n.name,n.scope)!==t)throw new Error(`resealToKey: ${JSON.stringify(t)} is not the own key of ${JSON.stringify(e)}`);const s=this.networkEncryption;if(!s||!this.requireAuth())return{status:"skipped",reason:"read_failed"};const i=`tinycloud.vault:${this.vaultConfig.spaceId}:${e}`;for(let n=0;;n++){const a=await this.fetchNetworkEnvelope(e);if("fetched"!==a.status)return{status:"skipped",reason:fc(a.status)};const{envelope:o,etag:c}=a,u=dc(o,this.vaultConfig.spaceId,e,{keyPath:t});if("ok"!==u)return{status:"skipped",reason:"corrupt"===u?"read_failed":"aad_mismatch"};if(o.keyPath===t&&2===o.v&&uc(String(o.networkId))===uc(s.networkId))return{status:"already"};if(!0===r?.dryRun)return{status:"pending"};if(void 0===c)return{status:"skipped",reason:"write_failed"};const d=await this.openStored(o,{keyPath:t});if("opened"!==d.status)return{status:"skipped",reason:fc(d.status)};let l,h,f;try{l=await this.namedKeys(),h=await l.encrypt(t,d.plaintext,{networkId:s.networkId,aad:Xo(i),metadata:o.metadata??{},ensureKey:!0})}catch(e){if(Zi(e))throw e;const{status:t}=e;return{status:"skipped",reason:401===t||403===t?"permission_required":"write_failed"}}try{if(!pc(await l.decrypt(h),d.plaintext))return{status:"skipped",reason:"verify_failed"}}catch(e){if(Zi(e))throw e;return{status:"skipped",reason:"verify_failed"}}try{f=await this.tc.kv.put(`vault/${e}`,JSON.stringify(h),{ifMatch:c})}catch(e){if(Zi(e))throw e;return{status:"skipped",reason:"write_failed"}}if(f.ok)return{status:"moved"};if(Zi(f.error))throw f.error;if(f.error.code!==ni.KV_PRECONDITION_FAILED)return{status:"skipped",reason:"write_failed"};if(n>0)return{status:"skipped",reason:"conflict"}}}async fetchNetworkEnvelope(e){if(!this.networkEncryption||!this.requireAuth())return{status:"read_failed"};let t;try{t=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"})}catch(e){if(Zi(e))throw e;return{status:"node_unreachable"}}if(!t.ok){if(Zi(t.error))throw t.error;const e=Wi(t.error.meta?.permissionHint);return"AUTH_UNAUTHORIZED"===t.error.code&&void 0!==e?{status:"permission_required",hint:e}:"NOT_FOUND"!==t.error.code&&"KV_NOT_FOUND"!==t.error.code||ic(t.error)?"NODE_NOT_RESPONDING"===t.error.code||"NETWORK_ERROR"===t.error.code||"TIMEOUT"===t.error.code||"ABORTED"===t.error.code?ic(t.error)?{status:"read_failed"}:{status:"node_unreachable"}:{status:"read_failed"}:{status:"not_found"}}try{const e=sc(t.data);return{status:"fetched",envelope:"string"==typeof e?JSON.parse(e):e,etag:t.data.headers?.etag}}catch{return{status:"corrupt_envelope"}}}async openStored(e,t){let r;try{r=await this.decryptStored(e,t)}catch(e){if(Zi(e))throw e;return{status:"decrypt_failed"}}if(r.ok)return{status:"opened",plaintext:r.data};if(Zi(r.error))throw r.error;const n=Wi(r.error.permissionHint);return"DECRYPT_DENIED"===r.error.code&&void 0!==n?{status:"permission_required",hint:n}:"INVALID_ENVELOPE"===r.error.code?{status:"corrupt_envelope"}:"LEGACY_ENVELOPE"===r.error.code?{status:"legacy_envelope"}:"NODE_NOT_RESPONDING"===r.error.code||"TRANSPORT_ERROR"===r.error.code?{status:"node_unreachable"}:{status:"decrypt_failed"}}async headNetworkEncrypted(e){if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"});if(!t.ok)return oc({code:"KEY_NOT_FOUND",key:e});const r=sc(t.data);return{ok:!0,data:("string"==typeof r?JSON.parse(r):r).metadata??{}}}catch(e){return oc({code:"STORAGE_ERROR",cause:Qo(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 oc({code:"STORAGE_ERROR",cause:new Error("ifNoneMatch is only supported by network-encrypted vaults")});if(void 0!==r?.ifMatch)return oc({code:"STORAGE_ERROR",cause:new Error("ifMatch is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return oc({code:"VAULT_LOCKED",message:"Vault must be unlocked before storing data"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{let n;n=t instanceof Uint8Array?t:r?.serialize?r.serialize(t):Xo("string"==typeof t?t:JSON.stringify(t));const s=r?.contentType??(t instanceof Uint8Array?"application/octet-stream":"application/json"),i=this.crypto.randomBytes(32),a=tc(this.crypto.sha256(i)).slice(0,16),o=this.crypto.encrypt(i,n),c=this.crypto.encrypt(this.masterKey,i),u={[Do]:"1",[Po]:"aes-256-gcm",[Uo]:a,[Lo]:s,[Co]:"hkdf-sha256",[Ko]:this.vaultConfig.keyRotation??"per-write",...r?.metadata??{}},d=JSON.stringify({keyId:a,contentType:s,...u}),l=JSON.stringify({key:rc(c),metadata:d}),h=await this.tc.kv.put(`keys/${e}`,l);if(!h.ok)return hc("Failed to store key blob",h.error);const f=JSON.stringify({data:rc(o),metadata:u}),p=await this.tc.kv.put(`vault/${e}`,f);return p.ok?si(void 0):hc("Failed to store encrypted value",p.error)}catch(e){return oc({code:"STORAGE_ERROR",cause:Qo(e)})}})}async get(e,t){return this.withTelemetry("get",e,async()=>{if(this.usesNetworkEncryption)return this.getNetworkEncrypted(e,t);if(!0===t?.expectAad)return oc({code:"STORAGE_ERROR",cause:new Error("expectAad is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return oc({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading data"});if(!this.requireAuth())return oc({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 oc({code:"KEY_NOT_FOUND",key:e});const n=nc(JSON.parse(r.data.data).key),s=this.crypto.decrypt(this.masterKey,n),i=await this.tc.kv.get(`vault/${e}`,{raw:!0,...void 0===t?.source?{}:{source:t.source}});if(!i.ok)return oc({code:"KEY_NOT_FOUND",key:e});const a=JSON.parse(i.data.data),o=nc(a.data),c=this.crypto.decrypt(s,o),u=a.metadata??{},d=u[Lo]??"application/json",l=u[Uo]??"";let h;return h=t?.raw?c:t?.deserialize?t.deserialize(c):"application/json"===d?JSON.parse(ec(c)):c,si({value:h,metadata:u,keyId:l})}catch(e){return e instanceof Error&&e.message.includes("decryption")?oc({code:"DECRYPTION_FAILED",message:e.message}):oc({code:"STORAGE_ERROR",cause:Qo(e)})}})}async delete(e){return this.withTelemetry("delete",e,async()=>{if(!this.isUnlocked)return oc({code:"VAULT_LOCKED",message:"Vault must be unlocked before deleting data"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{if(this.usesNetworkEncryption){const t=await this.tc.kv.delete(`vault/${e}`);if(!t.ok){const r=Zi(t.error);return oc(r||{code:"KEY_NOT_FOUND",key:e})}return si(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 n=Zi(t.error)??Zi(r.error);return oc(n||{code:"KEY_NOT_FOUND",key:e})}return si(void 0)}catch(e){const t=Zi(e);return oc(t||{code:"STORAGE_ERROR",cause:Qo(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 oc({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing data"});if(!this.requireAuth())return oc({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=Zi(r.error);return oc(e||{code:"STORAGE_ERROR",cause:new Error(`Failed to list vault keys: ${r.error.message}`)})}let n=r.data.keys;if(e?.removePrefix&&e.prefix){const t=e.prefix.endsWith("/")?e.prefix:`${e.prefix}/`;n=n.map(e=>e.startsWith(t)?e.slice(t.length):e)}return si({keys:n,truncated:!0===r.data.truncated,...void 0===r.data.nextCursor?{}:{nextCursor:r.data.nextCursor}})}catch(e){const t=Zi(e);return oc(t||{code:"STORAGE_ERROR",cause:Qo(e)})}})}async head(e){return this.withTelemetry("head",e,async()=>{if(this.usesNetworkEncryption)return this.headNetworkEncrypted(e);if(!this._isUnlocked)return oc({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading metadata"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0});if(!t.ok)return oc({code:"KEY_NOT_FOUND",key:e});return si(JSON.parse(t.data.data).metadata??{})}catch(e){return oc({code:"STORAGE_ERROR",cause:Qo(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 oc({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 oc({code:"VAULT_LOCKED",message:"Vault must be unlocked before granting access"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=await this.resolvePublicKey(t);if(!n.ok)return n;const s=n.data,i=await this.tc.kv.get(`keys/${e}`,{raw:!0});if(!i.ok)return oc({code:"KEY_NOT_FOUND",key:e});const a=nc(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,s),l=this.crypto.deriveKey(d,Xo("tinycloud-x25519"),Xo("vault-grant")),h=this.crypto.encrypt(l,o),f=function(...e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}(u.publicKey,h),p=JSON.stringify({grant:rc(f),spaceId:this.vaultConfig.spaceId,metadata:{[$o]:"1",[Bo]:this.tc.did,...r?.metadata??{}}}),y=await this.tc.kv.put(`grants/${t}/${e}`,p);return y.ok?si(void 0):hc("Failed to store grant",y.error)}catch(e){return oc({code:"STORAGE_ERROR",cause:Qo(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 oc({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 oc({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv.")});const n=this.networkEncryption;if(!n)return oc({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=await e.get(`vault/${t}`,{raw:!0});if(!s.ok)return oc({code:"KEY_NOT_FOUND",key:t});const i=sc(s.data),a="string"==typeof i?JSON.parse(i):i,o=await this.decryptCapabilityProof(),c=await n.service.decryptEnvelope(a,o);if(!c.ok)return oc({code:"DECRYPTION_FAILED",message:c.error.message});const u=a.metadata??{},d=u[Lo]??"application/json",l=u[Uo]??a.encryptedSymmetricKeyHash.slice(0,16);return{ok:!0,data:{value:this.deserializeValue(c.data,d,r),metadata:u,keyId:l}}}catch(e){return oc({code:"STORAGE_ERROR",cause:Qo(e)})}}if(!this._isUnlocked||!this.masterKey||!this.encryptionIdentity)return oc({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading shared data"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=this.tc.did,s=r?.kv;if(!s)return oc({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 s.get(`grants/${n}/${t}`,{raw:!0});if(!i.ok)return oc({code:"GRANT_NOT_FOUND",grantor:e,key:t});const a=nc(("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,Xo("tinycloud-x25519"),Xo("vault-grant")),l=this.crypto.decrypt(d,c),h=await s.get(`vault/${t}`,{raw:!0});if(!h.ok)return oc({code:"KEY_NOT_FOUND",key:t});const f="string"==typeof h.data?.data?JSON.parse(h.data.data):h.data?.data,p=nc(f.data),y=this.crypto.decrypt(l,p),m=f.metadata??{},g=m[Lo]??"application/json",v=m[Uo]??"";let _;return _=r?.raw?y:r?.deserialize?r.deserialize(y):"application/json"===g?JSON.parse(ec(y)):y,si({value:_,metadata:m,keyId:v})}catch(e){return e instanceof Error&&e.message.includes("decryption")?oc({code:"DECRYPTION_FAILED",message:e.message}):oc({code:"STORAGE_ERROR",cause:Qo(e)})}})}async resolvePublicKey(e){try{const t=this.parseDID(e);if(!t)return oc({code:"PUBLIC_KEY_NOT_FOUND",did:e});const r=this.tc.makePublicSpaceId(t.address,t.chainId),n=await this.tc.readPublicSpace(this.host,r,".well-known/vault-pubkey");return n.ok?{ok:!0,data:nc(n.data)}:oc({code:"PUBLIC_KEY_NOT_FOUND",did:e})}catch(t){return oc({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 oc({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing grants"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.list({prefix:"grants/",removePrefix:!0});if(!t.ok)return oc({code:"STORAGE_ERROR",cause:new Error(`Failed to list grants: ${t.error.message}`)});const r=[];for(const n of t.data.keys)if(n.endsWith(`/${e}`)){const t=n.slice(0,n.length-e.length-1);t&&r.push(t)}return si(r)}catch(e){return oc({code:"STORAGE_ERROR",cause:Qo(e)})}})}async revoke(e,t){return this.withTelemetry("revoke",e,async()=>{if(this.usesNetworkEncryption)return oc({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 oc({code:"VAULT_LOCKED",message:"Vault must be unlocked before revoking access"});if(!this.requireAuth())return oc({code:"VAULT_LOCKED",message:"Authentication required"});try{const r=await this.listGrants(e);if(!r.ok)return r;const n=r.data.filter(e=>e!==t),s=(await this.tc.kv.delete(`grants/${t}/${e}`),await this.get(e));if(!s.ok)return s;const i=s.data,a=this.crypto.randomBytes(32),o=tc(this.crypto.sha256(a)).slice(0,16);let c;c=i.value instanceof Uint8Array?i.value:Xo(JSON.stringify(i.value));const u=this.crypto.encrypt(a,c),d=this.crypto.encrypt(this.masterKey,a),l={...i.metadata,[Uo]:o},h=JSON.stringify({key:rc(d),metadata:JSON.stringify({keyId:o,...l})}),f=await this.tc.kv.put(`keys/${e}`,h);if(!f.ok)return hc("Failed to store rotated key blob",f.error);const p=JSON.stringify({data:rc(u),metadata:l}),y=await this.tc.kv.put(`vault/${e}`,p);if(!y.ok)return hc("Failed to store re-encrypted value",y.error);for(const t of n)(await this.reencrypt(e,t)).ok;return si(void 0)}catch(e){return oc({code:"STORAGE_ERROR",cause:Qo(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),n=t[4];return isNaN(r)||!n?null:{address:n,chainId:r}}}).serviceName="vault";var yc="tinycloud.encryption.decrypt/v1",mc="tinycloud.encryption.decrypt-result/v1";function gc(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 vc(e){return{...e,service:"encryption",message:gc(e)}}function _c(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function kc(e,t,r,n){let s;try{s=$i(e.networkId)}catch(e){return{ok:!1,error:vc({code:"INVALID_NETWORK_ID",message:`descriptor networkId is malformed: ${e instanceof Error?e.message:String(e)}`})}}if(s.name!==n||!qi(s.ownerDid,r))return{ok:!1,error:vc({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&&qi(i,r)&&qi(i,s.ownerDid)?e.name!==n?{ok:!1,error:vc({code:"INVALID_NETWORK_ID",message:"descriptor name does not match networkId name"})}:"string"!=typeof e.publicEncryptionKey||0===e.publicEncryptionKey.length?{ok:!1,error:vc({code:"INVALID_NETWORK_ID",message:"descriptor publicEncryptionKey must be a non-empty string"})}:{ok:!0,data:{...e,ownerDid:i}}:{ok:!1,error:vc({code:"INVALID_NETWORK_ID",message:"descriptor ownerDid does not match networkId ownerDid"})}}function wc(e){return"active"===e.state||"rotating"===e.state?{ok:!0,data:e}:{ok:!1,error:vc({code:"NETWORK_NOT_ACTIVE",state:e.state})}}var Ec="x25519-hkdf-aes256gcm/v2",bc=To("TCW2"),Tc=To("tinycloud.encryption.key-wrap/v2");function Nc(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let r=0;for(const n of e)t.set(n,r),r+=n.length;return t}function Oc(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}function xc(e){if("string"!=typeof e)throw new Error("Invalid key wrap encoding");const t=bo(e);if(32!==t.length||Eo(t)!==e)throw new Error("Invalid key wrap encoding");return t}function Rc(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=55296&&r<=56319){const r=e.charCodeAt(++t);if(!(r>=56320&&r<=57343))return!1}else if(r>=56320&&r<=57343)return!1}return!0}function Ac(e){if("network-key"!==e.purpose&&"receiver-key"!==e.purpose||"string"!=typeof e.networkId||"string"!=typeof e.keyPath||!Rc(e.networkId)||!Rc(e.keyPath)||!Number.isSafeInteger(e.keyVersion)||e.keyVersion<=0||!e.metadata||"object"!=typeof e.metadata||Array.isArray(e.metadata)||Object.entries(e.metadata).some(([e,t])=>!Rc(e)||"string"!=typeof t||!Rc(t)))throw new Error("Invalid key wrap context");if(""!==e.networkId){const t=Bi(""===e.keyPath?e.networkId:`${e.networkId}/${e.keyPath}`);if(t.networkId!==e.networkId||(t.keyPath??"")!==e.keyPath||e.keyPath.endsWith("/"))throw new Error("Invalid key wrap resource")}}function Ic(e){return e.length>=4&&bc.every((t,r)=>e[r]===t)}function Sc(e){if(!Ic(e)||e.length<8)throw new Error("Invalid v2 key wrap frame");const t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(4);if(0===t||t>65536||e.length<8+t+12+16)throw new Error("Invalid v2 key wrap length");const r=e.subarray(8,8+t),n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r)),s=["v","alg","kdf","aead","salt","ephemeralPublicKey","recipientPublicKey","purpose","networkId","keyPath","keyVersion","metadata"].sort();if(!n||"object"!=typeof n||Array.isArray(n)||Object.keys(n).sort().join(",")!==s.join(",")||2!==n.v||n.alg!==Ec||"hkdf-sha256"!==n.kdf||"aes-256-gcm"!==n.aead)throw new Error("Invalid v2 key wrap header");if(Ac(n),xc(n.salt),xc(n.ephemeralPublicKey),xc(n.recipientPublicKey),!Oc(r,To(vo({...n}))))throw new Error("Non-canonical v2 key wrap header");const i=8+t;return{header:n,aad:e.subarray(0,i),nonce:e.subarray(i,i+12),ciphertext:e.subarray(i+12)}}function Dc(e,t){Ac(t);for(const r of["purpose","networkId","keyPath","keyVersion"])if(e[r]!==t[r])throw new Error("Key wrap context mismatch");if(vo(e.metadata)!==vo(t.metadata))throw new Error("Key wrap metadata mismatch")}function Pc(e,t,r=!1){if("x25519-aes256gcm/v1"!==t&&t!==Ec)throw new Error("Unsupported key wrap algorithm");if(r&&t!==Ec)throw new Error("V2 network key wrap required");if(Ic(e)!==(t===Ec))throw new Error("Key wrap algorithm mismatch");t===Ec&&Sc(e)}function Uc(e,t=!1){const r=bo(e.encryptedSymmetricKey);Pc(r,e.alg,t),e.alg===Ec&&Dc(Sc(r).header,{purpose:"network-key",networkId:e.networkId,keyPath:e.keyPath??"",keyVersion:e.keyVersion,metadata:e.metadata??{}})}function Lc(e){return{ok:!0,data:e}}function Cc(e){return{ok:!1,error:e}}function Kc(e){return vc("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 pa{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,n;try{if(e.identifier.startsWith("urn:tinycloud:encryption:")){const s=$i(e.identifier);t=s.networkId,r=s.ownerDid,n=s.name}else{if(void 0===e.ownerDid)return{ok:!1,error:vc({code:"INVALID_INPUT",message:"discoverNetwork requires `ownerDid` when identifier is a bare network name"})};t=`urn:tinycloud:encryption:${e.ownerDid}:${e.identifier}`;const s=$i(t);r=s.ownerDid,n=s.name}}catch(e){if(e instanceof Ki)return{ok:!1,error:vc({code:"INVALID_NETWORK_ID",message:e.message})};throw e}if(void 0!==e.node)try{const s=await e.node.fetchByNetworkId(t);if(null!==s){const e=kc(s,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"node"}}:e}}catch(e){const t=Zi(e);return t?{ok:!1,error:vc(t)}:{ok:!1,error:vc({code:"TRANSPORT_ERROR",cause:e instanceof Error?e:new Error(String(e))})}}if(void 0!==e.wellKnown)try{const s=await e.wellKnown.fetchWellKnown(r,function(e){if(!Li.test(e))throw new Ki(`network name ${JSON.stringify(e)} must match ${Li.source}`);return`.well-known/encryption/network/${e}`}(n));if(null!==s){const e=kc(s,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"well-known"}}:e}}catch(e){const t=Zi(e);if(t)return{ok:!1,error:vc(t)}}return{ok:!1,error:vc({code:"NETWORK_NOT_FOUND",networkId:t,name:n})}}({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?Lc(r.data.descriptor):r}async encryptToNetwork(e,t,r){try{this.assertActive();const n=await this.discoverNetwork(e);if(!n.ok)return n;const s=wc(n.data);if(!s.ok)return s;const i=s.data,a=bo(i.publicEncryptionKey);return Lc(function(e,t){if(Bi(void 0===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`).keyPath!==t.keyPath||t.keyPath?.endsWith("/"))throw new Ki("keyPath must name an exact encryption key");const r=t.keyWrapV2?Ec:"x25519-aes256gcm/v1";if(void 0!==t.alg&&t.alg!==r)throw new Error("Algorithm does not match keyWrapV2");const n=t.keyVersion??1,s=e.randomBytes(32),i=e.authEncrypt(s,t.plaintext,t.aad),a=t.keyWrapV2?function(e,t,r){if(Ac(r),32!==e.length)throw new Error("Invalid recipient public key");const n=Cr(32),s=Bs.getPublicKey(n),i=Cr(32),a=To(vo({...{...r,v:2,alg:Ec,kdf:"hkdf-sha256",aead:"aes-256-gcm",salt:Eo(i),ephemeralPublicKey:Eo(s),recipientPublicKey:Eo(e)}}));if(a.length>65536)throw new Error("Key wrap header too large");const o=new Uint8Array(8);o.set(bc),new DataView(o.buffer).setUint32(4,a.length);const c=Nc(o,a),u=Cr(12);let d;try{const r=Bs.getSharedSecret(n,e);try{if(r.every(e=>0===e))throw new Error("Invalid key agreement");d=ei(ti,r,i,Nc(Tc,s,e),32)}finally{r.fill(0)}return Nc(c,u,yr(d,u,c).encrypt(t))}finally{n.fill(0),d?.fill(0)}}(t.networkPublicKey,s,{purpose:"network-key",networkId:t.networkId,keyPath:t.keyPath??"",keyVersion:n,metadata:t.metadata??{}}):e.sealToNetworkKey(t.networkPublicKey,s),o=Eo(a),c=No(e.sha256,o);return{envelope:{v:1,networkId:t.networkId,...void 0!==t.keyPath?{keyPath:t.keyPath}:{},alg:r,keyVersion:n,encryptedSymmetricKey:o,encryptedSymmetricKeyHash:c,ciphertext:Eo(i),...void 0!==t.aad?{aad:Eo(t.aad)}:{},...void 0!==t.metadata?{metadata:t.metadata}:{}},symmetricKey:s}}(this.crypto,{networkId:i.networkId,...void 0!==r?.keyPath?{keyPath:r.keyPath}:{},networkPublicKey:a,plaintext:t,...void 0!==r?.aad?{aad:r.aad}:{},keyWrapV2:r?.keyWrapV2??this._config.keyWrapV2??!1,...void 0!==r?.alg?{alg:r.alg}:{},keyVersion:r?.keyVersion??i.keyVersion,...void 0!==r?.metadata?{metadata:r.metadata}:{}}).envelope)}catch(e){const t=Zi(e);return Cc(vc(t||{code:"TRANSPORT_ERROR",cause:_c(e)}))}}async decryptEnvelope(e,t,r){try{this.assertActive();const s=function(e,t,r=!1){if(null===t||"object"!=typeof t)return{ok:!1,error:vc({code:"INVALID_ENVELOPE",message:"envelope must be an object"})};const n=t;if(1!==n.v)return{ok:!1,error:vc({code:"INVALID_ENVELOPE",message:`envelope.v must be 1 (got ${n.v})`})};try{if(void 0!==Bi(n.networkId).keyPath)throw new Error("networkId must identify the network root");if(void 0!==n.keyPath){if("string"!=typeof n.keyPath)throw new Error("keyPath must be a string");if(Bi(`${n.networkId}/${n.keyPath}`).keyPath!==n.keyPath||n.keyPath.endsWith("/"))throw new Error("keyPath must name an exact encryption key")}}catch(e){return{ok:!1,error:vc({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 n[e]||0===n[e].length)return{ok:!1,error:vc({code:"INVALID_ENVELOPE",message:`envelope.${e} must be a non-empty string`})};if("number"!=typeof n.keyVersion||!Number.isInteger(n.keyVersion))return{ok:!1,error:vc({code:"INVALID_ENVELOPE",message:"envelope.keyVersion must be an integer"})};if(No(e.sha256,n.encryptedSymmetricKey)!==n.encryptedSymmetricKeyHash)return{ok:!1,error:vc({code:"INVALID_ENVELOPE",message:"envelope.encryptedSymmetricKeyHash does not match canonical hash of encryptedSymmetricKey"})};try{Uc(n,r)}catch{return{ok:!1,error:vc({code:"INVALID_ENVELOPE",message:"Envelope key wrap context is invalid"})}}return{ok:!0,data:n}}(this.crypto,e,this._config.requireKeyWrapV2??!1);if(!s.ok)return s;if(void 0!==r?.aad&&s.data.aad!==Eo(r.aad))return Cc(vc({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 Cc(Kc(t.error));i=t.data}const a=wc(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 Cc(vc({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 Cc(vc({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=Eo(c.publicKey),d=No(this.crypto.sha256,u),l={type:yc,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:vo((n={crypto:this.crypto,body:l,receiverPublicKey:c.publicKey}).body),bodyHash:No(n.crypto.sha256,n.body),receiverPublicKeyHash:No(n.crypto.sha256,n.body.receiverPublicKey)},f=function(e){const t=void 0!==e.canonicalBody?wo(e.crypto.sha256(To(e.canonicalBody))):No(e.crypto.sha256,e.body),r=No(e.crypto.sha256,e.body.receiverPublicKey);return{type:yc,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}),p=await async function(e,t,r){const n=function(e,t){if(t.body.type!==yc)return{ok:!1,error:vc({code:"INVALID_INPUT",message:`body.type must be ${yc}`})};if(t.facts.type!==yc)return{ok:!1,error:vc({code:"INVALID_INPUT",message:`facts.type must be ${yc}`})};if(t.facts.targetNode!==t.targetNode)return{ok:!1,error:vc({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:vc({code:"INVALID_INPUT",message:"body.targetNode must equal targetNode"})};if(t.facts.networkId!==t.networkId)return{ok:!1,error:vc({code:"INVALID_INPUT",message:"facts.networkId must equal networkId"})};if(t.body.networkId!==t.networkId)return{ok:!1,error:vc({code:"INVALID_INPUT",message:"body.networkId must equal networkId"})};if(t.facts.keyPath!==t.body.keyPath)return{ok:!1,error:vc({code:"INVALID_INPUT",message:"facts.keyPath must equal body.keyPath"})};if(t.facts.alg!==t.body.alg)return{ok:!1,error:vc({code:"INVALID_INPUT",message:"facts.alg must equal body.alg"})};if(t.facts.keyVersion!==t.body.keyVersion)return{ok:!1,error:vc({code:"INVALID_INPUT",message:"facts.keyVersion must equal body.keyVersion"})};if(t.facts.encryptedSymmetricKeyHash!==t.body.encryptedSymmetricKeyHash)return{ok:!1,error:vc({code:"INVALID_INPUT",message:"facts.encryptedSymmetricKeyHash must equal body.encryptedSymmetricKeyHash"})};if(t.facts.receiverPublicKeyHash!==t.body.receiverPublicKeyHash)return{ok:!1,error:vc({code:"INVALID_INPUT",message:"facts.receiverPublicKeyHash must equal body.receiverPublicKeyHash"})};try{if(void 0!==Bi(t.networkId).keyPath)throw new Ki("networkId must identify the network root")}catch(e){return{ok:!1,error:vc({code:"INVALID_NETWORK_ID",message:e instanceof Error?e.message:String(e)})}}try{if(Bi(void 0===t.body.keyPath?t.body.networkId:`${t.body.networkId}/${t.body.keyPath}`).keyPath!==t.body.keyPath||t.body.keyPath?.endsWith("/"))throw new Ki("keyPath must name an exact encryption key")}catch(e){return{ok:!1,error:vc({code:"INVALID_INPUT",message:e instanceof Error?e.message:String(e)})}}const r=vo(t.body);return No(e.sha256,t.body)!==t.facts.bodyHash?{ok:!1,error:vc({code:"INVALID_INPUT",message:"facts.bodyHash does not match the canonical body hash"})}:{ok:!0,data:t,canonicalBody:r}}(e,r);if(!n.ok)return n;try{const e=await t.signDecryptInvocation(n.data);return e.authorization&&e.invocationCid?e.canonicalBody!==n.canonicalBody?{ok:!1,error:vc({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:vc({code:"INVALID_INPUT",message:"decrypt-invocation signer returned an empty authorization or invocationCid"})}}catch(e){return{ok:!1,error:vc({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:f,proof:t});if(this.assertActive(),!p.ok)return"TRANSPORT_ERROR"!==p.error.code?p:Cc(vc({code:"INVALID_INPUT",message:"Unable to build decrypt request"}));let y;try{y=await this._config.transport.postDecrypt({targetNode:o,networkId:e.networkId,authorization:p.data.authorization,canonicalBody:p.data.canonicalBody,signal:this.abortSignal}),this.assertActive()}catch(t){const r=Zi(t);return r?Cc(Kc(r)):t instanceof ri.DecryptTransportResponseError?Cc(vc(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"})):Cc(Kc({code:"TRANSPORT_ERROR",cause:_c(t)}))}const m=function(e){const{crypto:t,request:r,facts:n,invocationCid:s,requestBodyHash:i,response:a}=e;if(a.type!==mc)return{ok:!1,error:vc({code:"INVALID_RESPONSE",message:`response.type must be ${mc}`})};if(a.targetNode!==r.targetNode)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(a.networkId!==r.networkId)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(a.nodeId!==r.targetNode)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if("x25519-aes256gcm/v1"!==a.alg&&a.alg!==Ec)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(a.keyVersion!==r.keyVersion)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(a.encryptedSymmetricKeyHash!==r.encryptedSymmetricKeyHash)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(a.receiverPublicKeyHash!==r.receiverPublicKeyHash)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(a.invocationCid!==s)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const o=wo(t.sha256(To(`${s}${i}`)));if(a.requestHash!==o)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(n.encryptedSymmetricKeyHash!==a.encryptedSymmetricKeyHash||n.receiverPublicKeyHash!==a.receiverPublicKeyHash||n.networkId!==a.networkId||n.targetNode!==a.targetNode||n.alg!==r.alg||n.keyVersion!==a.keyVersion)return{ok:!1,error:vc({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const c=(new TextEncoder).encode(function(e){const{nodeSignature:t,...r}=e;return vo(r)}(a)),u=bo(a.nodeSignature);return t.verifyNodeSignature(a.nodeId,c,u)?{ok:!0,data:a}:{ok:!1,error:vc({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:this.crypto,request:l,facts:f,invocationCid:p.data.invocationCid,requestBodyHash:f.bodyHash,response:y});if(!m.ok)return m;const g=function(e,t,r,n){const s=bo(r.wrappedKey);if(Pc(s,r.alg),r.alg===Ec){if(!n)throw new Error("V2 response requires expected key context");return function(e,t,r){const{header:n,aad:s,nonce:i,ciphertext:a}=Sc(t);Dc(n,r);const o=Bs.getPublicKey(e);if(!Oc(o,xc(n.recipientPublicKey)))throw new Error("Key wrap recipient mismatch");const c=function(e,t,r,n){const s=Bs.getSharedSecret(e,t);if(s.every(e=>0===e))throw new Error("Invalid key agreement");try{return ei(ti,s,n,Nc(Tc,t,r),32)}finally{s.fill(0)}}(e,xc(n.ephemeralPublicKey),o,xc(n.salt));try{return yr(c,i,s).decrypt(a)}finally{c.fill(0)}}(t,s,n)}return e.openWithReceiverKey(t,s)}(this.crypto,c.privateKey,m.data,{purpose:"receiver-key",networkId:l.networkId,keyPath:l.keyPath??"",keyVersion:l.keyVersion,metadata:{}}),v=function(e,t,r){Uc(t);const n=bo(t.ciphertext),s=void 0!==t.aad?bo(t.aad):void 0;return e.authDecrypt(r,n,s)}(this.crypto,e,g);return Lc(v)}catch(e){const t=Zi(e);return Cc(t?Kc(t):vc({code:"INVALID_RESPONSE",message:"Local decryption failed"}))}var n}assertActive(){this._config.assertActive?.()}}).serviceName="encryption";var $c=Fe({kty:Ke(),crv:Ke().optional(),x:Ke().optional(),y:Ke().optional(),d:Ke().optional(),e:Ke().optional(),n:Ke().optional(),kid:Ke().optional(),alg:Ke().optional(),use:Ke().optional(),key_ops:qe(Ke()).optional()}),Bc=Ze(["main","session","ingested"]),Vc=Fe({id:Ke(),did:Ke(),type:Bc,jwk:$c.optional(),priority:$e()}),qc=(Fe({code:Ke(),message:Ke(),service:He("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>Le(t=>t instanceof e,t))(Error).optional(),meta:je(Ke(),Ve()).optional()}),"NOT_INITIALIZED"),Fc="NETWORK_ERROR",Mc="INVALID_INPUT",jc="INVALID_TOKEN",Hc=Fe({cid:Ke(),delegateDID:Ke(),spaceId:Ke(),path:Ke(),actions:qe(Ke()),caveats:qe(je(Ke(),Ve())).optional(),expiry:We(),isRevoked:Be(),delegatorDID:Ke().optional(),createdAt:We().optional(),parentCid:Ke().optional(),allowSubDelegation:Be().optional(),authHeader:Ke().optional()}),Zc=Fe({cid:Ke().min(1),lease_cid:Ke().min(1),generation:$e().int().nonnegative().safe(),previous_stamp_cid:Ke().min(1),new_end:$e().int().nonnegative().safe(),signed_bytes:Ke().min(1),signature:Ke().min(1)}).strict(),Wc=(Fe({cid:Ke().min(1),status:Ze(["active","revoked","expired","unavailable","not_found"]),exists:Be(),active:Be(),revoked:Be(),expired:Be(),effective_expiry:$e().int().nullable().optional(),renewal_history:qe(Zc).optional()}).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:o.custom,message:"delegation status flags do not match status"})}),Fe({revoked:He(!0),cid:Ke().min(1)}).strict()),zc=Fe({resource:Ke().min(1),actions:qe(Ke()),caveats:qe(je(Ke(),Ve()))}).strict(),Gc=Ke().datetime({offset:!0}).transform(e=>new Date(e)),Jc=Fe({cid:Ke().min(1),direction:Ze(["granted","received"]),delegatorDid:Ke().min(1),delegateDid:Ke().min(1),resources:qe(zc),parents:qe(Ke()),issuedAt:Gc.nullable(),notBefore:Gc.nullable(),expiresAt:Gc.nullable(),status:Ze(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:Gc.nullable().optional(),revokedBy:Ke().optional(),revokedAncestorCid:Ke().optional()}).strict(),Yc=Fe({schemaVersion:He(2),items:qe(Jc),nextCursor:Ke().optional()}).strict(),Qc=(Fe({direction:Ze(["granted","received","all","issued"]).optional(),status:Ze(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:Ke().trim().min(1).optional(),limit:$e().int().min(1).max(100).optional(),cursor:Ke().min(1).optional()}).strict(),Fe({resource:Ke(),action:Ke(),keys:qe(Vc),delegation:Hc,expiresAt:We().optional()}),Fe({cid:Ke(),spaceId:Ke(),delegator:Ke(),delegatee:Ke(),keyId:Ke().optional(),path:Ke(),actions:qe(Ke()),expiry:We().optional(),notBefore:We().optional(),isRevoked:Be(),createdAt:We(),parentCid:Ke().optional()}),Fe({delegateDID:Ke(),path:Ke(),actions:qe(Ke()),expiry:We().optional(),disableSubDelegation:Be().optional(),statement:Ke().optional()}),qe(Hc),Fe({root:Hc,chain:qe(Hc),leaf:Hc}),Ze(["granted","received","all"])),Xc=(Fe({direction:Qc.optional(),path:Ke().optional(),actions:qe(Ke()).optional(),includeRevoked:Be().optional(),delegator:Ke().optional(),delegatee:Ke().optional(),validAt:We().optional(),limit:$e().optional(),cursor:Ke().optional()}),Ze(["owned","delegated"])),eu=(Fe({id:Ke(),name:Ke().optional(),owner:Ke(),type:Xc,permissions:qe(Ke()).optional(),expiresAt:We().optional()}),Ze(["base64","compact","ipfs"]));Fe({token:Ke(),url:Ke(),delegation:Hc,schema:eu,expiresAt:We().optional(),description:Ke().optional()}),function(e){Fe({data:e,delegation:Hc,spaceId:Ke(),path:Ke()})}(Ve()),Fe({persist:Be().optional(),validateChain:Be().optional(),keyName:Ke().optional(),createSessionKey:Be().optional(),priority:$e().optional()}),Fe({includePlacement:Be().optional(),path:Ke().optional(),actions:qe(Ke()).optional(),resources:qe(Fe({path:Ke(),actions:qe(Ke()).optional()})).optional(),expiry:We().optional(),schema:eu.optional(),description:Ke().optional(),baseUrl:Ke().optional(),allowSubDelegation:Be().optional()}),Fe({hosts:qe(Ke()),accountSpaceId:Ke().min(1).optional(),session:Ve().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),invoke:Ve().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),invokeAny:Ve().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:Ve().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),Fe({createSessionKey:Ve().refine(e=>"function"==typeof e,{message:"Expected a function"}),getJWK:Ve().refine(e=>"function"==typeof e,{message:"Expected a function"}),getDID:Ve().refine(e=>"function"==typeof e,{message:"Expected a function"})}),Fe({siwe:Ke(),signature:Ke(),version:$e(),cid:Ke().optional()});var tu=Fe({service:Ke(),space:Ke(),path:Ke(),actions:qe(Ke()),caveats:qe(je(Ke(),Ve())).optional()}),ru=(Fe({session:Ve().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:Ke(),spaceId:Ke(),abilities:je(Ke(),je(Ke(),qe(Ke()))),expirationSecs:$e(),notBeforeSecs:$e().optional(),disableSubDelegation:Be().optional()}),Fe({delegation:Ke(),cid:Ke(),delegateDID:Ke(),expiry:We(),resources:qe(tu)}),"tinycloud.delegation/revoke"),nu="tinycloud.delegation/list";function su(e,t,r,n){return{code:e,message:t,service:"delegation",cause:r,meta:n}}var iu="delegation-issued-query-v1";async function au(e){return(await e.text()).replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,200)}async function ou(e,t,r,n){const s=n??await au(e),i={...r,status:e.status};return 401===e.status||403===e.status?su("PERMISSION_DENIED",""===s?"The node refused the request":s,void 0,i):400===e.status&&s.includes("invalid delegation query cursor")?su("INVALID_CURSOR","The node rejected the page cursor; list again from the start",void 0,i):503===e.status?su("CHAIN_TOO_DEEP","This delegation chain is too long for the node to check right now; try again later",void 0,{...i,retryable:!0}):su(Fc,`${t}: ${e.status} - ${s}`,void 0,i)}var cu=class extends Error{};function uu(){return{ok:!1,error:su("UNSUPPORTED_OPERATION","This node doesn't support listing issued delegations yet",void 0,{feature:iu})}}async function du(e,t){const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:su(qc,"Listing issued delegations needs a session key signer")};const n=r.did().split("#",1)[0];if(!/^did:key:z[1-9A-HJ-NP-Za-km-z]+$/.test(n))return{ok:!1,error:su(Mc,"Issued queries require the session key's did:key")};try{const s=async(e,s,i)=>e(`${s}/delegation/query`,{method:"POST",headers:{Authorization:await r.sign({[`tinycloud:${n.slice(4)}:agent/delegation`]:{[nu]:[{}]}},i),"content-type":"application/json"},body:JSON.stringify(t),redirect:"error"});let i;if(e.resourceTransport)i=await e.resourceTransport([{resource:e.spaceId??"",access:"read"}],e=>{const t=e.nodeInfo.features;if(!Array.isArray(t)||!t.includes(iu))throw new cu;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:su(Fc,`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(iu),{ok:!0,data:e.state.issuedQuerySupported}}(e);if(!t.ok)return t;if(!t.data)return uu();i=await s(e.fetchFn,e.host)}if(!i.ok)return{ok:!1,error:await ou(i,"Failed to query issued delegations",{})};const a=Yc.safeParse(await i.json());return a.success?{ok:!0,data:a.data}:{ok:!1,error:su(jc,"Node returned an invalid delegation query response")}}catch(e){return Zi(e)?{ok:!1,error:{...fa("delegation",e),service:"delegation"}}:e instanceof cu?uu():{ok:!1,error:su(Fc,`Network error during delegation query: ${String(e)}`,e instanceof Error?e:void 0)}}}async function lu(e,t){const{pageSize:r=100,maxItems:n,untilCid:s,...i}=t;if(void 0!==n&&(!Number.isInteger(n)||n<1))return{ok:!1,error:su(Mc,"maxItems must be a positive integer")};const a=[],o=new Set;let c;do{const t=Math.min(r,void 0===n?r:n-a.length),s=await e({...i,direction:"issued",limit:t,...void 0===c?{}:{cursor:c}});if(!s.ok)return s;if(a.push(...s.data.items),c=s.data.nextCursor,void 0!==c){if(o.has(c))return{ok:!1,error:su(jc,"The node returned the same page cursor twice while listing issued delegations")};o.add(c)}}while(void 0!==c&&(void 0===n||a.length<n)&&(void 0===s||!a.some(e=>e.cid===s)));return{ok:!0,data:void 0===n?a:a.slice(0,n)}}async function hu(e,t){if(!t)return{ok:!1,error:su(Mc,"cid is required")};const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:su(qc,"Revoking an issued delegation needs a session key signer")};try{const n=async(e,n,s)=>e(`${n}/revoke`,{method:"POST",headers:{Authorization:await r.sign({[`urn:cid:${t}`]:{[ru]:[{}]}},s)},redirect:"error"}),s=e.resourceTransport?await e.resourceTransport([{resource:e.spaceId??"",access:"read"}],e=>n(e.fetch,e.url,e.nodeDid),{nodeLocal:!0}):await n(e.fetchFn,e.host);if(!s.ok){if(404===s.status){const e=await au(s);return{ok:!1,error:"space not found"===e.toLowerCase()?su("NOT_FOUND",`Delegation not found: ${t}`,void 0,{cid:t,status:404}):await ou(s,"Failed to revoke delegation",{cid:t},e)}}return{ok:!1,error:await ou(s,"Failed to revoke delegation",{cid:t})}}const i=Wc.safeParse(await s.json());return i.success&&i.data.cid===t?{ok:!0,data:i.data}:{ok:!1,error:su("REVOCATION_FAILED","Node returned an invalid delegation revocation receipt",void 0,{cid:t})}}catch(e){return Zi(e)?{ok:!1,error:{...fa("delegation",e),service:"delegation"}}:{ok:!1,error:su(Fc,`Network error during delegation revocation: ${String(e)}`,e instanceof Error?e:void 0)}}}export{lu as queryAllIssued,du as queryIssued,hu as revokeIssued};