@tinycloud/web-sdk 3.14.0-beta.16 → 3.14.0-beta.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/delegations-issued.cjs +1 -1
- package/dist/delegations-issued.mjs +1 -1
- package/dist/delegations-renewal.cjs +1 -1
- package/dist/delegations-renewal.mjs +1 -1
- package/dist/encryption-keys.cjs +1 -1
- package/dist/encryption-keys.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/modules/runtimeGrantPersistence.d.ts +2 -4
- package/package.json +4 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! For license information please see delegations-issued.cjs.LICENSE.txt */
|
|
2
|
-
(()=>{"use strict";var e={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"}}}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n,s,i={};r.r(i),r.d(i,{queryAllIssued:()=>au,queryIssued:()=>iu,revokeIssued:()=>ou}),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}(n||(n={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const a=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),o=e=>{switch(typeof e){case"undefined":return a.undefined;case"string":return a.string;case"number":return Number.isNaN(e)?a.nan:a.number;case"boolean":return a.boolean;case"function":return a.function;case"bigint":return a.bigint;case"symbol":return a.symbol;case"object":return Array.isArray(e)?a.array:null===e?a.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?a.promise:"undefined"!=typeof Map&&e instanceof Map?a.map:"undefined"!=typeof Set&&e instanceof Set?a.set:"undefined"!=typeof Date&&e instanceof Date?a.date:a.object;default:return a.unknown}},c=n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class u extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},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 u))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,n.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()}}u.create=e=>new u(e);const d=(e,t)=>{let r;switch(e.code){case c.invalid_type:r=e.received===a.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case c.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,n.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case c.invalid_union:r="Invalid input";break;case c.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case c.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case c.invalid_arguments:r="Invalid function arguments";break;case c.invalid_return_type:r="Invalid function return type";break;case c.invalid_date:r="Invalid date";break;case c.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case c.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case c.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case c.custom:r="Invalid input";break;case c.invalid_intersection_types:r="Intersection results could not be merged";break;case c.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case c.not_finite:r="Number must be finite";break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};let l=d;var h;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(h||(h={}));function f(e,t){const r=l,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===d?void 0:d].filter(e=>!!e)});e.common.issues.push(n)}class p{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 y;"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 p.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 y;if("aborted"===s.status)return y;"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 y=Object.freeze({status:"aborted"}),g=e=>({status:"dirty",value:e}),m=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,_=e=>"dirty"===e.status,k=e=>"valid"===e.status,E=e=>"undefined"!=typeof Promise&&e instanceof Promise;class 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 b=(e,t)=>{if(k(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new u(e.common.issues);return this._error=t,this._error}}};function T(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 O{get description(){return this._def.description}_getType(e){return o(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new p,ctx:{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(E(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},n=this._parseSync({data:e,path:r.path,parent:r});return b(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return k(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>k(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(E(n)?n:Promise.resolve(n));return b(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:c.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:Ke.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Re.create(this,this._def)}nullable(){return Ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ce.create(this)}promise(){return Oe.create(this,this._def)}or(e){return le.create([this,e],this._def)}and(e){return ye.create(this,e,this._def)}transform(e){return new Ne({...T(this._def),schema:this,typeName:Ke.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...T(this._def),innerType:this,defaultValue:t,typeName:Ke.ZodDefault})}brand(){return new De({typeName:Ke.ZodBranded,type:this,...T(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new xe({...T(this._def),innerType:this,catchValue:t,typeName:Ke.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ue.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,R=/^[0-9a-z]+$/,I=/^[0-9A-HJKMNP-TV-Z]{26}$/i,A=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,x=/^[a-z0-9_-]{21}$/i,S=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,D=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,U=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let P;const 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])$/,C=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,K=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,V=/^(([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}(=)?))?$/,q="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",F=new RegExp(`^${q}$`);function M(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 j(e){return new RegExp(`^${M(e)}$`)}function H(e){let t=`${q}T${M(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Z(e,t){return!("v4"!==t&&t||!L.test(e))||!("v6"!==t&&t||!K.test(e))}function W(e,t){if(!S.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 z(e,t){return!("v4"!==t&&t||!C.test(e))||!("v6"!==t&&t||!V.test(e))}class G extends O{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==a.string){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.string,received:t.parsedType}),y}const t=new p;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:c.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:c.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const n=e.data.length>s.value,i=e.data.length<s.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?f(r,{code:c.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&f(r,{code:c.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)U.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"email",code:c.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)P||(P=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),P.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"emoji",code:c.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)A.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"uuid",code:c.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)x.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"nanoid",code:c.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)N.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid",code:c.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)R.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid2",code:c.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)I.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ulid",code:c.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),f(r,{validation:"url",code:c.invalid_string,message:s.message}),t.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"regex",code:c.invalid_string,message:s.message}),t.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):"datetime"===s.kind?H(s).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:"datetime",message:s.message}),t.dirty()):"date"===s.kind?F.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:"date",message:s.message}),t.dirty()):"time"===s.kind?j(s).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:"time",message:s.message}),t.dirty()):"duration"===s.kind?D.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"duration",code:c.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?Z(e.data,s.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ip",code:c.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?W(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"jwt",code:c.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?z(e.data,s.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cidr",code:c.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?$.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"base64",code:c.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?B.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"base64url",code:c.invalid_string,message:s.message}),t.dirty()):n.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:c.invalid_string,...h.errToObj(r)})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new G({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function J(e,t){const r=(e.toString().split(".")[1]||"").length,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}G.create=e=>new G({checks:[],typeName:Ke.ZodString,coerce:e?.coerce??!1,...T(e)});class Y extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==a.number){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.number,received:t.parsedType}),y}let t;const r=new p;for(const s of this._def.checks)"int"===s.kind?n.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:c.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"multipleOf"===s.kind?0!==J(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:c.not_finite,message:s.message}),r.dirty()):n.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,r,n){return new Y({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:h.toString(n)}]})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&n.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Y.create=e=>new Y({checks:[],typeName:Ke.ZodNumber,coerce:e?.coerce||!1,...T(e)});class Q extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==a.bigint)return this._getInvalidInput(e);let t;const r=new p;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):n.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.bigint,received:t.parsedType}),y}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,r,n){return new Q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:h.toString(n)}]})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Q.create=e=>new Q({checks:[],typeName:Ke.ZodBigInt,coerce:e?.coerce??!1,...T(e)});class X extends O{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==a.boolean){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.boolean,received:t.parsedType}),y}return m(e.data)}}X.create=e=>new X({typeName:Ke.ZodBoolean,coerce:e?.coerce||!1,...T(e)});class ee extends O{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==a.date){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.date,received:t.parsedType}),y}if(Number.isNaN(e.data.getTime()))return f(this._getOrReturnCtx(e),{code:c.invalid_date}),y;const t=new p;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:c.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:c.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):n.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ee.create=e=>new ee({checks:[],coerce:e?.coerce||!1,typeName:Ke.ZodDate,...T(e)});class te extends O{_parse(e){if(this._getType(e)!==a.symbol){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.symbol,received:t.parsedType}),y}return m(e.data)}}te.create=e=>new te({typeName:Ke.ZodSymbol,...T(e)});class re extends O{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.undefined,received:t.parsedType}),y}return m(e.data)}}re.create=e=>new re({typeName:Ke.ZodUndefined,...T(e)});class ne extends O{_parse(e){if(this._getType(e)!==a.null){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.null,received:t.parsedType}),y}return m(e.data)}}ne.create=e=>new ne({typeName:Ke.ZodNull,...T(e)});class se extends O{constructor(){super(...arguments),this._any=!0}_parse(e){return m(e.data)}}se.create=e=>new se({typeName:Ke.ZodAny,...T(e)});class ie extends O{constructor(){super(...arguments),this._unknown=!0}_parse(e){return m(e.data)}}ie.create=e=>new ie({typeName:Ke.ZodUnknown,...T(e)});class ae extends O{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.never,received:t.parsedType}),y}}ae.create=e=>new ae({typeName:Ke.ZodNever,...T(e)});class oe extends O{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.void,received:t.parsedType}),y}return m(e.data)}}oe.create=e=>new oe({typeName:Ke.ZodVoid,...T(e)});class ce extends O{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==a.array)return f(t,{code:c.invalid_type,expected:a.array,received:t.parsedType}),y;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(f(t,{code:e?c.too_big:c.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&&(f(t,{code:c.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&&(f(t,{code:c.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=>p.mergeArray(r,e));const s=[...t.data].map((e,r)=>n.type._parseSync(new w(t,e,t.path,r)));return p.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new ce({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new ce({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new ce({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}}function ue(e){if(e instanceof de){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Re.create(ue(n))}return new de({...e._def,shape:()=>t})}return e instanceof ce?new ce({...e._def,type:ue(e.element)}):e instanceof Re?Re.create(ue(e.unwrap())):e instanceof Ie?Ie.create(ue(e.unwrap())):e instanceof ge?ge.create(e.items.map(e=>ue(e))):e}ce.create=(e,t)=>new ce({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ke.ZodArray,...T(t)});class de extends O{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=n.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==a.object){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.object,received:t.parsedType}),y}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof ae&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||i.push(e);const o=[];for(const e of s){const t=n[e],s=r.data[e];o.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 ae){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(f(r,{code:c.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const n=r.data[t];o.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 o){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>p.mergeObjectSync(t,e)):p.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new de({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:h.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ke.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const t={};for(const r of n.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const r of n.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new de({...this._def,shape:()=>t})}deepPartial(){return ue(this)}partial(e){const t={};for(const r of n.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const r of n.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Re;)e=e._def.innerType;t[r]=e}return new de({...this._def,shape:()=>t})}keyof(){return we(n.objectKeys(this.shape))}}de.create=(e,t)=>new de({shape:()=>e,unknownKeys:"strip",catchall:ae.create(),typeName:Ke.ZodObject,...T(t)}),de.strictCreate=(e,t)=>new de({shape:()=>e,unknownKeys:"strict",catchall:ae.create(),typeName:Ke.ZodObject,...T(t)}),de.lazycreate=(e,t)=>new de({shape:e,unknownKeys:"strip",catchall:ae.create(),typeName:Ke.ZodObject,...T(t)});class le extends O{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new u(e.ctx.common.issues));return f(t,{code:c.invalid_union,unionErrors:r}),y});{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 u(e));return f(t,{code:c.invalid_union,unionErrors:s}),y}}get options(){return this._def.options}}le.create=(e,t)=>new le({options:e,typeName:Ke.ZodUnion,...T(t)});const he=e=>e instanceof ke?he(e.schema):e instanceof Ne?he(e.innerType()):e instanceof Ee?[e.value]:e instanceof be?e.options:e instanceof Te?n.objectValues(e.enum):e instanceof Ae?he(e._def.innerType):e instanceof re?[void 0]:e instanceof ne?[null]:e instanceof Re?[void 0,...he(e.unwrap())]:e instanceof Ie?[null,...he(e.unwrap())]:e instanceof De||e instanceof Pe?he(e.unwrap()):e instanceof xe?he(e._def.innerType):[];class fe extends O{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.object)return f(t,{code:c.invalid_type,expected:a.object,received:t.parsedType}),y;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}):(f(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}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=he(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const 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 fe({typeName:Ke.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...T(r)})}}function pe(e,t){const r=o(e),s=o(t);if(e===t)return{valid:!0,data:e};if(r===a.object&&s===a.object){const r=n.objectKeys(t),s=n.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of s){const n=pe(e[r],t[r]);if(!n.valid)return{valid:!1};i[r]=n.data}return{valid:!0,data:i}}if(r===a.array&&s===a.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const s=pe(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===a.date&&s===a.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class ye extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(v(e)||v(n))return y;const s=pe(e.value,n.value);return s.valid?((_(e)||_(n))&&t.dirty(),{status:t.value,value:s.data}):(f(r,{code:c.invalid_intersection_types}),y)};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}))}}ye.create=(e,t,r)=>new ye({left:e,right:t,typeName:Ke.ZodIntersection,...T(r)});class ge extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.array)return f(r,{code:c.invalid_type,expected:a.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return f(r,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:c.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=>p.mergeArray(t,e)):p.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ge({...this._def,rest:e})}}ge.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ge({items:e,typeName:Ke.ZodTuple,rest:null,...T(t)})};class me extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.object)return f(r,{code:c.invalid_type,expected:a.object,received:r.parsedType}),y;const n=[],s=this._def.keyType,i=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new w(r,e,r.path,e)),value:i._parse(new w(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?p.mergeObjectAsync(t,n):p.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new me(t instanceof O?{keyType:e,valueType:t,typeName:Ke.ZodRecord,...T(r)}:{keyType:G.create(),valueType:e,typeName:Ke.ZodRecord,...T(t)})}}class ve extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.map)return f(r,{code:c.invalid_type,expected:a.map,received:r.parsedType}),y;const n=this._def.keyType,s=this._def.valueType,i=[...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 i){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return y;"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 i){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return y;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}ve.create=(e,t,r)=>new ve({valueType:t,keyType:e,typeName:Ke.ZodMap,...T(r)});class _e extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.set)return f(r,{code:c.invalid_type,expected:a.set,received:r.parsedType}),y;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(f(r,{code:c.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&&(f(r,{code:c.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return y;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>s._parse(new w(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new _e({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new _e({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}_e.create=(e,t)=>new _e({valueType:e,minSize:null,maxSize:null,typeName:Ke.ZodSet,...T(t)});class ke extends O{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ke.create=(e,t)=>new ke({getter:e,typeName:Ke.ZodLazy,...T(t)});class Ee extends O{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function we(e,t){return new be({values:e,typeName:Ke.ZodEnum,...T(t)})}Ee.create=(e,t)=>new Ee({value:e,typeName:Ke.ZodLiteral,...T(t)});class be extends O{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:n.joinValues(r),received:t.parsedType,code:c.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:c.invalid_enum_value,options:r}),y}return m(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return be.create(e,{...this._def,...t})}exclude(e,t=this._def){return be.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}be.create=we;class Te extends O{_parse(e){const t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==a.string&&r.parsedType!==a.number){const e=n.objectValues(t);return f(r,{expected:n.joinValues(e),received:r.parsedType,code:c.invalid_type}),y}if(this._cache||(this._cache=new Set(n.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=n.objectValues(t);return f(r,{received:r.data,code:c.invalid_enum_value,options:e}),y}return m(e.data)}get enum(){return this._def.values}}Te.create=(e,t)=>new Te({values:e,typeName:Ke.ZodNativeEnum,...T(t)});class Oe extends O{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.promise&&!1===t.common.async)return f(t,{code:c.invalid_type,expected:a.promise,received:t.parsedType}),y;const r=t.parsedType===a.promise?t.data:Promise.resolve(t.data);return m(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Oe.create=(e,t)=>new Oe({type:e,typeName:Ke.ZodPromise,...T(t)});class Ne extends O{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ke.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:e=>{f(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===s.type){const e=s.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return y;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?y:"dirty"===n.status||"dirty"===t.value?g(n.value):n});{if("aborted"===t.value)return y;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?y:"dirty"===n.status||"dirty"===t.value?g(n.value):n}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?y:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?y:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!k(e))return y;const n=s.transform(e.value,i);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>k(e)?Promise.resolve(s.transform(e.value,i)).then(e=>({status:t.value,value:e})):y)}n.assertNever(s)}}Ne.create=(e,t,r)=>new Ne({schema:e,typeName:Ke.ZodEffects,effect:t,...T(r)}),Ne.createWithPreprocess=(e,t,r)=>new Ne({schema:t,effect:{type:"preprocess",transform:e},typeName:Ke.ZodEffects,...T(r)});class Re extends O{_parse(e){return this._getType(e)===a.undefined?m(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:Ke.ZodOptional,...T(t)});class Ie extends O{_parse(e){return this._getType(e)===a.null?m(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Ke.ZodNullable,...T(t)});class Ae extends O{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===a.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Ke.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...T(t)});class xe extends O{_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 E(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new u(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new u(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}xe.create=(e,t)=>new xe({innerType:e,typeName:Ke.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...T(t)});class Se extends O{_parse(e){if(this._getType(e)!==a.nan){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.nan,received:t.parsedType}),y}return{status:"valid",value:e.data}}}Se.create=e=>new Se({typeName:Ke.ZodNaN,...T(e)}),Symbol("zod_brand");class De extends O{_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 Ue extends O{_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?y:"dirty"===e.status?(t.dirty(),g(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?y:"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 Ue({in:e,out:t,typeName:Ke.ZodPipeline})}}class Pe extends O{_parse(e){const t=this._def.innerType._parse(e),r=e=>(k(e)&&(e.value=Object.freeze(e.value)),e);return E(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Le(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Ce(e,t={},r){return e?se.create().superRefine((n,s)=>{const i=e(n);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Le(t,n),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Le(t,n),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}}):se.create()}var Ke;Pe.create=(e,t)=>new Pe({innerType:e,typeName:Ke.ZodReadonly,...T(t)}),de.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Ke||(Ke={}));const Ve=G.create,$e=Y.create,Be=(Se.create,Q.create,X.create),qe=(ee.create,te.create,re.create,ne.create,se.create,ie.create),Fe=(ae.create,oe.create,ce.create),Me=de.create,je=(de.strictCreate,le.create,fe.create),He=(ye.create,ge.create,me.create),Ze=(ve.create,_e.create,ke.create,Ee.create),We=be.create,ze=(Te.create,Oe.create,Ne.create,Re.create,Ie.create,Ne.createWithPreprocess,Ue.create,e=>ee.create({...e,coerce:!0}));var Ge=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function Je(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function Ye(e){return e.slice(10,e.indexOf("/"))}function Qe(e){return e.slice(e.indexOf("/")+1)}function Xe(e){const t={};for(const r of Ge)Ye(r.urn)===e&&(t[Je(Qe(r.urn))]=r.urn);return t}var et=Xe("kv"),tt={...Xe("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},rt={...Xe("duckdb"),DESCRIBE:"tinycloud.duckdb/describe",EXECUTE:"tinycloud.duckdb/execute"},nt=Xe("capabilities"),st=(Xe("hooks"),Xe("encryption")),it=Xe("space"),at=Ge;["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 ot="applications",ct="account",ut="applications/",dt="secrets",lt="default",ht="public",ft="agents",pt="tinycloud.encryption",yt=st.NETWORK_CREATE,gt=[lt,ot,ct,dt,ht,ft],mt={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:lt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:lt,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:lt,path:"",actions:["read","write"]}]},vt={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:ot,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ot,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:ot,path:"",actions:["read","write"]}]},_t={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ct,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ct,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ct,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ct,path:"account",actions:["read","write","schema"]}]},kt={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:dt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:dt,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:dt,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:dt,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:dt,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:dt,path:"",actions:["read"],skipPrefix:!0}]},Et={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:ht,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ht,path:"",actions:["get","list","metadata"]}]},wt={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:ft,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ft,path:"",actions:["get","put","del","list","metadata"]}]},bt={[lt]:mt,[ot]:vt,[ct]:_t,[dt]:kt,[ht]:Et,[ft]:wt};function Tt(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Ot(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?et.GET:"write"===r||"put"===r?et.PUT:"delete"===r||"del"===r?et.DEL:"list"===r?et.LIST:"metadata"===r?et.METADATA:void 0;if(void 0===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===pt;return[{service:e.service,space:e.service===pt?"encryption":e.space??r,path:Ot(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 Rt(e){const t=new Set(e.filter(e=>e.service!==pt).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:[nt.READ]}))])}function It(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(Tt),s=n.flatMap(e=>{const t=e.prefix??e.app_id,r=e.space??ot;return(e.permissions??[]).flatMap(e=>Nt(e,t,r))});r&&s.push(...At.map(e=>({...e,actions:[...e.actions]})));const i=new Map;for(const e of n){const t=i.get(e.app_id)??[];t.push(Tt(e)),i.set(e.app_id,t)}return{manifests:n,resources:Rt(s),delegationTargets:[],registryRecords:r?[...i.entries()].map(([e,t])=>({key:`${ut}${e}`,app_id:e,manifests:t})):[],expiryMs:6048e5,includePublicSpace:n.some(e=>e.includePublicSpace??!0)}}([bt[e]],{includeAccountRegistryPermissions:!1})}gt.map(e=>({name:e,manifest:bt[e],persistedAsApplication:e===dt}));var At=Object.freeze([{service:"tinycloud.kv",space:ct,path:ut,actions:[et.GET,et.PUT,et.LIST]},{service:"tinycloud.kv",space:ct,path:"spaces/",actions:[et.GET,et.PUT,et.LIST]},{service:"tinycloud.kv",space:ct,path:"system/bootstrap/complete",actions:[et.GET,et.PUT]},{service:"tinycloud.delegation",space:ct,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ct,path:"account",actions:[tt.READ,tt.WRITE,tt.SCHEMA]},{service:"tinycloud.capabilities",space:ct,path:"",actions:[nt.READ]}]),xt=It(lt),St={...xt,resources:[...xt.resources,...At.map(e=>({...e,actions:[...e.actions]}))]},Dt=Object.freeze(Object.fromEntries(gt.map(e=>[e,e===lt?St:It(e)]))),Ut=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[yt]}]);function Pt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Lt(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 Ct(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 Kt(e,t){Lt(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Vt(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(gt.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:Dt[e].resources,...e===ct?{rawAbilities:Ut}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[it.HOST]}]));const qt=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Ft(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=Zt(e)}return e}const Mt=(e,t)=>{function r(r,...n){if(Lt(r),!qt)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?Lt(t):Lt(t,e.nonceLength)}const s=e.tagLength;s&&void 0!==n[1]&&Lt(n[1]);const i=t(r,...n),a=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Lt(t)}};let o=!1;return{encrypt(e,t){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Lt(e),a(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(Lt(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 jt(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 Ht(e){return e.byteOffset%4==0}function Zt(e){return Uint8Array.from(e)}const Wt=16,zt=new Uint8Array(16),Gt=Vt(zt),Jt=(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)}),Yt=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Qt{constructor(e,t){this.blockLen=Wt,this.outputLen=Wt,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,Lt(e=Ft(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:Yt(n),s1:Yt(s),s2:Yt(i),s3:Yt(a)}),({s0:n,s1:s,s2:i,s3:a}=Jt(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){Ct(this),Lt(e=Ft(e));const t=Vt(e),r=Math.floor(e.length/Wt),n=e.length%Wt;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&&(zt.set(e.subarray(r*Wt)),this._updateBlock(Gt[0],Gt[1],Gt[2],Gt[3]),$t(Gt)),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){Ct(this),Kt(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:s}=this,i=Vt(e);return i[0]=t,i[1]=r,i[2]=n,i[3]=s,e}digest(){const e=new Uint8Array(Wt);return this.digestInto(e),this.destroy(),e}}class Xt extends Qt{constructor(e,t){Lt(e=Ft(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}(Zt(e));super(r,t),$t(r)}update(e){e=Ft(e),Ct(this);const t=Vt(e),r=e.length%Wt,n=Math.floor(e.length/Wt);for(let e=0;e<n;e++)this._updateBlock(Yt(t[4*e+3]),Yt(t[4*e+2]),Yt(t[4*e+1]),Yt(t[4*e+0]));return r&&(zt.set(e.subarray(n*Wt)),this._updateBlock(Yt(Gt[3]),Yt(Gt[2]),Yt(Gt[1]),Yt(Gt[0])),$t(Gt)),this}digestInto(e){Ct(this),Kt(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:s}=this,i=Vt(e);return i[0]=t,i[1]=r,i[2]=n,i[3]=s,e.reverse()}}function er(e){const t=(t,r)=>e(r,t.length).update(Ft(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 tr=er((e,t)=>new Qt(e,t)),rr=(er((e,t)=>new Xt(e,t)),16),nr=new Uint8Array(rr);function sr(e){return e<<1^283&-(e>>7)}function ir(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=sr(e);return r}const ar=e=>e<<24|e>>>8,or=e=>e<<8|e>>>24;function cr(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(or),s=n.map(or),i=s.map(or),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 ur=cr((()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=sr(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=>ir(e,3)<<24|e<<16|e<<8|ir(e,2)),dr=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=sr(r))e[t]=r;return e})();function lr(e,t,r,n,s,i){return e[r<<8&65280|n>>>8&255]^t[s>>>8&65280|i>>>24&255]}function hr(e,t,r,n,s){return e[255&t|65280&r]|e[n>>>16&255|s>>>16&65280]<<16}function fr(e,t,r,n,s){const{sbox2:i,T01:a,T23:o}=ur;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++]^lr(a,o,t,r,n,s),u=e[c++]^lr(a,o,r,n,s,t),d=e[c++]^lr(a,o,n,s,t,r),l=e[c++]^lr(a,o,s,t,r,n);t=i,r=u,n=d,s=l}return{s0:e[c++]^hr(i,t,r,n,s),s1:e[c++]^hr(i,r,n,s,t),s2:e[c++]^hr(i,n,s,t,r),s3:e[c++]^hr(i,s,t,r,n)}}function pr(e,t,r,n,s){Lt(r,rr),Lt(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&&!Ht(t))throw new Error("invalid output, must be aligned");return t}(n.length,s);const i=r,a=Vt(i),o=Bt(i),c=Vt(n),u=Vt(s),d=t?0:12,l=n.length;let h=o.getUint32(d,t),{s0:f,s1:p,s2:y,s3:g}=fr(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}=fr(e,a[0],a[1],a[2],a[3]));const m=rr*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];$t(e)}var v;return s}function yr(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 jt(s,0,BigInt(t),r),jt(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 gr=Mt({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=yr(tr,!1,e,n,r);for(let e=0;e<t.length;e++)s[e]^=t[e];return s}function s(){const r=function(e){Lt(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}=ur,n=[];Ht(e)||n.push(e=Zt(e));const s=Vt(e),i=s.length,a=e=>hr(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(ar(t))^dr[e/i-1]:i>6&&e%i===4&&(t=a(t)),o[e]=o[e-i]^t}return $t(...n),o}(e),n=nr.slice(),s=nr.slice();if(pr(r,!1,s,s,n),12===t.length)s.set(t);else{const e=nr.slice();jt(Bt(e),8,BigInt(8*t.length),!1);const r=tr.create(n).update(t).update(e);r.digestInto(s),r.destroy()}return{xk:r,authKey:n,counter:s,tagMask:pr(r,!1,s,nr)}}return{encrypt(e){const{xk:t,authKey:r,counter:i,tagMask:a}=s(),o=new Uint8Array(e.length+16),c=[t,r,i,a];Ht(e)||c.push(e=Zt(e)),pr(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];Ht(e)||o.push(e=Zt(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=pr(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,vr={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 _r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function kr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Er(e,...t){if(!_r(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");kr(e.outputLen),kr(e.blockLen)}function br(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 Tr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Or(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Nr(e,t){return e<<32-t|e>>>t}const Rr=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Ir=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ar(e){if(Er(e),Rr)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Ir[e[r]];return t}function xr(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Sr(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Rr)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=xr(e.charCodeAt(s)),i=xr(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 Dr(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Ur(e){return"string"==typeof e&&(e=Dr(e)),Er(e),e}function Pr(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];Er(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 Lr{}function Cr(e){const t=t=>e().update(Ur(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Kr(e=32){if(vr&&"function"==typeof vr.getRandomValues)return vr.getRandomValues(new Uint8Array(e));if(vr&&"function"==typeof vr.randomBytes)return Uint8Array.from(vr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Vr(e,t,r){return e&t^~e&r}function $r(e,t,r){return e&t^e&r^t&r}class Br extends Lr{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=Or(this.buffer)}update(e){br(this),Er(e=Ur(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=Or(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){br(this),function(e,t){Er(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,Tr(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=Or(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 qr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Fr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Mr=BigInt(2**32-1),jr=BigInt(32);function Hr(e,t=!1){return t?{h:Number(e&Mr),l:Number(e>>jr&Mr)}:{h:0|Number(e>>jr&Mr),l:0|Number(e&Mr)}}const Zr=(e,t,r)=>e>>>r,Wr=(e,t,r)=>e<<32-r|t>>>r,zr=(e,t,r)=>e>>>r|t<<32-r,Gr=(e,t,r)=>e<<32-r|t>>>r,Jr=(e,t,r)=>e<<64-r|t>>>r-32,Yr=(e,t,r)=>e>>>r-32|t<<64-r;function Qr(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}}const Xr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),en=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,tn=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),rn=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,nn=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),sn=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,an=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]),on=new Uint32Array(64);class cn extends Br{constructor(e=32){super(64,e,8,!1),this.A=0|qr[0],this.B=0|qr[1],this.C=0|qr[2],this.D=0|qr[3],this.E=0|qr[4],this.F=0|qr[5],this.G=0|qr[6],this.H=0|qr[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)on[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=on[e-15],r=on[e-2],n=Nr(t,7)^Nr(t,18)^t>>>3,s=Nr(r,17)^Nr(r,19)^r>>>10;on[e]=s+on[e-7]+n+on[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))+Vr(a,o,c)+an[e]+on[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(){Tr(on)}destroy(){this.set(0,0,0,0,0,0,0,0),Tr(this.buffer)}}const un=(()=>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}=Hr(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))))(),dn=(()=>un[0])(),ln=(()=>un[1])(),hn=new Uint32Array(80),fn=new Uint32Array(80);class pn extends Br{constructor(e=64){super(128,e,16,!1),this.Ah=0|Fr[0],this.Al=0|Fr[1],this.Bh=0|Fr[2],this.Bl=0|Fr[3],this.Ch=0|Fr[4],this.Cl=0|Fr[5],this.Dh=0|Fr[6],this.Dl=0|Fr[7],this.Eh=0|Fr[8],this.El=0|Fr[9],this.Fh=0|Fr[10],this.Fl=0|Fr[11],this.Gh=0|Fr[12],this.Gl=0|Fr[13],this.Hh=0|Fr[14],this.Hl=0|Fr[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)hn[r]=e.getUint32(t),fn[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|hn[e-15],r=0|fn[e-15],n=zr(t,r,1)^zr(t,r,8)^Zr(t,0,7),s=Gr(t,r,1)^Gr(t,r,8)^Wr(t,r,7),i=0|hn[e-2],a=0|fn[e-2],o=zr(i,a,19)^Jr(i,a,61)^Zr(i,0,6),c=Gr(i,a,19)^Yr(i,a,61)^Wr(i,a,6),u=tn(s,c,fn[e-7],fn[e-16]),d=rn(u,n,o,hn[e-7],hn[e-16]);hn[e]=0|d,fn[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=zr(d,l,14)^zr(d,l,18)^Jr(d,l,41),v=Gr(d,l,14)^Gr(d,l,18)^Yr(d,l,41),_=d&h^~d&p,k=nn(m,v,l&f^~l&y,ln[e],fn[e]),E=sn(k,g,t,_,dn[e],hn[e]),w=0|k,b=zr(r,n,28)^Jr(r,n,34)^Jr(r,n,39),T=Gr(r,n,28)^Yr(r,n,34)^Yr(r,n,39),O=r&s^r&a^s&a,N=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}=Qr(0|c,0|u,0|E,0|w)),c=0|a,u=0|o,a=0|s,o=0|i,s=0|r,i=0|n;const R=Xr(w,T,N);r=en(R,E,b,O),n=0|R}({h:r,l:n}=Qr(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=Qr(0|this.Bh,0|this.Bl,0|s,0|i)),({h:a,l:o}=Qr(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=Qr(0|this.Dh,0|this.Dl,0|c,0|u)),({h:d,l}=Qr(0|this.Eh,0|this.El,0|d,0|l)),({h,l:f}=Qr(0|this.Fh,0|this.Fl,0|h,0|f)),({h:p,l:y}=Qr(0|this.Gh,0|this.Gl,0|p,0|y)),({h:g,l:m}=Qr(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(){Tr(hn,fn)}destroy(){Tr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const yn=Cr(()=>new cn),gn=Cr(()=>new pn),mn=BigInt(0),vn=BigInt(1);function _n(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function kn(e,t,r=""){const n=_r(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 En(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?mn:BigInt("0x"+e)}function wn(e){return Er(e),En(Ar(Uint8Array.from(e).reverse()))}function bn(e,t){return Sr(e.toString(16).padStart(2*t,"0"))}function Tn(e,t){return bn(e,t).reverse()}function On(e,t,r){let n;if("string"==typeof t)try{n=Sr(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!_r(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 Rn=e=>"bigint"==typeof e&&mn<=e;function In(e,t,r,n){if(!function(e,t,r){return Rn(e)&&Rn(t)&&Rn(r)&&t<=e&&e<r}(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}const An=e=>(vn<<BigInt(e))-vn;function xn(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 Sn=()=>{throw new Error("not implemented")};function Dn(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 Un=BigInt(0),Pn=BigInt(1),Ln=BigInt(2),Cn=BigInt(3),Kn=BigInt(4),Vn=BigInt(5),$n=BigInt(7),Bn=BigInt(8),qn=BigInt(9),Fn=BigInt(16);function Mn(e,t){const r=e%t;return r>=Un?r:t+r}function jn(e,t,r){let n=e;for(;t-- >Un;)n*=n,n%=r;return n}function Hn(e,t){if(e===Un)throw new Error("invert: expected non-zero number");if(t<=Un)throw new Error("invert: expected positive modulus, got "+t);let r=Mn(e,t),n=t,s=Un,i=Pn,a=Pn,o=Un;for(;r!==Un;){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 Mn(s,t)}function Zn(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Wn(e,t){const r=(e.ORDER+Pn)/Kn,n=e.pow(t,r);return Zn(e,n,t),n}function zn(e,t){const r=(e.ORDER-Vn)/Bn,n=e.mul(t,Ln),s=e.pow(n,r),i=e.mul(t,s),a=e.mul(e.mul(i,Ln),s),o=e.mul(i,e.sub(a,e.ONE));return Zn(e,o,t),o}function Gn(e){if(e<Cn)throw new Error("sqrt is not defined for small field");let t=e-Pn,r=0;for(;t%Ln===Un;)t/=Ln,r++;let n=Ln;const s=es(e);for(;1===Xn(s,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Wn;let i=s.pow(n,t);const a=(t+Pn)/Ln;return function(e,n){if(e.is0(n))return n;if(1!==Xn(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 Jn=(e,t)=>(Mn(e,t)&Pn)===Pn,Yn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Qn(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 Xn(e,t){const r=(e.ORDER-Pn)/Ln,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 es(e,t,r=!1,n={}){if(e<=Un)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&&kr(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:An(c),ZERO:Un,ONE:Pn,allowedLengths:a,create:t=>Mn(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Un<=t&&t<e},is0:e=>e===Un,isValidNot0:e=>!l.is0(e)&&l.isValid(e),isOdd:e=>(e&Pn)===Pn,neg:t=>Mn(-t,e),eql:(e,t)=>e===t,sqr:t=>Mn(t*t,e),add:(t,r)=>Mn(t+r,e),sub:(t,r)=>Mn(t-r,e),mul:(t,r)=>Mn(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Un)throw new Error("invalid exponent, negatives unsupported");if(r===Un)return e.ONE;if(r===Pn)return t;let n=e.ONE,s=t;for(;r>Un;)r&Pn&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Pn;return n}(l,e,t),div:(t,r)=>Mn(t*Hn(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Hn(t,e),sqrt:i||(t=>{return d||(d=(r=e)%Kn===Cn?Wn:r%Bn===Vn?zn:r%Fn===qn?function(e){const t=es(e),r=Gn(e),n=r(t,t.neg(t.ONE)),s=r(t,n),i=r(t,t.neg(n)),a=(e+$n)/Fn;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 Zn(e,f,t),f}}(r):Gn(r)),d(l,t);var r}),toBytes:e=>r?Tn(e,u):bn(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 En(Ar(e))}(t);if(o&&(s=Mn(s,e)),!n&&!l.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Qn(l,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(l)}const ts=BigInt(0),rs=BigInt(1);function ns(e,t){const r=t.negate();return e?r:t}function ss(e,t){const r=Qn(e.Fp,t.map(e=>e.Z));return t.map((t,n)=>e.fromAffine(t.toAffine(r[n])))}function is(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function as(e,t){is(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:An(e),maxNumber:r,shiftBy:BigInt(e)}}function os(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+=rs);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 cs=new WeakMap,us=new WeakMap;function ds(e){return us.get(e)||1}function ls(e){if(e!==ts)throw new Error("invalid wNAF")}class hs{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>ts;)t&rs&&(r=r.add(n)),n=n.double(),t>>=rs;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=as(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=as(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:d,offsetF:l}=os(r,e,i);r=a,c?s=s.add(ns(d,t[l])):n=n.add(ns(u,t[o]))}return ls(r),{p:n,f:s}}wNAFUnsafe(e,t,r,n=this.ZERO){const s=as(e,this.bits);for(let e=0;e<s.windows&&r!==ts;e++){const{nextN:i,offset:a,isZero:o,isNeg:c}=os(r,e,s);if(r=i,!o){const e=t[a];n=n.add(c?e.negate():e)}}return ls(r),n}getPrecomputes(e,t,r){let n=cs.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),cs.set(t,n))),n}cached(e,t,r){const n=ds(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const s=ds(e);return 1===s?this._unsafeLadder(e,t,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),t,n)}createCache(e,t){is(t,this.bits),us.set(e,t),cs.delete(e)}hasCache(e){return 1!==ds(e)}}function fs(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>>=vn,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=An(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 ps(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){xn(e,Yn.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return es(e,{isLE:r})}const ys=BigInt(0),gs=BigInt(1),ms=BigInt(2),vs=BigInt(8);class _s{constructor(e){this.ep=e}static fromBytes(e){Sn()}static fromHex(e){Sn()}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 Ar(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 ks(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:es(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');xn(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||Kr,c=r.adjustScalarBytes||(e=>e),u=r.domain||((e,t,r)=>{if(_n(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=On("private key",e,r);const n=On("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,On("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 kn(e,g.seed,"seed")}const v={getExtendedPublicKey:l,randomSecretKey:m,isValidSecretKey:function(e){return _r(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(gs+r,gs-r):i.div(r-gs,r+gs);return i.toBytes(a)},toMontgomerySecret(e){const r=g.secretKey;kn(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=On("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 kn(Pr(d,a.toBytes(p)),g.signature,"result")},verify:function(t,r,i,a=p){const{context:o,zip215:c}=a,u=g.signature;t=On("signature",t,u),r=On("message",r),i=On("publicKey",i,g.publicKey),void 0!==c&&_n(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>ts))throw new Error(`CURVE.${e} must be positive bigint`)}const s=ps(t.p,r.Fp,n),i=ps(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;xn(t,{},{uvRatio:"function"});const o=ms<<BigInt(8*s.BYTES)-gs,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:ys}}});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 In("coordinate "+e,t,r?gs:ys,o),t}function l(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const h=Dn((e,t)=>{const{X:r,Y:s,Z:i}=e,a=e.is0();null==t&&(t=a?vs:n.inv(i));const o=c(r*t),u=c(s*t),d=n.mul(i,t);if(a)return{x:ys,y:gs};if(d!==gs)throw new Error("invZ was invalid");return{x:o,y:u}}),f=Dn(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,gs,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:s,d:a}=i;e=Nn(kn(e,r,"point")),_n(t,"zip215");const d=Nn(e),l=e[r-1];d[r-1]=-129&l;const h=wn(d),f=t?o:n.ORDER;In("point.y",h,ys,f);const y=c(h*h),g=c(y-gs),m=c(a*y-s);let{isValid:v,value:_}=u(g,m);if(!v)throw new Error("bad point: invalid y coordinate");const k=(_&gs)===gs,E=!!(128&l);if(!t&&_===ys&&E)throw new Error("bad point: x=0 and x_0=1");return E!==k&&(_=c(-_)),p.fromAffine({x:_,y:h})}static fromHex(e,t=!1){return p.fromBytes(On("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,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,E=v+m,w=c(g-t*y),b=c(_*k),T=c(E*w),O=c(_*w),N=c(k*E);return new p(b,T,N,O)}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=>ss(p,e));return ss(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===ys?p.ZERO:this.is0()||e===gs?this:y.unsafe(this,e,e=>ss(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===gs?this:this.multiplyUnsafe(a)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&gs?128:0,r}toHex(){return Ar(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 ss(p,e)}static msm(e,t){return fs(p,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,gs,c(i.Gx*i.Gy)),p.ZERO=new p(ys,gs,gs,ys),p.Fp=n,p.Fn=s;const y=new hs(p,s.BITS);return p.BASE.precompute(8),p}(t,r),n,s))}Dr("HashToScalar-");const Es=BigInt(0),ws=BigInt(1),bs=BigInt(2);const Ts=BigInt(0),Os=BigInt(1),Ns=BigInt(2),Rs=BigInt(3),Is=BigInt(5),As=BigInt(8),xs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ss=(()=>({p:xs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:As,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ds(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),i=xs,a=e*e%i*e%i,o=jn(a,Ns,i)*a%i,c=jn(o,Os,i)*e%i,u=jn(c,Is,i)*c%i,d=jn(u,t,i)*u%i,l=jn(d,r,i)*d%i,h=jn(l,n,i)*l%i,f=jn(h,s,i)*h%i,p=jn(f,s,i)*h%i,y=jn(p,t,i)*u%i;return{pow_p_5_8:jn(y,Ns,i)*e%i,b2:a}}function Us(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ps=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ls(e,t){const r=xs,n=Mn(t*t*t,r),s=Mn(n*n*t,r);let i=Mn(e*n*Ds(e*s).pow_p_5_8,r);const a=Mn(t*i*i,r),o=i,c=Mn(i*Ps,r),u=a===e,d=a===Mn(-e,r),l=a===Mn(-e*Ps,r);return u&&(i=o),(d||l)&&(i=c),Jn(i,r)&&(i=Mn(-i,r)),{isValid:u||d,value:i}}const Cs=(()=>es(Ss.p,{isLE:!0}))(),Ks=(()=>es(Ss.n,{isLE:!0}))(),Vs=(()=>({...Ss,Fp:Cs,hash:gn,adjustScalarBytes:Us,uvRatio:Ls}))(),$s=(()=>ks(Vs))(),Bs=(()=>{const e=Cs.ORDER;return function(e){const t=(xn(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||Kr,d=c?255:448,l=c?32:56,h=c?BigInt(9):BigInt(5),f=c?BigInt(121665):BigInt(39081),p=c?bs**BigInt(254):bs**BigInt(447),y=c?BigInt(8)*bs**BigInt(251)-ws:BigInt(4)*bs**BigInt(445)-ws,g=p+y+ws,m=e=>Mn(e,n),v=_(h);function _(e){return Tn(m(e),l)}function k(e,t){const r=function(e,t){In("u",e,Es,n),In("scalar",t,p,g);const r=t,s=e;let i=ws,o=Es,c=e,u=ws,l=Es;for(let e=BigInt(d-1);e>=Es;e--){const t=r>>e&ws;l^=t,({x_2:i,x_3:c}=w(l,i,c)),({x_2:o,x_3:u}=w(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}=w(l,i,c)),({x_2:o,x_3:u}=w(l,o,u));const h=a(o);return m(i*h)}(function(e){const t=On("u coordinate",e,l);return c&&(t[31]&=127),m(wn(t))}(t),function(e){return wn(i(On("scalar",e,l)))}(e));if(r===Es)throw new Error("invalid private or public key received");return _(r)}function E(e){return k(e,v)}function w(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))=>(Er(e,b.seed),e);return{keygen:function(e){const t=T(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>k(e,t),getPublicKey:e=>E(e),scalarMult:k,scalarMultBase:E,utils:{randomSecretKey:T,randomPrivateKey:T},GuBytes:v.slice(),lengths:b}}({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:r,b2:n}=Ds(t);return Mn(jn(r,Rs,e)*n,e)},adjustScalarBytes:Us})})(),qs=Ps,Fs=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ms=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),js=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Hs=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Zs=e=>Ls(Os,e),Ws=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),zs=e=>$s.Point.Fp.create(wn(e)&Ws);function Gs(e){const{d:t}=Ss,r=xs,n=e=>Cs.create(e),s=n(qs*e*e),i=n((s+Os)*js);let a=BigInt(-1);const o=n((a-t*s)*n(s+t));let{isValid:c,value:u}=Ls(i,o),d=n(u*e);Jn(d,r)||(d=n(-d)),c||(u=d),c||(a=s);const l=n(a*(s-Os)*Hs-o),h=u*u,f=n((u+u)*o),p=n(l*Fs),y=n(Os-h),g=n(Os+h);return new $s.Point(n(f*g),n(y*p),n(p*g),n(f*y))}class Js extends _s{constructor(e){super(e)}static fromAffine(e){return new Js($s.Point.fromAffine(e))}assertSame(e){if(!(e instanceof Js))throw new Error("RistrettoPoint expected")}init(e){return new Js(e)}static hashToCurve(e){return function(e){Er(e,64);const t=Gs(zs(e.subarray(0,32))),r=Gs(zs(e.subarray(32,64)));return new Js(t.add(r))}(On("ristrettoHash",e,64))}static fromBytes(e){Er(e,32);const{a:t,d:r}=Ss,n=xs,s=e=>Cs.create(e),i=zs(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}(Cs.toBytes(i),e)||Jn(i,n))throw new Error("invalid ristretto255 encoding 1");const a=s(i*i),o=s(Os+t*a),c=s(Os-t*a),u=s(o*o),d=s(c*c),l=s(t*r*u-d),{isValid:h,value:f}=Zs(s(l*d)),p=s(f*c),y=s(f*p*l);let g=s((i+i)*p);Jn(g,n)&&(g=s(-g));const m=s(o*y),v=s(g*m);if(!h||Jn(v,n)||m===Ts)throw new Error("invalid ristretto255 encoding 2");return new Js(new $s.Point(g,m,Os,v))}static fromHex(e){return Js.fromBytes(On("ristrettoHex",e,32))}static msm(e,t){return fs(Js,$s.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep;const s=xs,i=e=>Cs.create(e),a=i(i(r+t)*i(r-t)),o=i(e*t),c=i(o*o),{value:u}=Zs(i(a*c)),d=i(u*a),l=i(u*o),h=i(d*l*n);let f;if(Jn(n*h,s)){let r=i(t*qs),n=i(e*qs);e=r,t=n,f=i(d*Ms)}else f=l;Jn(e*h,s)&&(t=i(-t));let p=i((r-t)*f);return Jn(p,s)&&(p=i(-p)),Cs.toBytes(p)}equals(e){this.assertSame(e);const{X:t,Y:r}=this.ep,{X:n,Y:s}=e.ep,i=e=>Cs.create(e),a=i(t*s)===i(r*n),o=i(r*s)===i(t*n);return a||o}is0(){return this.equals(Js.ZERO)}}Js.BASE=(()=>new Js($s.Point.BASE))(),Js.ZERO=(()=>new Js($s.Point.ZERO))(),Js.Fp=(()=>Cs)(),Js.Fn=(()=>Ks)();class Ys extends Lr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,wr(e);const r=Ur(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),Tr(s)}update(e){return br(this),this.iHash.update(e),this}digestInto(e){br(this),Er(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 Qs=(e,t,r)=>new Ys(e,t).update(r).digest();Qs.create=(e,t)=>new Ys(e,t);const Xs=Uint8Array.from([0]),ei=Uint8Array.of(),ti=(e,t,r,n,s)=>function(e,t,r,n=32){wr(e),kr(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=ei);const a=new Uint8Array(i*s),o=Qs.create(e,t),c=o._cloneInto(),u=new Uint8Array(o.outputLen);for(let e=0;e<i;e++)Xs[0]=e+1,c.update(0===e?ei:u).update(r).update(Xs).digestInto(u),a.set(u,s*e),o._cloneInto(c);return o.destroy(),c.destroy(),Tr(u,Xs),a.slice(0,n)}(e,function(e,t,r){return wr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Qs(e,Ur(r),Ur(t))}(e,t,r),n,s),ri=yn;var ni=r(4290),si={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"},ii=(si.NODE_BUSY,si.REQUEST_TIMEOUT,"telemetry.span");function ai(e){return{ok:!0,data:e}}function oi(e){return{ok:!1,error:e}}function ci(e,t,r,n){return{code:e,message:t,service:r,cause:n?.cause,meta:n?.meta}}var ui="[REDACTED]",di=new Set(["duration","durationMs","endedAt","startedAt","status","timestamp","latencyMs","stalenessMs","count","changes","deleted","fetched","pages","lagMs","pendingCleared","partitions","remaining","expiryMs"]),li=new Set(["authenticated","ok","persisted","purgePending"]),hi={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 fi(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function pi(e,t){try{return e[t]}catch{return ui}}function yi(e){if(null==e)return e;if("object"!=typeof e)return ui;try{if(function(e){try{return Array.isArray(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}catch{return!0}}(e))return ui;const t={};for(const r of di){const n=fi(pi(e,r));void 0!==n&&(t[r]=n)}for(const r of li){const n=pi(e,r);"boolean"==typeof n&&(t[r]=n)}for(const[r,n]of Object.entries(hi)){const s=pi(e,r);"string"==typeof s&&n.includes(s)&&(t[r]=s)}void 0!==pi(e,"url")&&(t.url=ui);const r=pi(e,"error");return void 0!==r&&(t.error=function(e){if("object"!=typeof e||null===e)return{};const t=fi(pi(e,"status"));return void 0!==t&&t>=100&&t<=599?{status:t}:{}}(r)),t}catch{return ui}}var gi="TinyCloud_debug";function mi(){return globalThis}function vi(){const e=globalThis.performance?.now?.bind(globalThis.performance);return"function"==typeof e?e():Date.now()}function _i(e){return!0===e||"true"===e||"1"===e}function ki(){const e=globalThis.process;return e?.env?.[gi]}function Ei(){if(mi().window===globalThis)try{return globalThis.localStorage}catch{return}}function wi(e){const t=Ei();if(t)try{e?t.setItem(gi,"true"):t.removeItem(gi)}catch{}}var bi=new class{constructor(){this.enabled=_i(mi()[gi])||_i(function(){const e=Ei();if(e)try{return e.getItem(gi)}catch{return}}())||_i(ki()),this.sequence=0,this.events=[],this.maxEvents=1e3}isEnabled(){return this.enabled||_i(mi()[gi])||_i(ki())}enable(e={}){this.enabled=!0,mi()[gi]=!0,!1!==e.persist&&wi(!0),this.log("debug.enabled",{persisted:!1!==e.persist})}disable(e={}){this.log("debug.disabled",{persisted:!1!==e.persist}),this.enabled=!1,mi()[gi]=!1,!1!==e.persist&&wi(!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=vi();return this.log(`${e}.start`,t),{stop:t=>{const n=vi();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:yi(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 Ti(e){return bi.enable(e),bi}function Oi(e){return bi.disable(e),bi}function Ni(){return bi.getLogs()}function Ri(){bi.clear()}!function(){const e=mi();e.TinyCloudDebug=bi,e.enableTinyCloudDebug=Ti,e.disableTinyCloudDebug=Oi,e.getTinyCloudDebugLogs=Ni,e.clearTinyCloudDebugLogs=Ri}();var Ii=Me({code:Ve(),message:Ve(),service:Ve(),cause:qe().optional(),meta:Me({}).passthrough().optional()});function Ai(e,t=Ii){return je("ok",[Me({ok:Ze(!0),data:e}),Me({ok:Ze(!1),error:t})])}Ai(qe(),Ii);var xi,Si=Me({etag:Ve().optional(),contentType:Ve().optional(),lastModified:Ve().optional(),contentLength:$e().optional()});function Di(e){try{return JSON.parse(e)}catch{return{}}}function Ui(e,t,r,n,s){return s.message?Li(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} - ${Li(n)}`;var i}function Pi(e,t,r){const n={status:e,statusText:t},s=Li(r);return s&&(n.responseSnippet=s.slice(0,300)),n}function Li(e){const t=e.replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,500)}...`:t}xi=qe(),Me({data:xi,headers:Si}),Ai(Me({keys:Fe(Ve()),truncated:Be().optional(),nextCursor:Ve().optional()})),Me({service:Ve(),action:Ve(),span:Ve().optional(),key:Ve().optional(),timestamp:$e()}),Me({service:Ve(),action:Ve(),span:Ve().optional(),ok:Be(),duration:$e(),durationMs:$e().optional(),status:$e().optional()}),Me({service:Ve(),span:Ve().optional(),error:Ii}),Me({service:Ve(),attempt:$e().int().positive(),maxAttempts:$e().int().positive(),error:Ii}),Me({span:Ve(),ok:Be(),durationMs:$e(),service:Ve().optional(),action:Ve().optional(),status:$e().optional(),error:Ii.optional()}),Me({maxAttempts:$e().int().positive(),backoff:We(["none","linear","exponential"]),baseDelayMs:$e().nonnegative(),maxDelayMs:$e().nonnegative(),retryableErrors:Fe(Ve()),maxTotalMs:$e().positive().optional()}),Me({delegationHeader:Me({Authorization:Ve()}),delegationCid:Ve(),spaceId:Ve(),verificationMethod:Ve(),jwk:Me({}).passthrough()});var Ci="urn:tinycloud:encryption:",Ki=/^[a-z0-9][a-z0-9-]*$/,Vi=/^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/,$i=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Bi(e){if("string"!=typeof e||0===e.length)throw new $i("networkId must be a non-empty string");if(!e.startsWith(Ci))throw new $i(`networkId must start with ${Ci} (got ${JSON.stringify(e)})`);const t=e.slice(25),r=t.lastIndexOf(":");if(r<=0||r===t.length-1)throw new $i(`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 $i(`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 $i(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(n)})`);if(!Ki.test(s))throw new $i(`networkId name ${JSON.stringify(s)} must match ${Ki.source}`);return{networkId:e,ownerDid:n,name:s}}function qi(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 $i(`encryption resource has an invalid keyPath (got ${JSON.stringify(e)})`);return{...i,keyPath:a}}function Fi(e){const t=e.match(Vi);return t?{chainId:t[1],address:t[2].toLowerCase()}:null}function Mi(e,t){const r=Fi(e),n=Fi(t);return r&&n?r.chainId===n.chainId&&r.address===n.address:e===t}Error,Error,Error,Error;var ji={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 Hi(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(ji,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 Zi(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 Wi(e){return{code:si.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=si.REQUEST_TIMEOUT;else{if(500!==r.status||"outcome_unknown"!==i)return;o=si.OUTCOME_UNKNOWN}else o=si.NODE_BUSY;const c=o!==si.OUTCOME_UNKNOWN,u=r.headers.get("retry-after")?.trim();return ci(o,t,e,{meta:{...Pi(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 Gi=class extends Error{constructor(e){super(`Request timed out after ${e}ms.`),this.name="TimeoutError",this.timeoutMs=e}};function Ji(e){return e instanceof Gi||e instanceof Error&&"TimeoutError"===e.name&&"number"==typeof e.timeoutMs}function Yi(e,t,r){return void 0===t?{code:si.TIMEOUT,message:"Request timed out.",service:e,...void 0===r?{}:{cause:r}}:{code:si.TIMEOUT,message:`Request timed out after ${t}ms.`,service:e,...void 0===r?{}:{cause:r},meta:{timeoutMs:t}}}function Qi(e){const t=e.match(/^Unauthorized Action:\s*(.+?)\s*\/\s*(tinycloud\.\S+)$/m);return t?{resource:t[1].trim(),action:t[2].trim()}:{}}var Xi=new Set(at.map(({urn:e})=>e).filter(e=>!e.endsWith("/*"))),ea=new Set(at.map(({service:e})=>e.slice(10)));function ta(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||!ea.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&&ea.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 ra(e){const t=ia(e);if("unauthenticated"!==t&&"forbidden"!==t)return;const r=new Set;let n=e;for(let e=0;e<na&&"object"==typeof n&&null!==n&&!r.has(n);e+=1){r.add(n);const e=n,t=sa(e),s=e.meta;if((401===t||403===t||void 0===t&&e.code===si.AUTH_UNAUTHORIZED)&&"object"==typeof s&&null!==s&&!Array.isArray(s)){const t=s,{resource:r,requiredAction:n}=t;if("string"==typeof n&&Xi.has(n)){const s=n.slice(10,n.indexOf("/")),i=void 0===e.service?t.service:e.service;if(ta(r,s,n)&&(void 0===i||i===s||i===`tinycloud.${s}`))return{resource:r,requiredAction:n}}}n=e.cause}}var na=8;function sa(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 ia(e){const t=new Set;let r=!1,n=e;for(let e=0;e<na&&"object"==typeof n&&null!==n&&!t.has(n);e+=1){t.add(n);const e=n,s=sa(e);if(401===s)return"unauthenticated";if(403===s)return"forbidden";if(void 0!==s)return"other";e.code===si.AUTH_UNAUTHORIZED&&(r=!0),n=e.cause}return r?"forbidden":void 0}function aa(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 oa={storage_quota_exceeded:!0,storage_limit_reached:!0};function ca(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=0}function ua(e){if("object"!=typeof e||null===e)return;const{usedBytes:t,limitBytes:r}=e;return ca(t)&&ca(r)?{usedBytes:t,limitBytes:r}:void 0}function da(e){let t;try{t=JSON.parse(e)}catch{return aa(e)}if("object"!=typeof t||null===t)return;const r=t,n="string"==typeof r.message?r.message:"",s=ua(r.space)??aa(n),i="string"==typeof r.error&&!0===oa[r.error];if(!s&&!i)return;const a={...s},o=ua(r.account);if(o){const e=r.account.plan;a.account="string"==typeof e&&""!==e?{...o,plan:e}:o}return a}function la(e,t,r,n){const s={...r,...da(n)};return 402===t?function(e,t,r){return{code:si.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:si.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 ha(e,t,r=si.NETWORK_ERROR){const n=Hi(t);return n?{...n,service:e}:t instanceof Error?Ji(t)?Yi(e,t.timeoutMs,t):"AbortError"===t.name?function(e){return{code:si.ABORTED,message:"Request was aborted.",service:e}}(e):"TimeoutError"===t.name||t.message.toLowerCase().includes("timeout")?Yi(e):{code:r,message:t.message,service:e,cause:t}:{code:r,message:String(t),service:e}}var fa=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(ii,{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 Gi(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=ha(this.getServiceName(),t);return this.emitResponse(e,!1,n),this.emitError(r,e),oi(r)}}},pa=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?ai({...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 oi(ci(si.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?ai({...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?ai({...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)}},ya="tinycloud.kv/get",ga="tinycloud.kv/put",ma="tinycloud.kv/list",va="tinycloud.kv/del",_a="tinycloud.kv/metadata",ka="tinycloud.kv/sync";function Ea(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var wa=new TextEncoder,ba=/^(?:Invalid invocation: )?delegation-(?:(revoked): [A-Za-z0-9]+|(ancestor-revoked): ancestor=[A-Za-z0-9]+ invoked=[A-Za-z0-9]+)$/,Ta=new Set(["delegation_revoked","parent_revoked","ancestor_revoked"]);function Oa(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Na(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 fa{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||da(t)))return oi(la("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)?oi(ci(si.KV_NOT_FOUND,`KV ${e.status} - ${r}`,"kv",{meta:{status:e.status,statusText:e.statusText}})):oi(ci(si.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=wa.encode(e),n=wa.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 oi(Wi("kv"));if(0===e.length)return ai({results:[],count:0});if(e.length>100)return oi(ci(si.INVALID_INPUT,"KV batch reads accept at most 100 keys","kv"));if(1===e.length){const n=e[0];return ai({results:[{key:n,result:t===ya?await this.get(n,r):await this.head(n,r)}],count:1})}if(!this.context.invokeAny)return oi(ci(si.INVALID_INPUT,"KV batch reads require SDK runtime support for multi-resource invocations","kv"));const n=t===ya?r:void 0;if(void 0!==n?.maxResponseBytes&&(!Number.isSafeInteger(n.maxResponseBytes)||n.maxResponseBytes<=0))return oi(ci(si.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 oi(ci(si.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?oi(ci(si.KV_RESPONSE_TOO_LARGE,"A KV batch value exceeds the requested response limit","kv",{meta:{status:a.status,statusText:a.statusText}})):oi(ci(si.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===ya);if(!o)return oi(ci(si.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:oi(ci(r.error.code,r.error.message,"kv"))};const i=r.headers,a=t===_a?void 0:this.parseBatchValue(r.dataBase64,i,n?.raw,n?.binary);return{key:e[s],result:ai({data:a,headers:this.createBatchResponseHeaders(i)})}});return ai({results:c,count:c.length})}catch(e){return oi(ha("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],ya):oi(ci(400===e.status?si.INVALID_INPUT:si.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}=Qi(r),c=n.find(e=>a===e||a===`${this.context.session.spaceId}/kv/${e}`),u=void 0!==c&&o===s?ra({service:"kv",code:si.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 oi((l=`${e}: ${t.status} - ${d}`,h={status:t.status,...i,...u},ci(si.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 oi(Wi("kv"));if(void 0!==t?.maxResponseBytes&&(!Number.isSafeInteger(t.maxResponseBytes)||t.maxResponseBytes<=0))return oi(ci(si.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===si.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 oi(ha("kv",e))}finally{n.dispose()}})}async getFromNetwork(e,t,r,n){const s=await this.invokeOperation(t,ya,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 Zi(r.permissionHint)??Zi(s?.permissionHint)}catch{return}}(r),i="tinycloud.kv"===n?.service&&n.space===this.context.session.spaceId&&n.path===t?ra({service:"kv",code:si.AUTH_UNAUTHORIZED,meta:{status:s.status,resource:`${this.context.session.spaceId}/kv/${t}`,requiredAction:ya}}):void 0;return this.authorizationFailure(`Failed to get key ${JSON.stringify(e)}`,s,r,[t],ya,i?{permissionHint:n,...i}:{})}if(404===s.status)return this.classifyNotFound(s,e);const r=await s.text();if(413===s.status)return oi(ci(si.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 oi(i||ci(si.NETWORK_ERROR,n,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return ai({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,ya,t))}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return oi(Wi("kv"));if(void 0!==r?.ifMatch&&void 0!==r.ifNoneMatch)return oi(ci(si.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 oi(ha("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 oi(ci(si.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 oi(n);return this.handleQuotaErrorResponse(i,t,e)||oi(ci(si.KV_WRITE_FAILED,r,"kv",{meta:{status:i.status,statusText:i.statusText}}))}return ai({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 oi(Wi("kv"));if(0===e.length)return ai({written:[],count:0});if(!this.context.invokeAny)return oi(ci(si.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 oi(ci(si.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=ha("kv",e);return oi({...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 oi(ci(si.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")||oi(ci(si.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=Ji(t);return oi(ci(r?si.TIMEOUT:si.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 oi(ci(si.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))?ai(u):oi(ci(si.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=ha("kv",e);return oi({...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 oi(Wi("kv"));if(void 0!==e?.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return oi(ci(si.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 oi(ha("kv",e))}finally{r.dispose()}})}async listFromNetwork(e,t,r){const n=await this.invokeOperation(e,ma,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],ma);const t=await n.text(),r=`Failed to list keys: ${n.status} - ${t}`,s=zi("kv",r,n,t);return oi(s||ci(si.NETWORK_ERROR,r,"kv",{meta:{status:n.status,statusText:n.statusText}}))}return ai({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 ai({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 oi(Wi("kv"));if("string"!=typeof e?.prefix||0===e.prefix.length)return oi(ci(si.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 oi(ci(si.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,ka,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?ai(o):oi(ci(si.NETWORK_ERROR,"KV changes response was not a tinycloud.kv/sync page","kv",{meta:{status:s.status,statusText:s.statusText}}))}catch(e){return oi(ha("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 oi(ci(si.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 oi(ci(si.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=ba.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&&Ta.has(e.code)&&"string"==typeof e.error)return e.error}catch{}return t}(e));if(null!==t)return void 0!==t[1]?si.AUTH_DELEGATION_REVOKED:si.AUTH_DELEGATION_ANCESTOR_REVOKED}(n);if(void 0!==e)return oi(ci(e,`${o}: 401 - ${n}`,"kv",{meta:s}))}return 401===e.status||403===e.status?this.authorizationFailure(o,e,n,[t],ka):oi(ci(400===e.status?si.INVALID_INPUT:si.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 oi(Wi("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 oi(ha("kv",e))}finally{n.dispose()}})}async deleteFromNetwork(e,t,r,n){const s=await this.invokeOperation(t,va,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],va);if(404===s.status)return this.classifyNotFound(s,e);const r=await s.text();if(412===s.status)return oi(ci(si.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 oi(i||ci(si.NETWORK_ERROR,n,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return ai({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 oi(Wi("kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeOperation(r,_a,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],_a);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 oi(i||ci(si.NETWORK_ERROR,s,"kv",{meta:{status:t.status,statusText:t.statusText}}))}return ai({data:void 0,headers:this.createResponseHeaders(t.headers)})}catch(e){return oi(ha("kv",e))}finally{n.dispose()}})}async batchHead(e,t){return this.withTelemetry("batchHead",String(e.length),()=>this.batchRead(e,_a,t))}async createSignedReadUrl(e,t){return this.withTelemetry("createSignedReadUrl",e,async()=>{if(!this.requireAuth())return oi(Wi("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,ya),{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?ai(a):oi(ci(si.NETWORK_ERROR,"Signed read URL response did not include url, ticketId, and expiresAt","kv"))}catch(e){return oi(ha("kv",e))}finally{i.dispose()}})}withPrefix(e){return new pa(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)}},Ia=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)}},Aa={READ:tt.READ,WRITE:tt.WRITE,SCHEMA:tt.SCHEMA,ADMIN:tt.ADMIN,SELECT:tt.SELECT,EXECUTE:tt.EXECUTE,EXPORT:tt.EXPORT,ALL:tt.ALL},xa=new Set(["alter","create","drop"]),Sa="__tinycloud_sql_migrations",Da=`CREATE TABLE IF NOT EXISTS ${Sa} (\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",Pa="000_metadata";function La(e){return e.map(e=>e instanceof Uint8Array?Array.from(e):e)}function Ca(e){return/no such table/i.test(e)}function Ka(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Va(e,t){return Array.isArray(e)?e[t]:e&&"object"==typeof e?Object.values(e)[t]:void 0}(class extends fa{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 Ia(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 oi(ci(si.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 oi(Wi("sql"));const s=this.createRequestSignal(n?.signal);try{const i={action:"query",sql:t,params:La(r??[])};void 0!==n?.maxRows&&(i.maxRows=n.maxRows),void 0!==n?.maxBytes&&(i.maxBytes=n.maxBytes);const a=this.actionForSql(t,Aa.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 ai(await o.json())}catch(e){return this.redactFailure(oi(ha("sql",e)),n?.redactErrors)}finally{s.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return oi(Wi("sql"));const s=this.createRequestSignal(n?.signal);try{const i={action:"execute",sql:t,params:La(r??[])};n?.schema&&(i.schema=n.schema);const a=[this.actionForSql(t,Aa.WRITE),...(n?.schema??[]).map(e=>this.actionForSql(e,Aa.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 ai(await c.json())}catch(e){return this.redactFailure(oi(ha("sql",e)),n?.redactErrors)}finally{s.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return oi(Wi("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 ai(await i.json())}catch(e){return this.redactFailure(oi(ha("sql",e)),r?.redactErrors)}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return oi(Wi("sql"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeSQL(e,Aa.WRITE,{action:"execute_statement",name:t,params:r??[]},s.signal);return n.ok?ai(await n.json()):await this.handleErrorResponse(n,"executeStatement",e,[Aa.WRITE])}catch(e){return oi(ha("sql",e))}finally{s.dispose()}})}async exportDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return oi(Wi("sql"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeSQL(e,Aa.READ,{action:"export"},r.signal);if(!t.ok)return await this.handleErrorResponse(t,"export",e,[Aa.READ]);const n=t;return"function"==typeof n.blob?ai(await n.blob()):ai(await t.text())}catch(e){return oi(ha("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='${Sa}'`,[],{signal:t.signal});let n=r.ok?0===r.data.rows.length:r.error.code===si.SQL_DATABASE_NOT_FOUND||Ca(r.error.message);if(!r.ok&&!n)return r;const s=new Set;if(!n){const r=await this.queryOnDb(e,`SELECT id FROM ${Sa} WHERE namespace = ? ORDER BY applied_at, id`,[t.namespace],{signal:t.signal});if(n=!r.ok&&(r.error.code===si.SQL_DATABASE_NOT_FOUND||Ca(r.error.message)),!r.ok&&!n)return r;if(r.ok)for(const e of r.data.rows){const t=Va(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 ai({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 ${Sa} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[Ka(t,r.id),t,r.id,(new Date).toISOString(),r.sql.length]}],i=await this.batchOnDb(e,s,{signal:n});return i.ok?ai(void 0):i}async ensureMigrationsTable(e,t){const r=await this.batchOnDb(e,[{sql:Da},{sql:`INSERT OR REPLACE INTO ${Sa} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[Ka(Ua,Pa),Ua,Pa,(new Date).toISOString(),1]}],{signal:t});return r.ok?ai(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?Aa.ADMIN:void 0!==r&&xa.has(r)?Aa.SCHEMA:t}actionsForSqlBatch(e){return this.dedupeActions(e.map(e=>this.actionForSql(e.sql,Aa.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(si,n)?n:si.SQL_ERROR,i="number"==typeof r&&Number.isInteger(r)&&r>=400&&r<=599?r:void 0;return oi(ci(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=Pi(e.status,e.statusText,s);if(402===e.status)return oi(la("sql",402,i,s));if(413===e.status&&da(s))return oi(la("sql",413,i,s));const a=zi("sql",`SQL ${t} failed: ${e.status} - ${s}`,e,s);if(a)return oi(a);const o=Di(s),c=Na("sql",t,e.status,s)??this.mapHttpStatusToErrorCode(e.status,o.error),u=Ui("SQL",t,e.status,s,o);if(401===e.status){const{action:e}=Qi(s);e&&n.includes(e)&&(i.requiredAction=e,i.resource=`${this.context.session.spaceId}/sql/${r}`)}return oi(ci(c,u,"sql",{meta:i}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return si.SQL_ERROR;case 401:return si.AUTH_UNAUTHORIZED;case 403:return"sql_readonly_violation"===t?si.SQL_READONLY_VIOLATION:si.SQL_PERMISSION_DENIED;case 404:return si.SQL_DATABASE_NOT_FOUND;case 413:return si.SQL_RESPONSE_TOO_LARGE;case 429:return si.SQL_QUOTA_EXCEEDED;default:return si.NETWORK_ERROR}}}).serviceName="sql";var $a=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)}},Ba={READ:rt.READ,WRITE:rt.WRITE,ADMIN:rt.ADMIN,DESCRIBE:rt.DESCRIBE,EXPORT:rt.EXPORT,IMPORT:rt.IMPORT,EXECUTE:rt.EXECUTE,ALL:rt.ALL};(class extends fa{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 $a(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 oi(Wi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Ba.READ,{action:"query",sql:t,params:r??[]},s.signal);return n.ok?ai(await n.json()):await this.handleErrorResponse(n,"query")}catch(e){return oi(ha("duckdb",e))}finally{s.dispose()}})}async queryArrowOnDb(e,t,r,n){return this.withTelemetry("queryArrow",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Ba.READ,{action:"query",sql:t,params:r??[]},s.signal,{Accept:"application/vnd.apache.arrow.stream"});return n.ok?ai(await n.arrayBuffer()):await this.handleErrorResponse(n,"queryArrow")}catch(e){return oi(ha("duckdb",e))}finally{s.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return oi(Wi("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,Ba.WRITE,i,s.signal);return a.ok?ai(await a.json()):await this.handleErrorResponse(a,"execute")}catch(e){return oi(ha("duckdb",e))}finally{s.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return oi(Wi("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,Ba.WRITE,s,n.signal);return i.ok?ai(await i.json()):await this.handleErrorResponse(i,"batch")}catch(e){return oi(ha("duckdb",e))}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Ba.WRITE,{action:"executeStatement",name:t,params:r??[]},s.signal);return n.ok?ai(await n.json()):await this.handleErrorResponse(n,"executeStatement")}catch(e){return oi(ha("duckdb",e))}finally{s.dispose()}})}async describeDb(e,t){return this.withTelemetry("describe",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,Ba.READ,{action:"describe"},r.signal);return t.ok?ai(await t.json()):await this.handleErrorResponse(t,"describe")}catch(e){return oi(ha("duckdb",e))}finally{r.dispose()}})}async exportOnDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,Ba.EXPORT,{action:"export"},r.signal);return t.ok?ai(await t.blob()):await this.handleErrorResponse(t,"export")}catch(e){return oi(ha("duckdb",e))}finally{r.dispose()}})}async importOnDb(e,t,r){return this.withTelemetry("import",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const n=this.createRequestSignal(r?.signal);try{const r=await this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,Ba.IMPORT),{headers:{"Content-Type":"application/x-duckdb"},body:new Blob([t]),signal:n.signal});return r.ok?ai(void 0):await this.handleErrorResponse(r,"import")}catch(e){return oi(ha("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=Pi(e.status,e.statusText,r);if(402===e.status)return oi(la("duckdb",402,n,r));if(413===e.status&&da(r))return oi(la("duckdb",413,n,r));const s=zi("duckdb",`DuckDB ${t} failed: ${e.status} - ${r}`,e,r);if(s)return oi(s);const i=Di(r),a=Na("duckdb",t,e.status,r)??this.mapHttpStatusToErrorCode(e.status,i.error),o=Ui("DuckDB",t,e.status,r,i);if(401===e.status){const{resource:e,action:t}=Qi(r);t&&(n.requiredAction=t),e&&(n.resource=e)}return oi(ci(a,o,"duckdb",{meta:n}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return si.DUCKDB_ERROR;case 401:return si.AUTH_UNAUTHORIZED;case 403:return"duckdb_readonly_violation"===t?si.DUCKDB_READONLY_VIOLATION:si.DUCKDB_PERMISSION_DENIED;case 404:return si.DUCKDB_DATABASE_NOT_FOUND;case 413:return si.DUCKDB_RESPONSE_TOO_LARGE;case 429:return si.DUCKDB_QUOTA_EXCEEDED;default:return si.NETWORK_ERROR}}}).serviceName="duckdb";var qa=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 Fa(e,t){const r=so(t);return r?`${e}/${r}`:e}function Ma(e){return"number"==typeof e&&e>=400&&e<500&&408!==e&&429!==e}(class extends fa{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(to),n={requested:r,signatures:r.map(ro),ttlSeconds:t.ttlSeconds,onReady:t.onReady,queue:new qa},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 oi(Wi("hooks"));if("string"!=typeof e.secret||0===e.secret.trim().length)return oi(ci(si.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",Fa(e.service,e.pathPrefix)),{headers:{"content-type":"application/json"},body:JSON.stringify({space:e.space,service:e.service,pathPrefix:so(e.pathPrefix),abilities:e.abilities??[],callbackUrl:e.callbackUrl,secret:e.secret})});if(!t.ok)return oi(await io("hooks","failed to register webhook",t));const r=co(await t.json());return r?ai(r):oi(ha("hooks",new Error("Webhook registration response did not include a record")))}catch(e){return oi(ha("hooks",e))}}async list(e={}){if(!this.requireAuth())return oi(Wi("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=so(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?Fa(e.service,e.pathPrefix):"webhooks"),{method:"GET"});if(!r.ok)return oi(await io("hooks","failed to list webhooks",r));const n=function(e){if(Array.isArray(e))return e.map(e=>co(e)).filter(e=>null!==e);if(!e||"object"!=typeof e)return null;const t=e,r=uo(t.webhooks)??uo(t.subscriptions)??uo(t.hooks)??uo(t.data);if(r)return r;const n=lo(t);return n?[n]:null}(await r.json());return n?ai(n):oi(ha("hooks",new Error("Webhook list response did not include records")))}catch(e){return oi(ha("hooks",e))}}async unregister(e,t={}){if(!this.requireAuth())return oi(Wi("hooks"));try{const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks/${encodeURIComponent(e)}`,()=>this.createHookHeaders("tinycloud.hooks/unregister",t.target?Fa(t.target.service,t.target.pathPrefix):`webhooks/${e}`),{method:"DELETE"});return r.ok?ai(void 0):oi(await io("hooks","failed to unregister webhook",r))}catch(e){return oi(ha("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 Ha(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 Ha(n.signal,()=>io("hooks","failed to mint hook ticket",d));return a()?{kind:"refused",terminal:Ma(e),error:t}:{kind:"stopped"}}const l=await Ha(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 Ha(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:Wa(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=ao(t);r&&(yield r),e=n.indexOf("\n\n")}}n+=r.decode();const s=ao(n.trim());s&&(yield s)}(f.body,n.signal)[Symbol.asyncIterator]();try{for(;;){const t=await Ha(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=oo(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===ja?{kind:"stopped"}:{kind:"failed",error:Ga(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??Xa)(s,e,t))}catch{n.push(Promise.resolve())}s.push(eo(t)),r&&s.push(eo(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(ci(si.INVALID_INPUT,"Hook readiness callback failed","hooks"))}}}dispatch(e){for(const t of this._subscribers)no(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=ci(si.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 ja=Symbol("hooks attempt superseded");async function Ha(e,t){if(e.aborted)throw"function"!=typeof t&&t.then(Za,()=>{}),ja;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(ja))};e.addEventListener("abort",a,{once:!0}),r.then(e=>{s?Za(e):(s=!0,i(),t(e))},e=>{s||(s=!0,i(),n(e))})})}function Za(e){if(e instanceof Response&&e.body)try{e.body.cancel().then(()=>{},()=>{})}catch{}}function Wa(e){const t="number"==typeof e?e:void 0;return ci(si.NETWORK_ERROR,`hook stream open refused: ${t??"unknown status"}`,"hooks",{meta:{phase:"open",status:t}})}var za=new Set(["Error","TypeError","AbortError","TimeoutError","SyntaxError","RangeError","NetworkError"]);function Ga(e,t){const r=Qa(t,"name"),n="string"==typeof r&&za.has(r)?r:"Error",s=Ya(Qa(t,"code"))??Ya(Qa(Qa(t,"cause"),"code"));return ci(si.NETWORK_ERROR,`hook stream ${e} failed: ${n}${s?` (${s})`:""}`,"hooks",{meta:{phase:e,errorName:n,...s?{errorCode:s}:{}}})}var Ja=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 Ya(e){return"string"==typeof e&&Ja.has(e)?e:void 0}function Qa(e,t){if(null!==e&&("object"==typeof e||"function"==typeof e))try{return Reflect.get(e,t)}catch{return}}var Xa=(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 eo(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 to(e){return{...e,pathPrefix:"kv"===e.service?so(e.pathPrefix):e.pathPrefix?.replace(/^\/+/,"")||void 0,abilities:e.abilities?[...e.abilities]:[]}}function ro(e){return JSON.stringify({space:e.space,service:e.service,pathPrefix:e.pathPrefix??"",abilities:[...e.abilities??[]].sort()})}function no(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 so(e){if(!e)return;const t=e.replace(/^\/+|\/+$/g,"");return t.length>0?t:void 0}async function io(e,t,r){let n=r.statusText;try{const e=await r.text();e&&(n=e)}catch{}return ci(408===r.status||504===r.status?si.TIMEOUT:si.NETWORK_ERROR,`${t}: ${r.status} ${n}`,e,{meta:{status:r.status,statusText:r.statusText}})}function ao(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 oo(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 co(e){if(!e||"object"!=typeof e)return null;const t=e;return lo(t)??co(t.webhook)??co(t.hook)??co(t.subscription)??co(t.data)??null}function uo(e){return Array.isArray(e)?e.map(e=>co(e)).filter(e=>null!==e):null}function lo(e){const t=ho(e,"id"),r=ho(e,"space")??ho(e,"spaceId"),n=ho(e,"service"),s=ho(e,"callbackUrl")??ho(e,"callback_url");return t&&r&&n&&s?{id:t,space:r,service:n,pathPrefix:fo(e,"pathPrefix")??fo(e,"path_prefix"),abilities:yo(e,"abilities")??go(e,"abilitiesJson")??go(e,"abilities_json"),callbackUrl:s,active:po(e,"active")??!0,createdAt:ho(e,"createdAt")??ho(e,"created_at")??(new Date).toISOString(),subscriberDid:fo(e,"subscriberDid")??fo(e,"subscriber_did")}:null}function ho(e,t){const r=e[t];return"string"==typeof r?r:void 0}function fo(e,t){return ho(e,t)}function po(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function yo(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 mo(e){return void 0===e?"":vo(e)}function vo(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(vo).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)}:${vo(t)}`)}return`{${r.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}var _o="0123456789abcdef";function ko(e){let t="";for(let r=0;r<e.length;r++){const n=e[r];t+=_o[n>>4&15]+_o[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 wo(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 bo(e){return(new TextEncoder).encode(e)}function To(e,t){return ko(e(bo(mo(t))))}var Oo=/^[A-Z][A-Z0-9_]{0,63}$/,No=new Set(["default","global"]),Ro=/^[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&&Ro.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(No.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"]);var Ao={masterMessage:e=>`tinycloud-vault-master-v1:${e}`,identityMessage:"tinycloud-encryption-identity-v1"},xo="x-vault-version",So="x-vault-cipher",Do="x-vault-key-id",Uo="x-vault-content-type",Po="x-vault-kdf",Lo="x-vault-key-rotation",Co="x-vault-grant-version",Ko="x-vault-grantor",Vo="signatures",$o="__wrap_key__";function Bo(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof crypto&&void 0!==crypto.subtle}catch{return!1}}function qo(){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 Fo(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 Mo(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 jo(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 Ho(e){const t=await Fo(e,$o);if(t)return t;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Mo(e,$o,r),r}function Zo(e){return`sig:${e}`}async function Wo(e){if(!Bo())return null;try{const t=await qo(),r=await Fo(t,Zo(e));if(!r)return null;const n=await Ho(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 zo(e,t){if(Bo())try{const r=await qo(),n=await Ho(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 Mo(r,Zo(e),s)}catch{}}async function Go(e){if(Bo())try{const t=await qo();if(e)await jo(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 jo(t,r)}}catch{}}function Jo(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function Yo(e){return(new TextEncoder).encode(e)}function Qo(e){return(new TextDecoder).decode(e)}function Xo(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}function ec(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function tc(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 rc(e){return null!==e&&"object"==typeof e&&"data"in e?e.data:e}function nc(e){return"number"==typeof e.meta?.status}function sc(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 ic(e){return{ok:!1,error:{...e,service:"vault",message:sc(e)}}}function ac(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 oc(e){return e.replace(/0x[0-9a-fA-F]{40}/g,e=>e.toLowerCase())}function cc(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=Qo(wo(n.aad)))}catch{}const i=`:${r}`;return s.endsWith(i)&&oc(s.slice(0,-i.length))===oc(`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 uc=[500,502,503,504,520,522,524];function dc(e,t){const r=Hi(t);if(r)return ic(r);if(t.code===si.STORAGE_QUOTA_EXCEEDED||t.code===si.STORAGE_LIMIT_REACHED)return ic({code:t.code,message:t.message,meta:t.meta});const n=`${e}: ${t.message}`;return t.code===si.AUTH_UNAUTHORIZED?ic({code:"unauthenticated"===ia(t)?"AUTH_UNAUTHORIZED":"PERMISSION_DENIED",message:n,...void 0!==t.meta?{meta:t.meta}:{},cause:ac(t)}):ic({code:"STORAGE_ERROR",cause:new Error(n,{cause:ac(t)}),...void 0!==t.meta?{meta:t.meta}:{}})}function lc(e){return"not_found"===e||"permission_required"===e||"aad_mismatch"===e?e:"read_failed"}function hc(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}(class extends fa{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||oc(String(s))!==oc(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(Hi(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):Yo("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(Qo(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=Ao,n=`vault-master:${e}`,s=`vault-identity:${this.tc.address}`;try{if(!this.masterKey){let s=await Wo(n);if(!s){if(!t)return ic({code:"VAULT_LOCKED",message:"Signer is required when no cached master signature exists"});s=Yo(await t.signMessage(r.masterMessage(e))),await zo(n,s)}this.masterKey=this.crypto.deriveKey(s,this.crypto.sha256(Yo(e)),Yo("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:tc(a),privateKey:new Uint8Array(0)};else{let e=await Wo(s);if(!e){if(!t)return this.encryptionIdentity=null,this._isUnlocked=!0,ai(void 0);e=Yo(await t.signMessage(r.identityMessage)),await zo(s,e)}const n=this.crypto.deriveKey(e,Yo("tinycloud-x25519"),Yo("encryption-identity"));this.encryptionIdentity=this.crypto.x25519FromSeed(n);try{const e=ec(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,ai(void 0)}catch(e){return this.masterKey=null,this.encryptionIdentity=null,ic({code:"STORAGE_ERROR",cause:Jo(e)})}});try{return await this.unlockInFlight}finally{this.unlockInFlight=null}}async clearCache(e){e?await Go(`vault-master:${e}`):await Go()}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 ic({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return ic({code:"VAULT_LOCKED",message:"Authentication required"});if(void 0!==r?.ifMatch){if(void 0!==r.ifNoneMatch)return ic({code:"STORAGE_ERROR",cause:new Error("ifMatch cannot be combined with ifNoneMatch")});if(!/^"[^"\s]+"$/.test(r.ifMatch))return ic({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={[xo]:"2",[So]:"tinycloud-network-envelope",[Uo]:i,...r?.metadata??{}},o=Yo(`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=Hi(c.error);return ic(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===si.KV_PRECONDITION_FAILED)return ic({code:"ALREADY_EXISTS",key:e,...void 0!==h.error.meta?{meta:h.error.meta}:{},cause:ac(h.error)});if(void 0!==r?.ifMatch){const t=function(e,t){const r=t.meta?.status,n=t.code===si.KV_PRECONDITION_FAILED?"ETAG_MISMATCH":t.code===si.KV_WRITE_FAILED&&400===r?"INVALID_ETAG":t.code===si.OUTCOME_UNKNOWN||t.code===si.KV_WRITE_FAILED&&"number"==typeof r&&uc.includes(r)||(t.code===si.NETWORK_ERROR||t.code===si.TIMEOUT)&&void 0===r&&!1!==t.meta?.requestMayHaveDispatched?"OUTCOME_UNKNOWN":t.code===si.NODE_BUSY||t.code===si.REQUEST_TIMEOUT?"NODE_BUSY":void 0;if(void 0!==n)return ic({code:n,key:e,message:t.message,...void 0!==t.meta?{meta:t.meta}:{},cause:ac(t)})}(e,h.error);if(void 0!==t)return t}return dc("Failed to store encrypted value",h.error)}return{ok:!0,data:void 0}}catch(e){const t=Hi(e);return ic(t||{code:"STORAGE_ERROR",cause:Jo(e)})}}async getNetworkEncrypted(e,t){if(!this.networkEncryption)return ic({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return ic({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=Hi(r.error);return ic(t||{code:"KEY_NOT_FOUND",key:e})}const n=rc(r.data),s="string"==typeof n?JSON.parse(n):n,i=cc(s,this.vaultConfig.spaceId,e,t);if("corrupt"===i)return ic({code:"DECRYPTION_FAILED",message:"envelope is malformed"});if("mismatch"===i)return ic({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=Hi(a.error);if(t)return ic(t);const{code:r,message:n,permissionHint:s}=a.error;return ic("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[Uo]??"application/json",u=o[Do]??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=Hi(e);return ic(t||{code:"STORAGE_ERROR",cause:Jo(e)})}}async readNetworkEncrypted(e,t){const r=await this.fetchNetworkEnvelope(e);if("fetched"!==r.status)return r;const{envelope:n,etag:s}=r,i=cc(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[Uo]??"application/json",i=e[Do]??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&&(!Ro.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.`);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:lc(a.status)};const{envelope:o,etag:c}=a,u=cc(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&&oc(String(o.networkId))===oc(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:lc(d.status)};let l,h,f;try{l=await this.namedKeys(),h=await l.encrypt(t,d.plaintext,{networkId:s.networkId,aad:Yo(i),metadata:o.metadata??{},ensureKey:!0})}catch(e){if(Hi(e))throw e;const{status:t}=e;return{status:"skipped",reason:401===t||403===t?"permission_required":"write_failed"}}try{if(!hc(await l.decrypt(h),d.plaintext))return{status:"skipped",reason:"verify_failed"}}catch(e){if(Hi(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(Hi(e))throw e;return{status:"skipped",reason:"write_failed"}}if(f.ok)return{status:"moved"};if(Hi(f.error))throw f.error;if(f.error.code!==si.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(Hi(e))throw e;return{status:"node_unreachable"}}if(!t.ok){if(Hi(t.error))throw t.error;const e=Zi(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||nc(t.error)?"NODE_NOT_RESPONDING"===t.error.code||"NETWORK_ERROR"===t.error.code||"TIMEOUT"===t.error.code||"ABORTED"===t.error.code?nc(t.error)?{status:"read_failed"}:{status:"node_unreachable"}:{status:"read_failed"}:{status:"not_found"}}try{const e=rc(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(Hi(e))throw e;return{status:"decrypt_failed"}}if(r.ok)return{status:"opened",plaintext:r.data};if(Hi(r.error))throw r.error;const n=Zi(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 ic({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"});if(!t.ok)return ic({code:"KEY_NOT_FOUND",key:e});const r=rc(t.data);return{ok:!0,data:("string"==typeof r?JSON.parse(r):r).metadata??{}}}catch(e){return ic({code:"STORAGE_ERROR",cause:Jo(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 ic({code:"STORAGE_ERROR",cause:new Error("ifNoneMatch is only supported by network-encrypted vaults")});if(void 0!==r?.ifMatch)return ic({code:"STORAGE_ERROR",cause:new Error("ifMatch is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return ic({code:"VAULT_LOCKED",message:"Vault must be unlocked before storing data"});if(!this.requireAuth())return ic({code:"VAULT_LOCKED",message:"Authentication required"});try{let n;n=t instanceof Uint8Array?t:r?.serialize?r.serialize(t):Yo("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=Xo(this.crypto.sha256(i)).slice(0,16),o=this.crypto.encrypt(i,n),c=this.crypto.encrypt(this.masterKey,i),u={[xo]:"1",[So]:"aes-256-gcm",[Do]:a,[Uo]:s,[Po]:"hkdf-sha256",[Lo]:this.vaultConfig.keyRotation??"per-write",...r?.metadata??{}},d=JSON.stringify({keyId:a,contentType:s,...u}),l=JSON.stringify({key:ec(c),metadata:d}),h=await this.tc.kv.put(`keys/${e}`,l);if(!h.ok)return dc("Failed to store key blob",h.error);const f=JSON.stringify({data:ec(o),metadata:u}),p=await this.tc.kv.put(`vault/${e}`,f);return p.ok?ai(void 0):dc("Failed to store encrypted value",p.error)}catch(e){return ic({code:"STORAGE_ERROR",cause:Jo(e)})}})}async get(e,t){return this.withTelemetry("get",e,async()=>{if(this.usesNetworkEncryption)return this.getNetworkEncrypted(e,t);if(!0===t?.expectAad)return ic({code:"STORAGE_ERROR",cause:new Error("expectAad is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return ic({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading data"});if(!this.requireAuth())return ic({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 ic({code:"KEY_NOT_FOUND",key:e});const n=tc(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 ic({code:"KEY_NOT_FOUND",key:e});const a=JSON.parse(i.data.data),o=tc(a.data),c=this.crypto.decrypt(s,o),u=a.metadata??{},d=u[Uo]??"application/json",l=u[Do]??"";let h;return h=t?.raw?c:t?.deserialize?t.deserialize(c):"application/json"===d?JSON.parse(Qo(c)):c,ai({value:h,metadata:u,keyId:l})}catch(e){return e instanceof Error&&e.message.includes("decryption")?ic({code:"DECRYPTION_FAILED",message:e.message}):ic({code:"STORAGE_ERROR",cause:Jo(e)})}})}async delete(e){return this.withTelemetry("delete",e,async()=>{if(!this.isUnlocked)return ic({code:"VAULT_LOCKED",message:"Vault must be unlocked before deleting data"});if(!this.requireAuth())return ic({code:"VAULT_LOCKED",message:"Authentication required"});try{if(this.usesNetworkEncryption){const t=await this.tc.kv.delete(`vault/${e}`);if(!t.ok){const r=Hi(t.error);return ic(r||{code:"KEY_NOT_FOUND",key:e})}return ai(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=Hi(t.error)??Hi(r.error);return ic(n||{code:"KEY_NOT_FOUND",key:e})}return ai(void 0)}catch(e){const t=Hi(e);return ic(t||{code:"STORAGE_ERROR",cause:Jo(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 ic({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing data"});if(!this.requireAuth())return ic({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=Hi(r.error);return ic(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 ai({keys:n,truncated:!0===r.data.truncated,...void 0===r.data.nextCursor?{}:{nextCursor:r.data.nextCursor}})}catch(e){const t=Hi(e);return ic(t||{code:"STORAGE_ERROR",cause:Jo(e)})}})}async head(e){return this.withTelemetry("head",e,async()=>{if(this.usesNetworkEncryption)return this.headNetworkEncrypted(e);if(!this._isUnlocked)return ic({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading metadata"});if(!this.requireAuth())return ic({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0});if(!t.ok)return ic({code:"KEY_NOT_FOUND",key:e});return ai(JSON.parse(t.data.data).metadata??{})}catch(e){return ic({code:"STORAGE_ERROR",cause:Jo(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 ic({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 ic({code:"VAULT_LOCKED",message:"Vault must be unlocked before granting access"});if(!this.requireAuth())return ic({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 ic({code:"KEY_NOT_FOUND",key:e});const a=tc(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,Yo("tinycloud-x25519"),Yo("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:ec(f),spaceId:this.vaultConfig.spaceId,metadata:{[Co]:"1",[Ko]:this.tc.did,...r?.metadata??{}}}),y=await this.tc.kv.put(`grants/${t}/${e}`,p);return y.ok?ai(void 0):dc("Failed to store grant",y.error)}catch(e){return ic({code:"STORAGE_ERROR",cause:Jo(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 ic({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 ic({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv.")});const n=this.networkEncryption;if(!n)return ic({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return ic({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=await e.get(`vault/${t}`,{raw:!0});if(!s.ok)return ic({code:"KEY_NOT_FOUND",key:t});const i=rc(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 ic({code:"DECRYPTION_FAILED",message:c.error.message});const u=a.metadata??{},d=u[Uo]??"application/json",l=u[Do]??a.encryptedSymmetricKeyHash.slice(0,16);return{ok:!0,data:{value:this.deserializeValue(c.data,d,r),metadata:u,keyId:l}}}catch(e){return ic({code:"STORAGE_ERROR",cause:Jo(e)})}}if(!this._isUnlocked||!this.masterKey||!this.encryptionIdentity)return ic({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading shared data"});if(!this.requireAuth())return ic({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=this.tc.did,s=r?.kv;if(!s)return ic({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 ic({code:"GRANT_NOT_FOUND",grantor:e,key:t});const a=tc(("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,Yo("tinycloud-x25519"),Yo("vault-grant")),l=this.crypto.decrypt(d,c),h=await s.get(`vault/${t}`,{raw:!0});if(!h.ok)return ic({code:"KEY_NOT_FOUND",key:t});const f="string"==typeof h.data?.data?JSON.parse(h.data.data):h.data?.data,p=tc(f.data),y=this.crypto.decrypt(l,p),g=f.metadata??{},m=g[Uo]??"application/json",v=g[Do]??"";let _;return _=r?.raw?y:r?.deserialize?r.deserialize(y):"application/json"===m?JSON.parse(Qo(y)):y,ai({value:_,metadata:g,keyId:v})}catch(e){return e instanceof Error&&e.message.includes("decryption")?ic({code:"DECRYPTION_FAILED",message:e.message}):ic({code:"STORAGE_ERROR",cause:Jo(e)})}})}async resolvePublicKey(e){try{const t=this.parseDID(e);if(!t)return ic({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:tc(n.data)}:ic({code:"PUBLIC_KEY_NOT_FOUND",did:e})}catch(t){return ic({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 ic({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing grants"});if(!this.requireAuth())return ic({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.list({prefix:"grants/",removePrefix:!0});if(!t.ok)return ic({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 ai(r)}catch(e){return ic({code:"STORAGE_ERROR",cause:Jo(e)})}})}async revoke(e,t){return this.withTelemetry("revoke",e,async()=>{if(this.usesNetworkEncryption)return ic({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 ic({code:"VAULT_LOCKED",message:"Vault must be unlocked before revoking access"});if(!this.requireAuth())return ic({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=Xo(this.crypto.sha256(a)).slice(0,16);let c;c=i.value instanceof Uint8Array?i.value:Yo(JSON.stringify(i.value));const u=this.crypto.encrypt(a,c),d=this.crypto.encrypt(this.masterKey,a),l={...i.metadata,[Do]:o},h=JSON.stringify({key:ec(d),metadata:JSON.stringify({keyId:o,...l})}),f=await this.tc.kv.put(`keys/${e}`,h);if(!f.ok)return dc("Failed to store rotated key blob",f.error);const p=JSON.stringify({data:ec(u),metadata:l}),y=await this.tc.kv.put(`vault/${e}`,p);if(!y.ok)return dc("Failed to store re-encrypted value",y.error);for(const t of n)(await this.reencrypt(e,t)).ok;return ai(void 0)}catch(e){return ic({code:"STORAGE_ERROR",cause:Jo(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 fc="tinycloud.encryption.decrypt/v1",pc="tinycloud.encryption.decrypt-result/v1";function yc(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 gc(e){return{...e,service:"encryption",message:yc(e)}}function mc(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function vc(e,t,r,n){let s;try{s=Bi(e.networkId)}catch(e){return{ok:!1,error:gc({code:"INVALID_NETWORK_ID",message:`descriptor networkId is malformed: ${e instanceof Error?e.message:String(e)}`})}}if(s.name!==n||!Mi(s.ownerDid,r))return{ok:!1,error:gc({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&&Mi(i,r)&&Mi(i,s.ownerDid)?e.name!==n?{ok:!1,error:gc({code:"INVALID_NETWORK_ID",message:"descriptor name does not match networkId name"})}:"string"!=typeof e.publicEncryptionKey||0===e.publicEncryptionKey.length?{ok:!1,error:gc({code:"INVALID_NETWORK_ID",message:"descriptor publicEncryptionKey must be a non-empty string"})}:{ok:!0,data:{...e,ownerDid:i}}:{ok:!1,error:gc({code:"INVALID_NETWORK_ID",message:"descriptor ownerDid does not match networkId ownerDid"})}}function _c(e){return"active"===e.state||"rotating"===e.state?{ok:!0,data:e}:{ok:!1,error:gc({code:"NETWORK_NOT_ACTIVE",state:e.state})}}var kc="x25519-hkdf-aes256gcm/v2",Ec=bo("TCW2"),wc=bo("tinycloud.encryption.key-wrap/v2");function bc(...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 Tc(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 Oc(e){if("string"!=typeof e)throw new Error("Invalid key wrap encoding");const t=wo(e);if(32!==t.length||Eo(t)!==e)throw new Error("Invalid key wrap encoding");return t}function Nc(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 Rc(e){if("network-key"!==e.purpose&&"receiver-key"!==e.purpose||"string"!=typeof e.networkId||"string"!=typeof e.keyPath||!Nc(e.networkId)||!Nc(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])=>!Nc(e)||"string"!=typeof t||!Nc(t)))throw new Error("Invalid key wrap context");if(""!==e.networkId){const t=qi(""===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&&Ec.every((t,r)=>e[r]===t)}function Ac(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!==kc||"hkdf-sha256"!==n.kdf||"aes-256-gcm"!==n.aead)throw new Error("Invalid v2 key wrap header");if(Rc(n),Oc(n.salt),Oc(n.ephemeralPublicKey),Oc(n.recipientPublicKey),!Tc(r,bo(mo({...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 xc(e,t){Rc(t);for(const r of["purpose","networkId","keyPath","keyVersion"])if(e[r]!==t[r])throw new Error("Key wrap context mismatch");if(mo(e.metadata)!==mo(t.metadata))throw new Error("Key wrap metadata mismatch")}function Sc(e,t,r=!1){if("x25519-aes256gcm/v1"!==t&&t!==kc)throw new Error("Unsupported key wrap algorithm");if(r&&t!==kc)throw new Error("V2 network key wrap required");if(Ic(e)!==(t===kc))throw new Error("Key wrap algorithm mismatch");t===kc&&Ac(e)}function Dc(e,t=!1){const r=wo(e.encryptedSymmetricKey);Sc(r,e.alg,t),e.alg===kc&&xc(Ac(r).header,{purpose:"network-key",networkId:e.networkId,keyPath:e.keyPath??"",keyVersion:e.keyVersion,metadata:e.metadata??{}})}function Uc(e){return{ok:!0,data:e}}function Pc(e){return{ok:!1,error:e}}function Lc(e){return gc("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 fa{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:gc({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 $i)return{ok:!1,error:gc({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=vc(s,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"node"}}:e}}catch(e){const t=Hi(e);return t?{ok:!1,error:gc(t)}:{ok:!1,error:gc({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(!Ki.test(e))throw new $i(`network name ${JSON.stringify(e)} must match ${Ki.source}`);return`.well-known/encryption/network/${e}`}(n));if(null!==s){const e=vc(s,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"well-known"}}:e}}catch(e){const t=Hi(e);if(t)return{ok:!1,error:gc(t)}}return{ok:!1,error:gc({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?Uc(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=_c(n.data);if(!s.ok)return s;const i=s.data,a=wo(i.publicEncryptionKey);return Uc(function(e,t){if(qi(void 0===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`).keyPath!==t.keyPath||t.keyPath?.endsWith("/"))throw new $i("keyPath must name an exact encryption key");const r=t.keyWrapV2?kc:"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(Rc(r),32!==e.length)throw new Error("Invalid recipient public key");const n=Kr(32),s=Bs.getPublicKey(n),i=Kr(32),a=bo(mo({...{...r,v:2,alg:kc,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(Ec),new DataView(o.buffer).setUint32(4,a.length);const c=bc(o,a),u=Kr(12);let d;try{const r=Bs.getSharedSecret(n,e);try{if(r.every(e=>0===e))throw new Error("Invalid key agreement");d=ti(ri,r,i,bc(wc,s,e),32)}finally{r.fill(0)}return bc(c,u,gr(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=To(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=Hi(e);return Pc(gc(t||{code:"TRANSPORT_ERROR",cause:mc(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:gc({code:"INVALID_ENVELOPE",message:"envelope must be an object"})};const n=t;if(1!==n.v)return{ok:!1,error:gc({code:"INVALID_ENVELOPE",message:`envelope.v must be 1 (got ${n.v})`})};try{if(void 0!==qi(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(qi(`${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:gc({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:gc({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:gc({code:"INVALID_ENVELOPE",message:"envelope.keyVersion must be an integer"})};if(To(e.sha256,n.encryptedSymmetricKey)!==n.encryptedSymmetricKeyHash)return{ok:!1,error:gc({code:"INVALID_ENVELOPE",message:"envelope.encryptedSymmetricKeyHash does not match canonical hash of encryptedSymmetricKey"})};try{Dc(n,r)}catch{return{ok:!1,error:gc({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 Pc(gc({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 Pc(Lc(t.error));i=t.data}const a=_c(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 Pc(gc({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 Pc(gc({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=To(this.crypto.sha256,u),l={type:fc,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:mo((n={crypto:this.crypto,body:l,receiverPublicKey:c.publicKey}).body),bodyHash:To(n.crypto.sha256,n.body),receiverPublicKeyHash:To(n.crypto.sha256,n.body.receiverPublicKey)},f=function(e){const t=void 0!==e.canonicalBody?ko(e.crypto.sha256(bo(e.canonicalBody))):To(e.crypto.sha256,e.body),r=To(e.crypto.sha256,e.body.receiverPublicKey);return{type:fc,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!==fc)return{ok:!1,error:gc({code:"INVALID_INPUT",message:`body.type must be ${fc}`})};if(t.facts.type!==fc)return{ok:!1,error:gc({code:"INVALID_INPUT",message:`facts.type must be ${fc}`})};if(t.facts.targetNode!==t.targetNode)return{ok:!1,error:gc({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:gc({code:"INVALID_INPUT",message:"body.targetNode must equal targetNode"})};if(t.facts.networkId!==t.networkId)return{ok:!1,error:gc({code:"INVALID_INPUT",message:"facts.networkId must equal networkId"})};if(t.body.networkId!==t.networkId)return{ok:!1,error:gc({code:"INVALID_INPUT",message:"body.networkId must equal networkId"})};if(t.facts.keyPath!==t.body.keyPath)return{ok:!1,error:gc({code:"INVALID_INPUT",message:"facts.keyPath must equal body.keyPath"})};if(t.facts.alg!==t.body.alg)return{ok:!1,error:gc({code:"INVALID_INPUT",message:"facts.alg must equal body.alg"})};if(t.facts.keyVersion!==t.body.keyVersion)return{ok:!1,error:gc({code:"INVALID_INPUT",message:"facts.keyVersion must equal body.keyVersion"})};if(t.facts.encryptedSymmetricKeyHash!==t.body.encryptedSymmetricKeyHash)return{ok:!1,error:gc({code:"INVALID_INPUT",message:"facts.encryptedSymmetricKeyHash must equal body.encryptedSymmetricKeyHash"})};if(t.facts.receiverPublicKeyHash!==t.body.receiverPublicKeyHash)return{ok:!1,error:gc({code:"INVALID_INPUT",message:"facts.receiverPublicKeyHash must equal body.receiverPublicKeyHash"})};try{if(void 0!==qi(t.networkId).keyPath)throw new $i("networkId must identify the network root")}catch(e){return{ok:!1,error:gc({code:"INVALID_NETWORK_ID",message:e instanceof Error?e.message:String(e)})}}try{if(qi(void 0===t.body.keyPath?t.body.networkId:`${t.body.networkId}/${t.body.keyPath}`).keyPath!==t.body.keyPath||t.body.keyPath?.endsWith("/"))throw new $i("keyPath must name an exact encryption key")}catch(e){return{ok:!1,error:gc({code:"INVALID_INPUT",message:e instanceof Error?e.message:String(e)})}}const r=mo(t.body);return To(e.sha256,t.body)!==t.facts.bodyHash?{ok:!1,error:gc({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:gc({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:gc({code:"INVALID_INPUT",message:"decrypt-invocation signer returned an empty authorization or invocationCid"})}}catch(e){return{ok:!1,error:gc({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:Pc(gc({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=Hi(t);return r?Pc(Lc(r)):t instanceof ni.DecryptTransportResponseError?Pc(gc(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"})):Pc(Lc({code:"TRANSPORT_ERROR",cause:mc(t)}))}const g=function(e){const{crypto:t,request:r,facts:n,invocationCid:s,requestBodyHash:i,response:a}=e;if(a.type!==pc)return{ok:!1,error:gc({code:"INVALID_RESPONSE",message:`response.type must be ${pc}`})};if(a.targetNode!==r.targetNode)return{ok:!1,error:gc({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(a.networkId!==r.networkId)return{ok:!1,error:gc({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(a.nodeId!==r.targetNode)return{ok:!1,error:gc({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if("x25519-aes256gcm/v1"!==a.alg&&a.alg!==kc)return{ok:!1,error:gc({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(a.keyVersion!==r.keyVersion)return{ok:!1,error:gc({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(a.encryptedSymmetricKeyHash!==r.encryptedSymmetricKeyHash)return{ok:!1,error:gc({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(a.receiverPublicKeyHash!==r.receiverPublicKeyHash)return{ok:!1,error:gc({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(a.invocationCid!==s)return{ok:!1,error:gc({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const o=ko(t.sha256(bo(`${s}${i}`)));if(a.requestHash!==o)return{ok:!1,error:gc({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:gc({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const c=(new TextEncoder).encode(function(e){const{nodeSignature:t,...r}=e;return mo(r)}(a)),u=wo(a.nodeSignature);return t.verifyNodeSignature(a.nodeId,c,u)?{ok:!0,data:a}:{ok:!1,error:gc({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=wo(r.wrappedKey);if(Sc(s,r.alg),r.alg===kc){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}=Ac(t);xc(n,r);const o=Bs.getPublicKey(e);if(!Tc(o,Oc(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 ti(ri,s,n,bc(wc,t,r),32)}finally{s.fill(0)}}(e,Oc(n.ephemeralPublicKey),o,Oc(n.salt));try{return gr(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){Dc(t);const n=wo(t.ciphertext),s=void 0!==t.aad?wo(t.aad):void 0;return e.authDecrypt(r,n,s)}(this.crypto,e,m);return Uc(v)}catch(e){const t=Hi(e);return Pc(t?Lc(t):gc({code:"INVALID_RESPONSE",message:"Local decryption failed"}))}var n}assertActive(){this._config.assertActive?.()}}).serviceName="encryption";var Cc=Me({kty:Ve(),crv:Ve().optional(),x:Ve().optional(),y:Ve().optional(),d:Ve().optional(),e:Ve().optional(),n:Ve().optional(),kid:Ve().optional(),alg:Ve().optional(),use:Ve().optional(),key_ops:Fe(Ve()).optional()}),Kc=We(["main","session","ingested"]),Vc=Me({id:Ve(),did:Ve(),type:Kc,jwk:Cc.optional(),priority:$e()}),$c=(Me({code:Ve(),message:Ve(),service:Ze("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>Ce(t=>t instanceof e,t))(Error).optional(),meta:He(Ve(),qe()).optional()}),{AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_EXPIRED:"AUTH_EXPIRED",NOT_INITIALIZED:"NOT_INITIALIZED",NOT_FOUND:"NOT_FOUND",REVOKED:"REVOKED",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",ABORTED:"ABORTED",INVALID_INPUT:"INVALID_INPUT",PERMISSION_DENIED:"PERMISSION_DENIED",CREATION_FAILED:"CREATION_FAILED",REVOCATION_FAILED:"REVOCATION_FAILED",INVALID_TOKEN:"INVALID_TOKEN",KV_SERVICE_UNAVAILABLE:"KV_SERVICE_UNAVAILABLE",DATA_FETCH_FAILED:"DATA_FETCH_FAILED",VALIDATION_ERROR:"VALIDATION_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",CHAIN_TOO_DEEP:"CHAIN_TOO_DEEP",INVALID_CURSOR:"INVALID_CURSOR"}),Bc=Me({cid:Ve(),delegateDID:Ve(),spaceId:Ve(),path:Ve(),actions:Fe(Ve()),caveats:Fe(He(Ve(),qe())).optional(),expiry:ze(),isRevoked:Be(),delegatorDID:Ve().optional(),createdAt:ze().optional(),parentCid:Ve().optional(),allowSubDelegation:Be().optional(),authHeader:Ve().optional()}),qc=Me({cid:Ve().min(1),lease_cid:Ve().min(1),generation:$e().int().nonnegative().safe(),previous_stamp_cid:Ve().min(1),new_end:$e().int().nonnegative().safe(),signed_bytes:Ve().min(1),signature:Ve().min(1)}).strict(),Fc=(Me({cid:Ve().min(1),status:We(["active","revoked","expired","unavailable","not_found"]),exists:Be(),active:Be(),revoked:Be(),expired:Be(),effective_expiry:$e().int().nullable().optional(),renewal_history:Fe(qc).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:c.custom,message:"delegation status flags do not match status"})}),Me({revoked:Ze(!0),cid:Ve().min(1)}).strict()),Mc=Me({resource:Ve().min(1),actions:Fe(Ve()),caveats:Fe(He(Ve(),qe()))}).strict(),jc=Ve().datetime({offset:!0}).transform(e=>new Date(e)),Hc=Me({cid:Ve().min(1),direction:We(["granted","received"]),delegatorDid:Ve().min(1),delegateDid:Ve().min(1),resources:Fe(Mc),parents:Fe(Ve()),issuedAt:jc.nullable(),notBefore:jc.nullable(),expiresAt:jc.nullable(),status:We(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:jc.nullable().optional(),revokedBy:Ve().optional(),revokedAncestorCid:Ve().optional()}).strict(),Zc=Me({schemaVersion:Ze(2),items:Fe(Hc),nextCursor:Ve().optional()}).strict(),Wc=(Me({direction:We(["granted","received","all","issued"]).optional(),status:We(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:Ve().trim().min(1).optional(),limit:$e().int().min(1).max(100).optional(),cursor:Ve().min(1).optional()}).strict(),Me({resource:Ve(),action:Ve(),keys:Fe(Vc),delegation:Bc,expiresAt:ze().optional()}),Me({cid:Ve(),spaceId:Ve(),delegator:Ve(),delegatee:Ve(),keyId:Ve().optional(),path:Ve(),actions:Fe(Ve()),expiry:ze().optional(),notBefore:ze().optional(),isRevoked:Be(),createdAt:ze(),parentCid:Ve().optional()}),Me({delegateDID:Ve(),path:Ve(),actions:Fe(Ve()),expiry:ze().optional(),disableSubDelegation:Be().optional(),statement:Ve().optional()}),Fe(Bc),Me({root:Bc,chain:Fe(Bc),leaf:Bc}),We(["granted","received","all"])),zc=(Me({direction:Wc.optional(),path:Ve().optional(),actions:Fe(Ve()).optional(),includeRevoked:Be().optional(),delegator:Ve().optional(),delegatee:Ve().optional(),validAt:ze().optional(),limit:$e().optional(),cursor:Ve().optional()}),We(["owned","delegated"])),Gc=(Me({id:Ve(),name:Ve().optional(),owner:Ve(),type:zc,permissions:Fe(Ve()).optional(),expiresAt:ze().optional()}),We(["base64","compact","ipfs"]));Me({token:Ve(),url:Ve(),delegation:Bc,schema:Gc,expiresAt:ze().optional(),description:Ve().optional()}),function(e){Me({data:e,delegation:Bc,spaceId:Ve(),path:Ve()})}(qe()),Me({persist:Be().optional(),validateChain:Be().optional(),keyName:Ve().optional(),createSessionKey:Be().optional(),priority:$e().optional()}),Me({includePlacement:Be().optional(),path:Ve().optional(),actions:Fe(Ve()).optional(),resources:Fe(Me({path:Ve(),actions:Fe(Ve()).optional()})).optional(),expiry:ze().optional(),schema:Gc.optional(),description:Ve().optional(),baseUrl:Ve().optional(),allowSubDelegation:Be().optional()}),Me({hosts:Fe(Ve()),accountSpaceId:Ve().min(1).optional(),session:qe().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),invoke:qe().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),invokeAny:qe().refine(e=>void 0===e||"function"==typeof e,{message:"Expected an invokeAny function or undefined"}).optional(),signOwnerRevocation:Ce().optional(),sessionInvocationSigner:Ce().optional(),resourceTransport:Ce().optional(),fetch:qe().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),Me({createSessionKey:qe().refine(e=>"function"==typeof e,{message:"Expected a function"}),getJWK:qe().refine(e=>"function"==typeof e,{message:"Expected a function"}),getDID:qe().refine(e=>"function"==typeof e,{message:"Expected a function"})}),Me({siwe:Ve(),signature:Ve(),version:$e(),cid:Ve().optional()});var Jc=Me({service:Ve(),space:Ve(),path:Ve(),actions:Fe(Ve()),caveats:Fe(He(Ve(),qe())).optional()}),Yc=(Me({session:qe().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:Ve(),spaceId:Ve(),abilities:He(Ve(),He(Ve(),Fe(Ve()))),expirationSecs:$e(),notBeforeSecs:$e().optional(),disableSubDelegation:Be().optional()}),Me({delegation:Ve(),cid:Ve(),delegateDID:Ve(),expiry:ze(),resources:Fe(Jc)}),{REVOKE:"tinycloud.delegation/revoke",STATUS:"tinycloud.delegation/status",LIST:"tinycloud.delegation/list",GET:"tinycloud.delegation/get",CHECK:"tinycloud.delegation/check"});function Qc(e,t,r,n){return{code:e,message:t,service:"delegation",cause:r,meta:n}}var Xc="delegation-issued-query-v1";async function eu(e){return(await e.text()).replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,200)}var tu="space not found";async function ru(e,t,r,n){const s=n??await eu(e),i={...r,status:e.status};return 401===e.status||403===e.status?Qc($c.PERMISSION_DENIED,""===s?"The node refused the request":s,void 0,i):400===e.status&&s.includes("invalid delegation query cursor")?Qc($c.INVALID_CURSOR,"The node rejected the page cursor; list again from the start",void 0,i):503===e.status?Qc($c.CHAIN_TOO_DEEP,"This delegation chain is too long for the node to check right now; try again later",void 0,{...i,retryable:!0}):Qc($c.NETWORK_ERROR,`${t}: ${e.status} - ${s}`,void 0,i)}var nu=class extends Error{};function su(){return{ok:!1,error:Qc($c.UNSUPPORTED_OPERATION,"This node doesn't support listing issued delegations yet",void 0,{feature:Xc})}}async function iu(e,t){const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:Qc($c.NOT_INITIALIZED,"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:Qc($c.INVALID_INPUT,"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`]:{[Yc.LIST]:[{}]}},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(Xc))throw new nu;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:Qc($c.NETWORK_ERROR,`Couldn't read the node's info: ${t.status}`,void 0,{status:t.status})};const r=await t.json();return e.state.issuedQuerySupported=Array.isArray(r.features)&&r.features.includes(Xc),{ok:!0,data:e.state.issuedQuerySupported}}(e);if(!t.ok)return t;if(!t.data)return su();i=await s(e.fetchFn,e.host)}if(!i.ok)return{ok:!1,error:await ru(i,"Failed to query issued delegations",{})};const a=Zc.safeParse(await i.json());return a.success?{ok:!0,data:a.data}:{ok:!1,error:Qc($c.INVALID_TOKEN,"Node returned an invalid delegation query response")}}catch(e){return Hi(e)?{ok:!1,error:{...ha("delegation",e),service:"delegation"}}:e instanceof nu?su():{ok:!1,error:Qc($c.NETWORK_ERROR,`Network error during delegation query: ${String(e)}`,e instanceof Error?e:void 0)}}}async function au(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:Qc($c.INVALID_INPUT,"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:Qc($c.INVALID_TOKEN,"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 ou(e,t){if(!t)return{ok:!1,error:Qc($c.INVALID_INPUT,"cid is required")};const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:Qc($c.NOT_INITIALIZED,"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}`]:{[Yc.REVOKE]:[{}]}},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 eu(s);return{ok:!1,error:e.toLowerCase()===tu?Qc($c.NOT_FOUND,`Delegation not found: ${t}`,void 0,{cid:t,status:404}):await ru(s,"Failed to revoke delegation",{cid:t},e)}}return{ok:!1,error:await ru(s,"Failed to revoke delegation",{cid:t})}}const i=Fc.safeParse(await s.json());return i.success&&i.data.cid===t?{ok:!0,data:i.data}:{ok:!1,error:Qc($c.REVOCATION_FAILED,"Node returned an invalid delegation revocation receipt",void 0,{cid:t})}}catch(e){return Hi(e)?{ok:!1,error:{...ha("delegation",e),service:"delegation"}}:{ok:!1,error:Qc($c.NETWORK_ERROR,`Network error during delegation revocation: ${String(e)}`,e instanceof Error?e:void 0)}}}module.exports=i})();
|
|
2
|
+
(()=>{"use strict";var e={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"}}}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n,s,i={};r.r(i),r.d(i,{queryAllIssued:()=>ou,queryIssued:()=>au,revokeIssued:()=>cu}),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}(n||(n={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(s||(s={}));const a=n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),o=e=>{switch(typeof e){case"undefined":return a.undefined;case"string":return a.string;case"number":return Number.isNaN(e)?a.nan:a.number;case"boolean":return a.boolean;case"function":return a.function;case"bigint":return a.bigint;case"symbol":return a.symbol;case"object":return Array.isArray(e)?a.array:null===e?a.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?a.promise:"undefined"!=typeof Map&&e instanceof Map?a.map:"undefined"!=typeof Set&&e instanceof Set?a.set:"undefined"!=typeof Date&&e instanceof Date?a.date:a.object;default:return a.unknown}},c=n.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class u extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},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 u))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,n.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()}}u.create=e=>new u(e);const d=(e,t)=>{let r;switch(e.code){case c.invalid_type:r=e.received===a.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case c.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,n.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:r=`Unrecognized key(s) in object: ${n.joinValues(e.keys,", ")}`;break;case c.invalid_union:r="Invalid input";break;case c.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${n.joinValues(e.options)}`;break;case c.invalid_enum_value:r=`Invalid enum value. Expected ${n.joinValues(e.options)}, received '${e.received}'`;break;case c.invalid_arguments:r="Invalid function arguments";break;case c.invalid_return_type:r="Invalid function return type";break;case c.invalid_date:r="Invalid date";break;case c.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:n.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case c.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case c.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case c.custom:r="Invalid input";break;case c.invalid_intersection_types:r="Intersection results could not be merged";break;case c.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case c.not_finite:r="Number must be finite";break;default:r=t.defaultError,n.assertNever(e)}return{message:r}};let l=d;var h;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(h||(h={}));function f(e,t){const r=l,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===d?void 0:d].filter(e=>!!e)});e.common.issues.push(n)}class p{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 y;"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 p.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 y;if("aborted"===s.status)return y;"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 y=Object.freeze({status:"aborted"}),g=e=>({status:"dirty",value:e}),m=e=>({status:"valid",value:e}),v=e=>"aborted"===e.status,_=e=>"dirty"===e.status,k=e=>"valid"===e.status,E=e=>"undefined"!=typeof Promise&&e instanceof Promise;class 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 b=(e,t)=>{if(k(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new u(e.common.issues);return this._error=t,this._error}}};function T(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 O{get description(){return this._def.description}_getType(e){return o(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new p,ctx:{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(E(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},n=this._parseSync({data:e,path:r.path,parent:r});return b(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return k(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>k(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(E(n)?n:Promise.resolve(n));return b(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:c.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:Ke.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Re.create(this,this._def)}nullable(){return Ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ce.create(this)}promise(){return Oe.create(this,this._def)}or(e){return le.create([this,e],this._def)}and(e){return ye.create(this,e,this._def)}transform(e){return new Ne({...T(this._def),schema:this,typeName:Ke.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Ae({...T(this._def),innerType:this,defaultValue:t,typeName:Ke.ZodDefault})}brand(){return new De({typeName:Ke.ZodBranded,type:this,...T(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new xe({...T(this._def),innerType:this,catchValue:t,typeName:Ke.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ue.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,R=/^[0-9a-z]+$/,I=/^[0-9A-HJKMNP-TV-Z]{26}$/i,A=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,x=/^[a-z0-9_-]{21}$/i,S=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,D=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,U=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let P;const 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])$/,C=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,K=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,V=/^(([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}(=)?))?$/,q="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",F=new RegExp(`^${q}$`);function M(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 j(e){return new RegExp(`^${M(e)}$`)}function H(e){let t=`${q}T${M(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Z(e,t){return!("v4"!==t&&t||!L.test(e))||!("v6"!==t&&t||!K.test(e))}function W(e,t){if(!S.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 z(e,t){return!("v4"!==t&&t||!C.test(e))||!("v6"!==t&&t||!V.test(e))}class G extends O{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==a.string){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.string,received:t.parsedType}),y}const t=new p;let r;for(const s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:c.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("max"===s.kind)e.data.length>s.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:c.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),t.dirty());else if("length"===s.kind){const n=e.data.length>s.value,i=e.data.length<s.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?f(r,{code:c.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&f(r,{code:c.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),t.dirty())}else if("email"===s.kind)U.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"email",code:c.invalid_string,message:s.message}),t.dirty());else if("emoji"===s.kind)P||(P=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),P.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"emoji",code:c.invalid_string,message:s.message}),t.dirty());else if("uuid"===s.kind)A.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"uuid",code:c.invalid_string,message:s.message}),t.dirty());else if("nanoid"===s.kind)x.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"nanoid",code:c.invalid_string,message:s.message}),t.dirty());else if("cuid"===s.kind)N.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid",code:c.invalid_string,message:s.message}),t.dirty());else if("cuid2"===s.kind)R.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cuid2",code:c.invalid_string,message:s.message}),t.dirty());else if("ulid"===s.kind)I.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ulid",code:c.invalid_string,message:s.message}),t.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),f(r,{validation:"url",code:c.invalid_string,message:s.message}),t.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"regex",code:c.invalid_string,message:s.message}),t.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),t.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:{startsWith:s.value},message:s.message}),t.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:{endsWith:s.value},message:s.message}),t.dirty()):"datetime"===s.kind?H(s).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:"datetime",message:s.message}),t.dirty()):"date"===s.kind?F.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:"date",message:s.message}),t.dirty()):"time"===s.kind?j(s).test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:c.invalid_string,validation:"time",message:s.message}),t.dirty()):"duration"===s.kind?D.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"duration",code:c.invalid_string,message:s.message}),t.dirty()):"ip"===s.kind?Z(e.data,s.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"ip",code:c.invalid_string,message:s.message}),t.dirty()):"jwt"===s.kind?W(e.data,s.alg)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"jwt",code:c.invalid_string,message:s.message}),t.dirty()):"cidr"===s.kind?z(e.data,s.version)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"cidr",code:c.invalid_string,message:s.message}),t.dirty()):"base64"===s.kind?$.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"base64",code:c.invalid_string,message:s.message}),t.dirty()):"base64url"===s.kind?B.test(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{validation:"base64url",code:c.invalid_string,message:s.message}),t.dirty()):n.assertNever(s);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:c.invalid_string,...h.errToObj(r)})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new G({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function J(e,t){const r=(e.toString().split(".")[1]||"").length,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}G.create=e=>new G({checks:[],typeName:Ke.ZodString,coerce:e?.coerce??!1,...T(e)});class Y extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==a.number){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.number,received:t.parsedType}),y}let t;const r=new p;for(const s of this._def.checks)"int"===s.kind?n.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:c.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"multipleOf"===s.kind?0!==J(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),f(t,{code:c.not_finite,message:s.message}),r.dirty()):n.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,r,n){return new Y({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:h.toString(n)}]})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&n.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Y.create=e=>new Y({checks:[],typeName:Ke.ZodNumber,coerce:e?.coerce||!1,...T(e)});class Q extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==a.bigint)return this._getInvalidInput(e);let t;const r=new p;for(const s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),f(t,{code:c.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):n.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.bigint,received:t.parsedType}),y}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,r,n){return new Q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:h.toString(n)}]})}_addCheck(e){return new Q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}Q.create=e=>new Q({checks:[],typeName:Ke.ZodBigInt,coerce:e?.coerce??!1,...T(e)});class X extends O{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==a.boolean){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.boolean,received:t.parsedType}),y}return m(e.data)}}X.create=e=>new X({typeName:Ke.ZodBoolean,coerce:e?.coerce||!1,...T(e)});class ee extends O{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==a.date){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.date,received:t.parsedType}),y}if(Number.isNaN(e.data.getTime()))return f(this._getOrReturnCtx(e),{code:c.invalid_date}),y;const t=new p;let r;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:c.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(r=this._getOrReturnCtx(e,r),f(r,{code:c.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):n.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ee.create=e=>new ee({checks:[],coerce:e?.coerce||!1,typeName:Ke.ZodDate,...T(e)});class te extends O{_parse(e){if(this._getType(e)!==a.symbol){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.symbol,received:t.parsedType}),y}return m(e.data)}}te.create=e=>new te({typeName:Ke.ZodSymbol,...T(e)});class re extends O{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.undefined,received:t.parsedType}),y}return m(e.data)}}re.create=e=>new re({typeName:Ke.ZodUndefined,...T(e)});class ne extends O{_parse(e){if(this._getType(e)!==a.null){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.null,received:t.parsedType}),y}return m(e.data)}}ne.create=e=>new ne({typeName:Ke.ZodNull,...T(e)});class se extends O{constructor(){super(...arguments),this._any=!0}_parse(e){return m(e.data)}}se.create=e=>new se({typeName:Ke.ZodAny,...T(e)});class ie extends O{constructor(){super(...arguments),this._unknown=!0}_parse(e){return m(e.data)}}ie.create=e=>new ie({typeName:Ke.ZodUnknown,...T(e)});class ae extends O{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.never,received:t.parsedType}),y}}ae.create=e=>new ae({typeName:Ke.ZodNever,...T(e)});class oe extends O{_parse(e){if(this._getType(e)!==a.undefined){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.void,received:t.parsedType}),y}return m(e.data)}}oe.create=e=>new oe({typeName:Ke.ZodVoid,...T(e)});class ce extends O{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==a.array)return f(t,{code:c.invalid_type,expected:a.array,received:t.parsedType}),y;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(f(t,{code:e?c.too_big:c.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&&(f(t,{code:c.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&&(f(t,{code:c.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=>p.mergeArray(r,e));const s=[...t.data].map((e,r)=>n.type._parseSync(new w(t,e,t.path,r)));return p.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new ce({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new ce({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new ce({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}}function ue(e){if(e instanceof de){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Re.create(ue(n))}return new de({...e._def,shape:()=>t})}return e instanceof ce?new ce({...e._def,type:ue(e.element)}):e instanceof Re?Re.create(ue(e.unwrap())):e instanceof Ie?Ie.create(ue(e.unwrap())):e instanceof ge?ge.create(e.items.map(e=>ue(e))):e}ce.create=(e,t)=>new ce({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ke.ZodArray,...T(t)});class de extends O{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=n.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==a.object){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.object,received:t.parsedType}),y}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof ae&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||i.push(e);const o=[];for(const e of s){const t=n[e],s=r.data[e];o.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 ae){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(f(r,{code:c.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const n=r.data[t];o.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 o){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>p.mergeObjectSync(t,e)):p.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new de({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:h.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ke.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const t={};for(const r of n.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const r of n.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new de({...this._def,shape:()=>t})}deepPartial(){return ue(this)}partial(e){const t={};for(const r of n.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const r of n.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Re;)e=e._def.innerType;t[r]=e}return new de({...this._def,shape:()=>t})}keyof(){return we(n.objectKeys(this.shape))}}de.create=(e,t)=>new de({shape:()=>e,unknownKeys:"strip",catchall:ae.create(),typeName:Ke.ZodObject,...T(t)}),de.strictCreate=(e,t)=>new de({shape:()=>e,unknownKeys:"strict",catchall:ae.create(),typeName:Ke.ZodObject,...T(t)}),de.lazycreate=(e,t)=>new de({shape:e,unknownKeys:"strip",catchall:ae.create(),typeName:Ke.ZodObject,...T(t)});class le extends O{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new u(e.ctx.common.issues));return f(t,{code:c.invalid_union,unionErrors:r}),y});{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 u(e));return f(t,{code:c.invalid_union,unionErrors:s}),y}}get options(){return this._def.options}}le.create=(e,t)=>new le({options:e,typeName:Ke.ZodUnion,...T(t)});const he=e=>e instanceof ke?he(e.schema):e instanceof Ne?he(e.innerType()):e instanceof Ee?[e.value]:e instanceof be?e.options:e instanceof Te?n.objectValues(e.enum):e instanceof Ae?he(e._def.innerType):e instanceof re?[void 0]:e instanceof ne?[null]:e instanceof Re?[void 0,...he(e.unwrap())]:e instanceof Ie?[null,...he(e.unwrap())]:e instanceof De||e instanceof Pe?he(e.unwrap()):e instanceof xe?he(e._def.innerType):[];class fe extends O{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.object)return f(t,{code:c.invalid_type,expected:a.object,received:t.parsedType}),y;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}):(f(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}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=he(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const 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 fe({typeName:Ke.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...T(r)})}}function pe(e,t){const r=o(e),s=o(t);if(e===t)return{valid:!0,data:e};if(r===a.object&&s===a.object){const r=n.objectKeys(t),s=n.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of s){const n=pe(e[r],t[r]);if(!n.valid)return{valid:!1};i[r]=n.data}return{valid:!0,data:i}}if(r===a.array&&s===a.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const s=pe(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===a.date&&s===a.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class ye extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(v(e)||v(n))return y;const s=pe(e.value,n.value);return s.valid?((_(e)||_(n))&&t.dirty(),{status:t.value,value:s.data}):(f(r,{code:c.invalid_intersection_types}),y)};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}))}}ye.create=(e,t,r)=>new ye({left:e,right:t,typeName:Ke.ZodIntersection,...T(r)});class ge extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.array)return f(r,{code:c.invalid_type,expected:a.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return f(r,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:c.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=>p.mergeArray(t,e)):p.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ge({...this._def,rest:e})}}ge.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ge({items:e,typeName:Ke.ZodTuple,rest:null,...T(t)})};class me extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.object)return f(r,{code:c.invalid_type,expected:a.object,received:r.parsedType}),y;const n=[],s=this._def.keyType,i=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new w(r,e,r.path,e)),value:i._parse(new w(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?p.mergeObjectAsync(t,n):p.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new me(t instanceof O?{keyType:e,valueType:t,typeName:Ke.ZodRecord,...T(r)}:{keyType:G.create(),valueType:e,typeName:Ke.ZodRecord,...T(t)})}}class ve extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.map)return f(r,{code:c.invalid_type,expected:a.map,received:r.parsedType}),y;const n=this._def.keyType,s=this._def.valueType,i=[...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 i){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return y;"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 i){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return y;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}ve.create=(e,t,r)=>new ve({valueType:t,keyType:e,typeName:Ke.ZodMap,...T(r)});class _e extends O{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==a.set)return f(r,{code:c.invalid_type,expected:a.set,received:r.parsedType}),y;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(f(r,{code:c.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&&(f(r,{code:c.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return y;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map((e,t)=>s._parse(new w(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new _e({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new _e({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}_e.create=(e,t)=>new _e({valueType:e,minSize:null,maxSize:null,typeName:Ke.ZodSet,...T(t)});class ke extends O{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ke.create=(e,t)=>new ke({getter:e,typeName:Ke.ZodLazy,...T(t)});class Ee extends O{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}}function we(e,t){return new be({values:e,typeName:Ke.ZodEnum,...T(t)})}Ee.create=(e,t)=>new Ee({value:e,typeName:Ke.ZodLiteral,...T(t)});class be extends O{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:n.joinValues(r),received:t.parsedType,code:c.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:c.invalid_enum_value,options:r}),y}return m(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return be.create(e,{...this._def,...t})}exclude(e,t=this._def){return be.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}be.create=we;class Te extends O{_parse(e){const t=n.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==a.string&&r.parsedType!==a.number){const e=n.objectValues(t);return f(r,{expected:n.joinValues(e),received:r.parsedType,code:c.invalid_type}),y}if(this._cache||(this._cache=new Set(n.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=n.objectValues(t);return f(r,{received:r.data,code:c.invalid_enum_value,options:e}),y}return m(e.data)}get enum(){return this._def.values}}Te.create=(e,t)=>new Te({values:e,typeName:Ke.ZodNativeEnum,...T(t)});class Oe extends O{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==a.promise&&!1===t.common.async)return f(t,{code:c.invalid_type,expected:a.promise,received:t.parsedType}),y;const r=t.parsedType===a.promise?t.data:Promise.resolve(t.data);return m(r.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Oe.create=(e,t)=>new Oe({type:e,typeName:Ke.ZodPromise,...T(t)});class Ne extends O{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ke.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:e=>{f(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===s.type){const e=s.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return y;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?y:"dirty"===n.status||"dirty"===t.value?g(n.value):n});{if("aborted"===t.value)return y;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?y:"dirty"===n.status||"dirty"===t.value?g(n.value):n}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?y:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?y:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===s.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!k(e))return y;const n=s.transform(e.value,i);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>k(e)?Promise.resolve(s.transform(e.value,i)).then(e=>({status:t.value,value:e})):y)}n.assertNever(s)}}Ne.create=(e,t,r)=>new Ne({schema:e,typeName:Ke.ZodEffects,effect:t,...T(r)}),Ne.createWithPreprocess=(e,t,r)=>new Ne({schema:t,effect:{type:"preprocess",transform:e},typeName:Ke.ZodEffects,...T(r)});class Re extends O{_parse(e){return this._getType(e)===a.undefined?m(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:Ke.ZodOptional,...T(t)});class Ie extends O{_parse(e){return this._getType(e)===a.null?m(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Ke.ZodNullable,...T(t)});class Ae extends O{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===a.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:Ke.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...T(t)});class xe extends O{_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 E(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new u(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new u(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}xe.create=(e,t)=>new xe({innerType:e,typeName:Ke.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...T(t)});class Se extends O{_parse(e){if(this._getType(e)!==a.nan){const t=this._getOrReturnCtx(e);return f(t,{code:c.invalid_type,expected:a.nan,received:t.parsedType}),y}return{status:"valid",value:e.data}}}Se.create=e=>new Se({typeName:Ke.ZodNaN,...T(e)}),Symbol("zod_brand");class De extends O{_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 Ue extends O{_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?y:"dirty"===e.status?(t.dirty(),g(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?y:"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 Ue({in:e,out:t,typeName:Ke.ZodPipeline})}}class Pe extends O{_parse(e){const t=this._def.innerType._parse(e),r=e=>(k(e)&&(e.value=Object.freeze(e.value)),e);return E(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function Le(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Ce(e,t={},r){return e?se.create().superRefine((n,s)=>{const i=e(n);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Le(t,n),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Le(t,n),i=e.fatal??r??!0;s.addIssue({code:"custom",...e,fatal:i})}}):se.create()}var Ke;Pe.create=(e,t)=>new Pe({innerType:e,typeName:Ke.ZodReadonly,...T(t)}),de.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Ke||(Ke={}));const Ve=G.create,$e=Y.create,Be=(Se.create,Q.create,X.create),qe=(ee.create,te.create,re.create,ne.create,se.create,ie.create),Fe=(ae.create,oe.create,ce.create),Me=de.create,je=(de.strictCreate,le.create,fe.create),He=(ye.create,ge.create,me.create),Ze=(ve.create,_e.create,ke.create,Ee.create),We=be.create,ze=(Te.create,Oe.create,Ne.create,Re.create,Ie.create,Ne.createWithPreprocess,Ue.create,e=>ee.create({...e,coerce:!0}));var Ge=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function Je(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function Ye(e){return e.slice(10,e.indexOf("/"))}function Qe(e){return e.slice(e.indexOf("/")+1)}function Xe(e){const t={};for(const r of Ge)Ye(r.urn)===e&&(t[Je(Qe(r.urn))]=r.urn);return t}var et=Xe("kv"),tt={...Xe("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},rt={...Xe("duckdb"),DESCRIBE:"tinycloud.duckdb/describe",EXECUTE:"tinycloud.duckdb/execute"},nt=Xe("capabilities"),st=(Xe("hooks"),Xe("encryption")),it=Xe("space"),at=Ge;["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 ot="applications",ct="account",ut="applications/",dt="secrets",lt="default",ht="public",ft="agents",pt="tinycloud.encryption",yt=st.NETWORK_CREATE,gt=[lt,ot,ct,dt,ht,ft],mt={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:lt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:lt,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:lt,path:"",actions:["read","write"]}]},vt={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:ot,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ot,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:ot,path:"",actions:["read","write"]}]},_t={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ct,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ct,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ct,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ct,path:"account",actions:["read","write","schema"]}]},kt={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:dt,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:dt,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:dt,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:dt,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:dt,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:dt,path:"",actions:["read"],skipPrefix:!0}]},Et={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:ht,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ht,path:"",actions:["get","list","metadata"]}]},wt={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:ft,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ft,path:"",actions:["get","put","del","list","metadata"]}]},bt={[lt]:mt,[ot]:vt,[ct]:_t,[dt]:kt,[ht]:Et,[ft]:wt};function Tt(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Ot(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?et.GET:"write"===r||"put"===r?et.PUT:"delete"===r||"del"===r?et.DEL:"list"===r?et.LIST:"metadata"===r?et.METADATA:void 0;if(void 0===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===pt;return[{service:e.service,space:e.service===pt?"encryption":e.space??r,path:Ot(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 Rt(e){const t=new Set(e.filter(e=>e.service!==pt).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:[nt.READ]}))])}function It(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(Tt),s=n.flatMap(e=>{const t=e.prefix??e.app_id,r=e.space??ot;return(e.permissions??[]).flatMap(e=>Nt(e,t,r))});r&&s.push(...At.map(e=>({...e,actions:[...e.actions]})));const i=new Map;for(const e of n){const t=i.get(e.app_id)??[];t.push(Tt(e)),i.set(e.app_id,t)}return{manifests:n,resources:Rt(s),delegationTargets:[],registryRecords:r?[...i.entries()].map(([e,t])=>({key:`${ut}${e}`,app_id:e,manifests:t})):[],expiryMs:6048e5,includePublicSpace:n.some(e=>e.includePublicSpace??!0)}}([bt[e]],{includeAccountRegistryPermissions:!1})}gt.map(e=>({name:e,manifest:bt[e],persistedAsApplication:e===dt}));var At=Object.freeze([{service:"tinycloud.kv",space:ct,path:ut,actions:[et.GET,et.PUT,et.LIST]},{service:"tinycloud.kv",space:ct,path:"spaces/",actions:[et.GET,et.PUT,et.LIST]},{service:"tinycloud.kv",space:ct,path:"system/bootstrap/complete",actions:[et.GET,et.PUT]},{service:"tinycloud.delegation",space:ct,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ct,path:"account",actions:[tt.READ,tt.WRITE,tt.SCHEMA]},{service:"tinycloud.capabilities",space:ct,path:"",actions:[nt.READ]}]),xt=It(lt),St={...xt,resources:[...xt.resources,...At.map(e=>({...e,actions:[...e.actions]}))]},Dt=Object.freeze(Object.fromEntries(gt.map(e=>[e,e===lt?St:It(e)]))),Ut=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[yt]}]);function Pt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Lt(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 Ct(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 Kt(e,t){Lt(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Vt(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(gt.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:Dt[e].resources,...e===ct?{rawAbilities:Ut}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[it.HOST]}]));const qt=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Ft(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=Zt(e)}return e}const Mt=(e,t)=>{function r(r,...n){if(Lt(r),!qt)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?Lt(t):Lt(t,e.nonceLength)}const s=e.tagLength;s&&void 0!==n[1]&&Lt(n[1]);const i=t(r,...n),a=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Lt(t)}};let o=!1;return{encrypt(e,t){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Lt(e),a(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(Lt(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 jt(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 Ht(e){return e.byteOffset%4==0}function Zt(e){return Uint8Array.from(e)}const Wt=16,zt=new Uint8Array(16),Gt=Vt(zt),Jt=(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)}),Yt=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;class Qt{constructor(e,t){this.blockLen=Wt,this.outputLen=Wt,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,Lt(e=Ft(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:Yt(n),s1:Yt(s),s2:Yt(i),s3:Yt(a)}),({s0:n,s1:s,s2:i,s3:a}=Jt(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){Ct(this),Lt(e=Ft(e));const t=Vt(e),r=Math.floor(e.length/Wt),n=e.length%Wt;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&&(zt.set(e.subarray(r*Wt)),this._updateBlock(Gt[0],Gt[1],Gt[2],Gt[3]),$t(Gt)),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){Ct(this),Kt(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:s}=this,i=Vt(e);return i[0]=t,i[1]=r,i[2]=n,i[3]=s,e}digest(){const e=new Uint8Array(Wt);return this.digestInto(e),this.destroy(),e}}class Xt extends Qt{constructor(e,t){Lt(e=Ft(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}(Zt(e));super(r,t),$t(r)}update(e){e=Ft(e),Ct(this);const t=Vt(e),r=e.length%Wt,n=Math.floor(e.length/Wt);for(let e=0;e<n;e++)this._updateBlock(Yt(t[4*e+3]),Yt(t[4*e+2]),Yt(t[4*e+1]),Yt(t[4*e+0]));return r&&(zt.set(e.subarray(n*Wt)),this._updateBlock(Yt(Gt[3]),Yt(Gt[2]),Yt(Gt[1]),Yt(Gt[0])),$t(Gt)),this}digestInto(e){Ct(this),Kt(e,this),this.finished=!0;const{s0:t,s1:r,s2:n,s3:s}=this,i=Vt(e);return i[0]=t,i[1]=r,i[2]=n,i[3]=s,e.reverse()}}function er(e){const t=(t,r)=>e(r,t.length).update(Ft(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 tr=er((e,t)=>new Qt(e,t)),rr=(er((e,t)=>new Xt(e,t)),16),nr=new Uint8Array(rr);function sr(e){return e<<1^283&-(e>>7)}function ir(e,t){let r=0;for(;t>0;t>>=1)r^=e&-(1&t),e=sr(e);return r}const ar=e=>e<<24|e>>>8,or=e=>e<<8|e>>>24;function cr(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(or),s=n.map(or),i=s.map(or),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 ur=cr((()=>{const e=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=sr(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=>ir(e,3)<<24|e<<16|e<<8|ir(e,2)),dr=(()=>{const e=new Uint8Array(16);for(let t=0,r=1;t<16;t++,r=sr(r))e[t]=r;return e})();function lr(e,t,r,n,s,i){return e[r<<8&65280|n>>>8&255]^t[s>>>8&65280|i>>>24&255]}function hr(e,t,r,n,s){return e[255&t|65280&r]|e[n>>>16&255|s>>>16&65280]<<16}function fr(e,t,r,n,s){const{sbox2:i,T01:a,T23:o}=ur;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++]^lr(a,o,t,r,n,s),u=e[c++]^lr(a,o,r,n,s,t),d=e[c++]^lr(a,o,n,s,t,r),l=e[c++]^lr(a,o,s,t,r,n);t=i,r=u,n=d,s=l}return{s0:e[c++]^hr(i,t,r,n,s),s1:e[c++]^hr(i,r,n,s,t),s2:e[c++]^hr(i,n,s,t,r),s3:e[c++]^hr(i,s,t,r,n)}}function pr(e,t,r,n,s){Lt(r,rr),Lt(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&&!Ht(t))throw new Error("invalid output, must be aligned");return t}(n.length,s);const i=r,a=Vt(i),o=Bt(i),c=Vt(n),u=Vt(s),d=t?0:12,l=n.length;let h=o.getUint32(d,t),{s0:f,s1:p,s2:y,s3:g}=fr(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}=fr(e,a[0],a[1],a[2],a[3]));const m=rr*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];$t(e)}var v;return s}function yr(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 jt(s,0,BigInt(t),r),jt(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 gr=Mt({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=yr(tr,!1,e,n,r);for(let e=0;e<t.length;e++)s[e]^=t[e];return s}function s(){const r=function(e){Lt(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}=ur,n=[];Ht(e)||n.push(e=Zt(e));const s=Vt(e),i=s.length,a=e=>hr(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(ar(t))^dr[e/i-1]:i>6&&e%i===4&&(t=a(t)),o[e]=o[e-i]^t}return $t(...n),o}(e),n=nr.slice(),s=nr.slice();if(pr(r,!1,s,s,n),12===t.length)s.set(t);else{const e=nr.slice();jt(Bt(e),8,BigInt(8*t.length),!1);const r=tr.create(n).update(t).update(e);r.digestInto(s),r.destroy()}return{xk:r,authKey:n,counter:s,tagMask:pr(r,!1,s,nr)}}return{encrypt(e){const{xk:t,authKey:r,counter:i,tagMask:a}=s(),o=new Uint8Array(e.length+16),c=[t,r,i,a];Ht(e)||c.push(e=Zt(e)),pr(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];Ht(e)||o.push(e=Zt(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=pr(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,vr={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 _r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function kr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Er(e,...t){if(!_r(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");kr(e.outputLen),kr(e.blockLen)}function br(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 Tr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Or(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Nr(e,t){return e<<32-t|e>>>t}const Rr=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Ir=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ar(e){if(Er(e),Rr)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Ir[e[r]];return t}function xr(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Sr(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Rr)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=xr(e.charCodeAt(s)),i=xr(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 Dr(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Ur(e){return"string"==typeof e&&(e=Dr(e)),Er(e),e}function Pr(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];Er(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 Lr{}function Cr(e){const t=t=>e().update(Ur(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Kr(e=32){if(vr&&"function"==typeof vr.getRandomValues)return vr.getRandomValues(new Uint8Array(e));if(vr&&"function"==typeof vr.randomBytes)return Uint8Array.from(vr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Vr(e,t,r){return e&t^~e&r}function $r(e,t,r){return e&t^e&r^t&r}class Br extends Lr{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=Or(this.buffer)}update(e){br(this),Er(e=Ur(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=Or(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){br(this),function(e,t){Er(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,Tr(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=Or(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 qr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Fr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Mr=BigInt(2**32-1),jr=BigInt(32);function Hr(e,t=!1){return t?{h:Number(e&Mr),l:Number(e>>jr&Mr)}:{h:0|Number(e>>jr&Mr),l:0|Number(e&Mr)}}const Zr=(e,t,r)=>e>>>r,Wr=(e,t,r)=>e<<32-r|t>>>r,zr=(e,t,r)=>e>>>r|t<<32-r,Gr=(e,t,r)=>e<<32-r|t>>>r,Jr=(e,t,r)=>e<<64-r|t>>>r-32,Yr=(e,t,r)=>e>>>r-32|t<<64-r;function Qr(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}}const Xr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),en=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,tn=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),rn=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,nn=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),sn=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,an=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]),on=new Uint32Array(64);class cn extends Br{constructor(e=32){super(64,e,8,!1),this.A=0|qr[0],this.B=0|qr[1],this.C=0|qr[2],this.D=0|qr[3],this.E=0|qr[4],this.F=0|qr[5],this.G=0|qr[6],this.H=0|qr[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)on[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=on[e-15],r=on[e-2],n=Nr(t,7)^Nr(t,18)^t>>>3,s=Nr(r,17)^Nr(r,19)^r>>>10;on[e]=s+on[e-7]+n+on[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))+Vr(a,o,c)+an[e]+on[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(){Tr(on)}destroy(){this.set(0,0,0,0,0,0,0,0),Tr(this.buffer)}}const un=(()=>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}=Hr(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))))(),dn=(()=>un[0])(),ln=(()=>un[1])(),hn=new Uint32Array(80),fn=new Uint32Array(80);class pn extends Br{constructor(e=64){super(128,e,16,!1),this.Ah=0|Fr[0],this.Al=0|Fr[1],this.Bh=0|Fr[2],this.Bl=0|Fr[3],this.Ch=0|Fr[4],this.Cl=0|Fr[5],this.Dh=0|Fr[6],this.Dl=0|Fr[7],this.Eh=0|Fr[8],this.El=0|Fr[9],this.Fh=0|Fr[10],this.Fl=0|Fr[11],this.Gh=0|Fr[12],this.Gl=0|Fr[13],this.Hh=0|Fr[14],this.Hl=0|Fr[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)hn[r]=e.getUint32(t),fn[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|hn[e-15],r=0|fn[e-15],n=zr(t,r,1)^zr(t,r,8)^Zr(t,0,7),s=Gr(t,r,1)^Gr(t,r,8)^Wr(t,r,7),i=0|hn[e-2],a=0|fn[e-2],o=zr(i,a,19)^Jr(i,a,61)^Zr(i,0,6),c=Gr(i,a,19)^Yr(i,a,61)^Wr(i,a,6),u=tn(s,c,fn[e-7],fn[e-16]),d=rn(u,n,o,hn[e-7],hn[e-16]);hn[e]=0|d,fn[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=zr(d,l,14)^zr(d,l,18)^Jr(d,l,41),v=Gr(d,l,14)^Gr(d,l,18)^Yr(d,l,41),_=d&h^~d&p,k=nn(m,v,l&f^~l&y,ln[e],fn[e]),E=sn(k,g,t,_,dn[e],hn[e]),w=0|k,b=zr(r,n,28)^Jr(r,n,34)^Jr(r,n,39),T=Gr(r,n,28)^Yr(r,n,34)^Yr(r,n,39),O=r&s^r&a^s&a,N=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}=Qr(0|c,0|u,0|E,0|w)),c=0|a,u=0|o,a=0|s,o=0|i,s=0|r,i=0|n;const R=Xr(w,T,N);r=en(R,E,b,O),n=0|R}({h:r,l:n}=Qr(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=Qr(0|this.Bh,0|this.Bl,0|s,0|i)),({h:a,l:o}=Qr(0|this.Ch,0|this.Cl,0|a,0|o)),({h:c,l:u}=Qr(0|this.Dh,0|this.Dl,0|c,0|u)),({h:d,l}=Qr(0|this.Eh,0|this.El,0|d,0|l)),({h,l:f}=Qr(0|this.Fh,0|this.Fl,0|h,0|f)),({h:p,l:y}=Qr(0|this.Gh,0|this.Gl,0|p,0|y)),({h:g,l:m}=Qr(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(){Tr(hn,fn)}destroy(){Tr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const yn=Cr(()=>new cn),gn=Cr(()=>new pn),mn=BigInt(0),vn=BigInt(1);function _n(e,t=""){if("boolean"!=typeof e)throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e);return e}function kn(e,t,r=""){const n=_r(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 En(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?mn:BigInt("0x"+e)}function wn(e){return Er(e),En(Ar(Uint8Array.from(e).reverse()))}function bn(e,t){return Sr(e.toString(16).padStart(2*t,"0"))}function Tn(e,t){return bn(e,t).reverse()}function On(e,t,r){let n;if("string"==typeof t)try{n=Sr(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!_r(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 Rn=e=>"bigint"==typeof e&&mn<=e;function In(e,t,r,n){if(!function(e,t,r){return Rn(e)&&Rn(t)&&Rn(r)&&t<=e&&e<r}(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}const An=e=>(vn<<BigInt(e))-vn;function xn(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 Sn=()=>{throw new Error("not implemented")};function Dn(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 Un=BigInt(0),Pn=BigInt(1),Ln=BigInt(2),Cn=BigInt(3),Kn=BigInt(4),Vn=BigInt(5),$n=BigInt(7),Bn=BigInt(8),qn=BigInt(9),Fn=BigInt(16);function Mn(e,t){const r=e%t;return r>=Un?r:t+r}function jn(e,t,r){let n=e;for(;t-- >Un;)n*=n,n%=r;return n}function Hn(e,t){if(e===Un)throw new Error("invert: expected non-zero number");if(t<=Un)throw new Error("invert: expected positive modulus, got "+t);let r=Mn(e,t),n=t,s=Un,i=Pn,a=Pn,o=Un;for(;r!==Un;){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 Mn(s,t)}function Zn(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Wn(e,t){const r=(e.ORDER+Pn)/Kn,n=e.pow(t,r);return Zn(e,n,t),n}function zn(e,t){const r=(e.ORDER-Vn)/Bn,n=e.mul(t,Ln),s=e.pow(n,r),i=e.mul(t,s),a=e.mul(e.mul(i,Ln),s),o=e.mul(i,e.sub(a,e.ONE));return Zn(e,o,t),o}function Gn(e){if(e<Cn)throw new Error("sqrt is not defined for small field");let t=e-Pn,r=0;for(;t%Ln===Un;)t/=Ln,r++;let n=Ln;const s=es(e);for(;1===Xn(s,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Wn;let i=s.pow(n,t);const a=(t+Pn)/Ln;return function(e,n){if(e.is0(n))return n;if(1!==Xn(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 Jn=(e,t)=>(Mn(e,t)&Pn)===Pn,Yn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Qn(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 Xn(e,t){const r=(e.ORDER-Pn)/Ln,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 es(e,t,r=!1,n={}){if(e<=Un)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&&kr(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:An(c),ZERO:Un,ONE:Pn,allowedLengths:a,create:t=>Mn(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Un<=t&&t<e},is0:e=>e===Un,isValidNot0:e=>!l.is0(e)&&l.isValid(e),isOdd:e=>(e&Pn)===Pn,neg:t=>Mn(-t,e),eql:(e,t)=>e===t,sqr:t=>Mn(t*t,e),add:(t,r)=>Mn(t+r,e),sub:(t,r)=>Mn(t-r,e),mul:(t,r)=>Mn(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Un)throw new Error("invalid exponent, negatives unsupported");if(r===Un)return e.ONE;if(r===Pn)return t;let n=e.ONE,s=t;for(;r>Un;)r&Pn&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Pn;return n}(l,e,t),div:(t,r)=>Mn(t*Hn(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Hn(t,e),sqrt:i||(t=>{return d||(d=(r=e)%Kn===Cn?Wn:r%Bn===Vn?zn:r%Fn===qn?function(e){const t=es(e),r=Gn(e),n=r(t,t.neg(t.ONE)),s=r(t,n),i=r(t,t.neg(n)),a=(e+$n)/Fn;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 Zn(e,f,t),f}}(r):Gn(r)),d(l,t);var r}),toBytes:e=>r?Tn(e,u):bn(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 En(Ar(e))}(t);if(o&&(s=Mn(s,e)),!n&&!l.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Qn(l,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(l)}const ts=BigInt(0),rs=BigInt(1);function ns(e,t){const r=t.negate();return e?r:t}function ss(e,t){const r=Qn(e.Fp,t.map(e=>e.Z));return t.map((t,n)=>e.fromAffine(t.toAffine(r[n])))}function is(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function as(e,t){is(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:An(e),maxNumber:r,shiftBy:BigInt(e)}}function os(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+=rs);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 cs=new WeakMap,us=new WeakMap;function ds(e){return us.get(e)||1}function ls(e){if(e!==ts)throw new Error("invalid wNAF")}class hs{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>ts;)t&rs&&(r=r.add(n)),n=n.double(),t>>=rs;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=as(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=as(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:a,offset:o,isZero:c,isNeg:u,isNegF:d,offsetF:l}=os(r,e,i);r=a,c?s=s.add(ns(d,t[l])):n=n.add(ns(u,t[o]))}return ls(r),{p:n,f:s}}wNAFUnsafe(e,t,r,n=this.ZERO){const s=as(e,this.bits);for(let e=0;e<s.windows&&r!==ts;e++){const{nextN:i,offset:a,isZero:o,isNeg:c}=os(r,e,s);if(r=i,!o){const e=t[a];n=n.add(c?e.negate():e)}}return ls(r),n}getPrecomputes(e,t,r){let n=cs.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),cs.set(t,n))),n}cached(e,t,r){const n=ds(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const s=ds(e);return 1===s?this._unsafeLadder(e,t,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),t,n)}createCache(e,t){is(t,this.bits),us.set(e,t),cs.delete(e)}hasCache(e){return 1!==ds(e)}}function fs(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>>=vn,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=An(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 ps(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){xn(e,Yn.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return es(e,{isLE:r})}const ys=BigInt(0),gs=BigInt(1),ms=BigInt(2),vs=BigInt(8);class _s{constructor(e){this.ep=e}static fromBytes(e){Sn()}static fromHex(e){Sn()}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 Ar(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 ks(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:es(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');xn(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||Kr,c=r.adjustScalarBytes||(e=>e),u=r.domain||((e,t,r)=>{if(_n(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=On("private key",e,r);const n=On("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,On("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 kn(e,g.seed,"seed")}const v={getExtendedPublicKey:l,randomSecretKey:m,isValidSecretKey:function(e){return _r(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(gs+r,gs-r):i.div(r-gs,r+gs);return i.toBytes(a)},toMontgomerySecret(e){const r=g.secretKey;kn(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=On("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 kn(Pr(d,a.toBytes(p)),g.signature,"result")},verify:function(t,r,i,a=p){const{context:o,zip215:c}=a,u=g.signature;t=On("signature",t,u),r=On("message",r),i=On("publicKey",i,g.publicKey),void 0!==c&&_n(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>ts))throw new Error(`CURVE.${e} must be positive bigint`)}const s=ps(t.p,r.Fp,n),i=ps(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;xn(t,{},{uvRatio:"function"});const o=ms<<BigInt(8*s.BYTES)-gs,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:ys}}});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 In("coordinate "+e,t,r?gs:ys,o),t}function l(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const h=Dn((e,t)=>{const{X:r,Y:s,Z:i}=e,a=e.is0();null==t&&(t=a?vs:n.inv(i));const o=c(r*t),u=c(s*t),d=n.mul(i,t);if(a)return{x:ys,y:gs};if(d!==gs)throw new Error("invZ was invalid");return{x:o,y:u}}),f=Dn(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,gs,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:s,d:a}=i;e=Nn(kn(e,r,"point")),_n(t,"zip215");const d=Nn(e),l=e[r-1];d[r-1]=-129&l;const h=wn(d),f=t?o:n.ORDER;In("point.y",h,ys,f);const y=c(h*h),g=c(y-gs),m=c(a*y-s);let{isValid:v,value:_}=u(g,m);if(!v)throw new Error("bad point: invalid y coordinate");const k=(_&gs)===gs,E=!!(128&l);if(!t&&_===ys&&E)throw new Error("bad point: x=0 and x_0=1");return E!==k&&(_=c(-_)),p.fromAffine({x:_,y:h})}static fromHex(e,t=!1){return p.fromBytes(On("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,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,E=v+m,w=c(g-t*y),b=c(_*k),T=c(E*w),O=c(_*w),N=c(k*E);return new p(b,T,N,O)}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=>ss(p,e));return ss(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===ys?p.ZERO:this.is0()||e===gs?this:y.unsafe(this,e,e=>ss(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===gs?this:this.multiplyUnsafe(a)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&gs?128:0,r}toHex(){return Ar(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 ss(p,e)}static msm(e,t){return fs(p,s,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(i.Gx,i.Gy,gs,c(i.Gx*i.Gy)),p.ZERO=new p(ys,gs,gs,ys),p.Fp=n,p.Fn=s;const y=new hs(p,s.BITS);return p.BASE.precompute(8),p}(t,r),n,s))}Dr("HashToScalar-");const Es=BigInt(0),ws=BigInt(1),bs=BigInt(2);const Ts=BigInt(0),Os=BigInt(1),Ns=BigInt(2),Rs=BigInt(3),Is=BigInt(5),As=BigInt(8),xs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ss=(()=>({p:xs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:As,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ds(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),i=xs,a=e*e%i*e%i,o=jn(a,Ns,i)*a%i,c=jn(o,Os,i)*e%i,u=jn(c,Is,i)*c%i,d=jn(u,t,i)*u%i,l=jn(d,r,i)*d%i,h=jn(l,n,i)*l%i,f=jn(h,s,i)*h%i,p=jn(f,s,i)*h%i,y=jn(p,t,i)*u%i;return{pow_p_5_8:jn(y,Ns,i)*e%i,b2:a}}function Us(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ps=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ls(e,t){const r=xs,n=Mn(t*t*t,r),s=Mn(n*n*t,r);let i=Mn(e*n*Ds(e*s).pow_p_5_8,r);const a=Mn(t*i*i,r),o=i,c=Mn(i*Ps,r),u=a===e,d=a===Mn(-e,r),l=a===Mn(-e*Ps,r);return u&&(i=o),(d||l)&&(i=c),Jn(i,r)&&(i=Mn(-i,r)),{isValid:u||d,value:i}}const Cs=(()=>es(Ss.p,{isLE:!0}))(),Ks=(()=>es(Ss.n,{isLE:!0}))(),Vs=(()=>({...Ss,Fp:Cs,hash:gn,adjustScalarBytes:Us,uvRatio:Ls}))(),$s=(()=>ks(Vs))(),Bs=(()=>{const e=Cs.ORDER;return function(e){const t=(xn(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||Kr,d=c?255:448,l=c?32:56,h=c?BigInt(9):BigInt(5),f=c?BigInt(121665):BigInt(39081),p=c?bs**BigInt(254):bs**BigInt(447),y=c?BigInt(8)*bs**BigInt(251)-ws:BigInt(4)*bs**BigInt(445)-ws,g=p+y+ws,m=e=>Mn(e,n),v=_(h);function _(e){return Tn(m(e),l)}function k(e,t){const r=function(e,t){In("u",e,Es,n),In("scalar",t,p,g);const r=t,s=e;let i=ws,o=Es,c=e,u=ws,l=Es;for(let e=BigInt(d-1);e>=Es;e--){const t=r>>e&ws;l^=t,({x_2:i,x_3:c}=w(l,i,c)),({x_2:o,x_3:u}=w(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}=w(l,i,c)),({x_2:o,x_3:u}=w(l,o,u));const h=a(o);return m(i*h)}(function(e){const t=On("u coordinate",e,l);return c&&(t[31]&=127),m(wn(t))}(t),function(e){return wn(i(On("scalar",e,l)))}(e));if(r===Es)throw new Error("invalid private or public key received");return _(r)}function E(e){return k(e,v)}function w(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))=>(Er(e,b.seed),e);return{keygen:function(e){const t=T(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>k(e,t),getPublicKey:e=>E(e),scalarMult:k,scalarMultBase:E,utils:{randomSecretKey:T,randomPrivateKey:T},GuBytes:v.slice(),lengths:b}}({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:r,b2:n}=Ds(t);return Mn(jn(r,Rs,e)*n,e)},adjustScalarBytes:Us})})(),qs=Ps,Fs=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ms=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),js=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Hs=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Zs=e=>Ls(Os,e),Ws=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),zs=e=>$s.Point.Fp.create(wn(e)&Ws);function Gs(e){const{d:t}=Ss,r=xs,n=e=>Cs.create(e),s=n(qs*e*e),i=n((s+Os)*js);let a=BigInt(-1);const o=n((a-t*s)*n(s+t));let{isValid:c,value:u}=Ls(i,o),d=n(u*e);Jn(d,r)||(d=n(-d)),c||(u=d),c||(a=s);const l=n(a*(s-Os)*Hs-o),h=u*u,f=n((u+u)*o),p=n(l*Fs),y=n(Os-h),g=n(Os+h);return new $s.Point(n(f*g),n(y*p),n(p*g),n(f*y))}class Js extends _s{constructor(e){super(e)}static fromAffine(e){return new Js($s.Point.fromAffine(e))}assertSame(e){if(!(e instanceof Js))throw new Error("RistrettoPoint expected")}init(e){return new Js(e)}static hashToCurve(e){return function(e){Er(e,64);const t=Gs(zs(e.subarray(0,32))),r=Gs(zs(e.subarray(32,64)));return new Js(t.add(r))}(On("ristrettoHash",e,64))}static fromBytes(e){Er(e,32);const{a:t,d:r}=Ss,n=xs,s=e=>Cs.create(e),i=zs(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}(Cs.toBytes(i),e)||Jn(i,n))throw new Error("invalid ristretto255 encoding 1");const a=s(i*i),o=s(Os+t*a),c=s(Os-t*a),u=s(o*o),d=s(c*c),l=s(t*r*u-d),{isValid:h,value:f}=Zs(s(l*d)),p=s(f*c),y=s(f*p*l);let g=s((i+i)*p);Jn(g,n)&&(g=s(-g));const m=s(o*y),v=s(g*m);if(!h||Jn(v,n)||m===Ts)throw new Error("invalid ristretto255 encoding 2");return new Js(new $s.Point(g,m,Os,v))}static fromHex(e){return Js.fromBytes(On("ristrettoHex",e,32))}static msm(e,t){return fs(Js,$s.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep;const s=xs,i=e=>Cs.create(e),a=i(i(r+t)*i(r-t)),o=i(e*t),c=i(o*o),{value:u}=Zs(i(a*c)),d=i(u*a),l=i(u*o),h=i(d*l*n);let f;if(Jn(n*h,s)){let r=i(t*qs),n=i(e*qs);e=r,t=n,f=i(d*Ms)}else f=l;Jn(e*h,s)&&(t=i(-t));let p=i((r-t)*f);return Jn(p,s)&&(p=i(-p)),Cs.toBytes(p)}equals(e){this.assertSame(e);const{X:t,Y:r}=this.ep,{X:n,Y:s}=e.ep,i=e=>Cs.create(e),a=i(t*s)===i(r*n),o=i(r*s)===i(t*n);return a||o}is0(){return this.equals(Js.ZERO)}}Js.BASE=(()=>new Js($s.Point.BASE))(),Js.ZERO=(()=>new Js($s.Point.ZERO))(),Js.Fp=(()=>Cs)(),Js.Fn=(()=>Ks)();class Ys extends Lr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,wr(e);const r=Ur(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),Tr(s)}update(e){return br(this),this.iHash.update(e),this}digestInto(e){br(this),Er(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 Qs=(e,t,r)=>new Ys(e,t).update(r).digest();Qs.create=(e,t)=>new Ys(e,t);const Xs=Uint8Array.from([0]),ei=Uint8Array.of(),ti=(e,t,r,n,s)=>function(e,t,r,n=32){wr(e),kr(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=ei);const a=new Uint8Array(i*s),o=Qs.create(e,t),c=o._cloneInto(),u=new Uint8Array(o.outputLen);for(let e=0;e<i;e++)Xs[0]=e+1,c.update(0===e?ei:u).update(r).update(Xs).digestInto(u),a.set(u,s*e),o._cloneInto(c);return o.destroy(),c.destroy(),Tr(u,Xs),a.slice(0,n)}(e,function(e,t,r){return wr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Qs(e,Ur(r),Ur(t))}(e,t,r),n,s),ri=yn;var ni=r(4290),si={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"},ii=(si.NODE_BUSY,si.REQUEST_TIMEOUT,"telemetry.span");function ai(e){return{ok:!0,data:e}}function oi(e){return{ok:!1,error:e}}function ci(e,t,r,n){return{code:e,message:t,service:r,cause:n?.cause,meta:n?.meta}}var ui="[REDACTED]",di=new Set(["duration","durationMs","endedAt","startedAt","status","timestamp","latencyMs","stalenessMs","count","changes","deleted","fetched","pages","lagMs","pendingCleared","partitions","remaining","expiryMs"]),li=new Set(["authenticated","ok","persisted","purgePending"]),hi={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 fi(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function pi(e,t){try{return e[t]}catch{return ui}}function yi(e){if(null==e)return e;if("object"!=typeof e)return ui;try{if(function(e){try{return Array.isArray(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}catch{return!0}}(e))return ui;const t={};for(const r of di){const n=fi(pi(e,r));void 0!==n&&(t[r]=n)}for(const r of li){const n=pi(e,r);"boolean"==typeof n&&(t[r]=n)}for(const[r,n]of Object.entries(hi)){const s=pi(e,r);"string"==typeof s&&n.includes(s)&&(t[r]=s)}void 0!==pi(e,"url")&&(t.url=ui);const r=pi(e,"error");return void 0!==r&&(t.error=function(e){if("object"!=typeof e||null===e)return{};const t=fi(pi(e,"status"));return void 0!==t&&t>=100&&t<=599?{status:t}:{}}(r)),t}catch{return ui}}var gi="TinyCloud_debug";function mi(){return globalThis}function vi(){const e=globalThis.performance?.now?.bind(globalThis.performance);return"function"==typeof e?e():Date.now()}function _i(e){return!0===e||"true"===e||"1"===e}function ki(){const e=globalThis.process;return e?.env?.[gi]}function Ei(){if(mi().window===globalThis)try{return globalThis.localStorage}catch{return}}function wi(e){const t=Ei();if(t)try{e?t.setItem(gi,"true"):t.removeItem(gi)}catch{}}var bi=new class{constructor(){this.enabled=_i(mi()[gi])||_i(function(){const e=Ei();if(e)try{return e.getItem(gi)}catch{return}}())||_i(ki()),this.sequence=0,this.events=[],this.maxEvents=1e3}isEnabled(){return this.enabled||_i(mi()[gi])||_i(ki())}enable(e={}){this.enabled=!0,mi()[gi]=!0,!1!==e.persist&&wi(!0),this.log("debug.enabled",{persisted:!1!==e.persist})}disable(e={}){this.log("debug.disabled",{persisted:!1!==e.persist}),this.enabled=!1,mi()[gi]=!1,!1!==e.persist&&wi(!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=vi();return this.log(`${e}.start`,t),{stop:t=>{const n=vi();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:yi(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 Ti(e){return bi.enable(e),bi}function Oi(e){return bi.disable(e),bi}function Ni(){return bi.getLogs()}function Ri(){bi.clear()}!function(){const e=mi();e.TinyCloudDebug=bi,e.enableTinyCloudDebug=Ti,e.disableTinyCloudDebug=Oi,e.getTinyCloudDebugLogs=Ni,e.clearTinyCloudDebugLogs=Ri}();var Ii=Me({code:Ve(),message:Ve(),service:Ve(),cause:qe().optional(),meta:Me({}).passthrough().optional()});function Ai(e,t=Ii){return je("ok",[Me({ok:Ze(!0),data:e}),Me({ok:Ze(!1),error:t})])}Ai(qe(),Ii);var xi,Si=Me({etag:Ve().optional(),contentType:Ve().optional(),lastModified:Ve().optional(),contentLength:$e().optional()});function Di(e){try{return JSON.parse(e)}catch{return{}}}function Ui(e,t,r,n,s){return s.message?Li(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} - ${Li(n)}`;var i}function Pi(e,t,r){const n={status:e,statusText:t},s=Li(r);return s&&(n.responseSnippet=s.slice(0,300)),n}function Li(e){const t=e.replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,500)}...`:t}xi=qe(),Me({data:xi,headers:Si}),Ai(Me({keys:Fe(Ve()),truncated:Be().optional(),nextCursor:Ve().optional()})),Me({service:Ve(),action:Ve(),span:Ve().optional(),key:Ve().optional(),timestamp:$e()}),Me({service:Ve(),action:Ve(),span:Ve().optional(),ok:Be(),duration:$e(),durationMs:$e().optional(),status:$e().optional()}),Me({service:Ve(),span:Ve().optional(),error:Ii}),Me({service:Ve(),attempt:$e().int().positive(),maxAttempts:$e().int().positive(),error:Ii}),Me({span:Ve(),ok:Be(),durationMs:$e(),service:Ve().optional(),action:Ve().optional(),status:$e().optional(),error:Ii.optional()}),Me({maxAttempts:$e().int().positive(),backoff:We(["none","linear","exponential"]),baseDelayMs:$e().nonnegative(),maxDelayMs:$e().nonnegative(),retryableErrors:Fe(Ve()),maxTotalMs:$e().positive().optional()}),Me({delegationHeader:Me({Authorization:Ve()}),delegationCid:Ve(),spaceId:Ve(),verificationMethod:Ve(),jwk:Me({}).passthrough()});var Ci="urn:tinycloud:encryption:",Ki=/^[a-z0-9][a-z0-9-]*$/,Vi=/^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/,$i=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Bi(e){if("string"!=typeof e||0===e.length)throw new $i("networkId must be a non-empty string");if(!e.startsWith(Ci))throw new $i(`networkId must start with ${Ci} (got ${JSON.stringify(e)})`);const t=e.slice(25),r=t.lastIndexOf(":");if(r<=0||r===t.length-1)throw new $i(`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 $i(`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 $i(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(n)})`);if(!Ki.test(s))throw new $i(`networkId name ${JSON.stringify(s)} must match ${Ki.source}`);return{networkId:e,ownerDid:n,name:s}}function qi(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 $i(`encryption resource has an invalid keyPath (got ${JSON.stringify(e)})`);return{...i,keyPath:a}}function Fi(e){const t=e.match(Vi);return t?{chainId:t[1],address:t[2].toLowerCase()}:null}function Mi(e,t){const r=Fi(e),n=Fi(t);return r&&n?r.chainId===n.chainId&&r.address===n.address:e===t}Error,Error,Error,Error;var ji={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 Hi(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(ji,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 Zi(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 Wi(e){return{code:si.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=si.REQUEST_TIMEOUT;else{if(500!==r.status||"outcome_unknown"!==i)return;o=si.OUTCOME_UNKNOWN}else o=si.NODE_BUSY;const c=o!==si.OUTCOME_UNKNOWN,u=r.headers.get("retry-after")?.trim();return ci(o,t,e,{meta:{...Pi(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 Gi=class extends Error{constructor(e){super(`Request timed out after ${e}ms.`),this.name="TimeoutError",this.timeoutMs=e}};function Ji(e){return e instanceof Gi||e instanceof Error&&"TimeoutError"===e.name&&"number"==typeof e.timeoutMs}function Yi(e,t,r){return void 0===t?{code:si.TIMEOUT,message:"Request timed out.",service:e,...void 0===r?{}:{cause:r}}:{code:si.TIMEOUT,message:`Request timed out after ${t}ms.`,service:e,...void 0===r?{}:{cause:r},meta:{timeoutMs:t}}}function Qi(e){const t=e.match(/^Unauthorized Action:\s*(.+?)\s*\/\s*(tinycloud\.\S+)$/m);return t?{resource:t[1].trim(),action:t[2].trim()}:{}}var Xi=new Set(at.map(({urn:e})=>e).filter(e=>!e.endsWith("/*"))),ea=new Set(at.map(({service:e})=>e.slice(10)));function ta(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||!ea.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&&ea.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 ra(e){const t=ia(e);if("unauthenticated"!==t&&"forbidden"!==t)return;const r=new Set;let n=e;for(let e=0;e<na&&"object"==typeof n&&null!==n&&!r.has(n);e+=1){r.add(n);const e=n,t=sa(e),s=e.meta;if((401===t||403===t||void 0===t&&e.code===si.AUTH_UNAUTHORIZED)&&"object"==typeof s&&null!==s&&!Array.isArray(s)){const t=s,{resource:r,requiredAction:n}=t;if("string"==typeof n&&Xi.has(n)){const s=n.slice(10,n.indexOf("/")),i=void 0===e.service?t.service:e.service;if(ta(r,s,n)&&(void 0===i||i===s||i===`tinycloud.${s}`))return{resource:r,requiredAction:n}}}n=e.cause}}var na=8;function sa(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 ia(e){const t=new Set;let r=!1,n=e;for(let e=0;e<na&&"object"==typeof n&&null!==n&&!t.has(n);e+=1){t.add(n);const e=n,s=sa(e);if(401===s)return"unauthenticated";if(403===s)return"forbidden";if(void 0!==s)return"other";e.code===si.AUTH_UNAUTHORIZED&&(r=!0),n=e.cause}return r?"forbidden":void 0}function aa(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 oa={storage_quota_exceeded:!0,storage_limit_reached:!0};function ca(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=0}function ua(e){if("object"!=typeof e||null===e)return;const{usedBytes:t,limitBytes:r}=e;return ca(t)&&ca(r)?{usedBytes:t,limitBytes:r}:void 0}function da(e){let t;try{t=JSON.parse(e)}catch{return aa(e)}if("object"!=typeof t||null===t)return;const r=t,n="string"==typeof r.message?r.message:"",s=ua(r.space)??aa(n),i="string"==typeof r.error&&!0===oa[r.error];if(!s&&!i)return;const a={...s},o=ua(r.account);if(o){const e=r.account.plan;a.account="string"==typeof e&&""!==e?{...o,plan:e}:o}return a}function la(e,t,r,n){const s={...r,...da(n)};return 402===t?function(e,t,r){return{code:si.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:si.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 ha(e,t,r=si.NETWORK_ERROR){const n=Hi(t);return n?{...n,service:e}:t instanceof Error?Ji(t)?Yi(e,t.timeoutMs,t):"AbortError"===t.name?function(e){return{code:si.ABORTED,message:"Request was aborted.",service:e}}(e):"TimeoutError"===t.name||t.message.toLowerCase().includes("timeout")?Yi(e):{code:r,message:t.message,service:e,cause:t}:{code:r,message:String(t),service:e}}var fa=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(ii,{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 Gi(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=ha(this.getServiceName(),t);return this.emitResponse(e,!1,n),this.emitError(r,e),oi(r)}}},pa=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?ai({...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 oi(ci(si.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?ai({...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?ai({...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)}},ya="tinycloud.kv/get",ga="tinycloud.kv/put",ma="tinycloud.kv/list",va="tinycloud.kv/del",_a="tinycloud.kv/metadata",ka="tinycloud.kv/sync";function Ea(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var wa=new TextEncoder,ba=/^(?:Invalid invocation: )?delegation-(?:(revoked): [A-Za-z0-9]+|(ancestor-revoked): ancestor=[A-Za-z0-9]+ invoked=[A-Za-z0-9]+)$/,Ta=new Set(["delegation_revoked","parent_revoked","ancestor_revoked"]);function Oa(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function Na(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 fa{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||da(t)))return oi(la("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)?oi(ci(si.KV_NOT_FOUND,`KV ${e.status} - ${r}`,"kv",{meta:{status:e.status,statusText:e.statusText}})):oi(ci(si.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=wa.encode(e),n=wa.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 oi(Wi("kv"));if(0===e.length)return ai({results:[],count:0});if(e.length>100)return oi(ci(si.INVALID_INPUT,"KV batch reads accept at most 100 keys","kv"));if(1===e.length){const n=e[0];return ai({results:[{key:n,result:t===ya?await this.get(n,r):await this.head(n,r)}],count:1})}if(!this.context.invokeAny)return oi(ci(si.INVALID_INPUT,"KV batch reads require SDK runtime support for multi-resource invocations","kv"));const n=t===ya?r:void 0;if(void 0!==n?.maxResponseBytes&&(!Number.isSafeInteger(n.maxResponseBytes)||n.maxResponseBytes<=0))return oi(ci(si.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 oi(ci(si.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?oi(ci(si.KV_RESPONSE_TOO_LARGE,"A KV batch value exceeds the requested response limit","kv",{meta:{status:a.status,statusText:a.statusText}})):oi(ci(si.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===ya);if(!o)return oi(ci(si.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:oi(ci(r.error.code,r.error.message,"kv"))};const i=r.headers,a=t===_a?void 0:this.parseBatchValue(r.dataBase64,i,n?.raw,n?.binary);return{key:e[s],result:ai({data:a,headers:this.createBatchResponseHeaders(i)})}});return ai({results:c,count:c.length})}catch(e){return oi(ha("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],ya):oi(ci(400===e.status?si.INVALID_INPUT:si.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}=Qi(r),c=n.find(e=>a===e||a===`${this.context.session.spaceId}/kv/${e}`),u=void 0!==c&&o===s?ra({service:"kv",code:si.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 oi((l=`${e}: ${t.status} - ${d}`,h={status:t.status,...i,...u},ci(si.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 oi(Wi("kv"));if(void 0!==t?.maxResponseBytes&&(!Number.isSafeInteger(t.maxResponseBytes)||t.maxResponseBytes<=0))return oi(ci(si.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===si.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 oi(ha("kv",e))}finally{n.dispose()}})}async getFromNetwork(e,t,r,n){const s=await this.invokeOperation(t,ya,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 Zi(r.permissionHint)??Zi(s?.permissionHint)}catch{return}}(r),i="tinycloud.kv"===n?.service&&n.space===this.context.session.spaceId&&n.path===t?ra({service:"kv",code:si.AUTH_UNAUTHORIZED,meta:{status:s.status,resource:`${this.context.session.spaceId}/kv/${t}`,requiredAction:ya}}):void 0;return this.authorizationFailure(`Failed to get key ${JSON.stringify(e)}`,s,r,[t],ya,i?{permissionHint:n,...i}:{})}if(404===s.status)return this.classifyNotFound(s,e);const r=await s.text();if(413===s.status)return oi(ci(si.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 oi(i||ci(si.NETWORK_ERROR,n,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return ai({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,ya,t))}async put(e,t,r){return this.withTelemetry("put",e,async()=>{if(null!==this.readThroughReady&&await this.readThroughReady(),!this.requireAuth())return oi(Wi("kv"));if(void 0!==r?.ifMatch&&void 0!==r.ifNoneMatch)return oi(ci(si.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 oi(ha("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 oi(ci(si.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 oi(n);return this.handleQuotaErrorResponse(i,t,e)||oi(ci(si.KV_WRITE_FAILED,r,"kv",{meta:{status:i.status,statusText:i.statusText}}))}return ai({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 oi(Wi("kv"));if(0===e.length)return ai({written:[],count:0});if(!this.context.invokeAny)return oi(ci(si.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 oi(ci(si.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=ha("kv",e);return oi({...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 oi(ci(si.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")||oi(ci(si.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=Ji(t);return oi(ci(r?si.TIMEOUT:si.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 oi(ci(si.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))?ai(u):oi(ci(si.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=ha("kv",e);return oi({...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 oi(Wi("kv"));if(void 0!==e?.limit&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3))return oi(ci(si.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 oi(ha("kv",e))}finally{r.dispose()}})}async listFromNetwork(e,t,r){const n=await this.invokeOperation(e,ma,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],ma);const t=await n.text(),r=`Failed to list keys: ${n.status} - ${t}`,s=zi("kv",r,n,t);return oi(s||ci(si.NETWORK_ERROR,r,"kv",{meta:{status:n.status,statusText:n.statusText}}))}return ai({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 ai({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 oi(Wi("kv"));if("string"!=typeof e?.prefix||0===e.prefix.length)return oi(ci(si.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 oi(ci(si.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,ka,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?ai(o):oi(ci(si.NETWORK_ERROR,"KV changes response was not a tinycloud.kv/sync page","kv",{meta:{status:s.status,statusText:s.statusText}}))}catch(e){return oi(ha("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 oi(ci(si.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 oi(ci(si.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=ba.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&&Ta.has(e.code)&&"string"==typeof e.error)return e.error}catch{}return t}(e));if(null!==t)return void 0!==t[1]?si.AUTH_DELEGATION_REVOKED:si.AUTH_DELEGATION_ANCESTOR_REVOKED}(n);if(void 0!==e)return oi(ci(e,`${o}: 401 - ${n}`,"kv",{meta:s}))}return 401===e.status||403===e.status?this.authorizationFailure(o,e,n,[t],ka):oi(ci(400===e.status?si.INVALID_INPUT:si.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 oi(Wi("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 oi(ha("kv",e))}finally{n.dispose()}})}async deleteFromNetwork(e,t,r,n){const s=await this.invokeOperation(t,va,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],va);if(404===s.status)return this.classifyNotFound(s,e);const r=await s.text();if(412===s.status)return oi(ci(si.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 oi(i||ci(si.NETWORK_ERROR,n,"kv",{meta:{status:s.status,statusText:s.statusText}}))}return ai({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 oi(Wi("kv"));const r=this.getFullPath(e,t?.prefix),n=this.createRequestSignal(t?.signal,t?.timeout);try{const t=await this.invokeOperation(r,_a,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],_a);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 oi(i||ci(si.NETWORK_ERROR,s,"kv",{meta:{status:t.status,statusText:t.statusText}}))}return ai({data:void 0,headers:this.createResponseHeaders(t.headers)})}catch(e){return oi(ha("kv",e))}finally{n.dispose()}})}async batchHead(e,t){return this.withTelemetry("batchHead",String(e.length),()=>this.batchRead(e,_a,t))}async createSignedReadUrl(e,t){return this.withTelemetry("createSignedReadUrl",e,async()=>{if(!this.requireAuth())return oi(Wi("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,ya),{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?ai(a):oi(ci(si.NETWORK_ERROR,"Signed read URL response did not include url, ticketId, and expiresAt","kv"))}catch(e){return oi(ha("kv",e))}finally{i.dispose()}})}withPrefix(e){return new pa(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)}},Ia=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)}},Aa={READ:tt.READ,WRITE:tt.WRITE,SCHEMA:tt.SCHEMA,ADMIN:tt.ADMIN,SELECT:tt.SELECT,EXECUTE:tt.EXECUTE,EXPORT:tt.EXPORT,ALL:tt.ALL},xa=new Set(["alter","create","drop"]),Sa="__tinycloud_sql_migrations",Da=`CREATE TABLE IF NOT EXISTS ${Sa} (\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",Pa="000_metadata";function La(e){return e.map(e=>e instanceof Uint8Array?Array.from(e):e)}function Ca(e){return/no such table/i.test(e)}function Ka(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Va(e,t){return Array.isArray(e)?e[t]:e&&"object"==typeof e?Object.values(e)[t]:void 0}(class extends fa{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 Ia(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 oi(ci(si.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 oi(Wi("sql"));const s=this.createRequestSignal(n?.signal);try{const i={action:"query",sql:t,params:La(r??[])};void 0!==n?.maxRows&&(i.maxRows=n.maxRows),void 0!==n?.maxBytes&&(i.maxBytes=n.maxBytes);const a=this.actionForSql(t,Aa.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 ai(await o.json())}catch(e){return this.redactFailure(oi(ha("sql",e)),n?.redactErrors)}finally{s.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return oi(Wi("sql"));const s=this.createRequestSignal(n?.signal);try{const i={action:"execute",sql:t,params:La(r??[])};n?.schema&&(i.schema=n.schema);const a=[this.actionForSql(t,Aa.WRITE),...(n?.schema??[]).map(e=>this.actionForSql(e,Aa.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 ai(await c.json())}catch(e){return this.redactFailure(oi(ha("sql",e)),n?.redactErrors)}finally{s.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return oi(Wi("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 ai(await i.json())}catch(e){return this.redactFailure(oi(ha("sql",e)),r?.redactErrors)}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return oi(Wi("sql"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeSQL(e,Aa.WRITE,{action:"execute_statement",name:t,params:r??[]},s.signal);return n.ok?ai(await n.json()):await this.handleErrorResponse(n,"executeStatement",e,[Aa.WRITE])}catch(e){return oi(ha("sql",e))}finally{s.dispose()}})}async exportDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return oi(Wi("sql"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeSQL(e,Aa.READ,{action:"export"},r.signal);if(!t.ok)return await this.handleErrorResponse(t,"export",e,[Aa.READ]);const n=t;return"function"==typeof n.blob?ai(await n.blob()):ai(await t.text())}catch(e){return oi(ha("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='${Sa}'`,[],{signal:t.signal});let n=r.ok?0===r.data.rows.length:r.error.code===si.SQL_DATABASE_NOT_FOUND||Ca(r.error.message);if(!r.ok&&!n)return r;const s=new Set;if(!n){const r=await this.queryOnDb(e,`SELECT id FROM ${Sa} WHERE namespace = ? ORDER BY applied_at, id`,[t.namespace],{signal:t.signal});if(n=!r.ok&&(r.error.code===si.SQL_DATABASE_NOT_FOUND||Ca(r.error.message)),!r.ok&&!n)return r;if(r.ok)for(const e of r.data.rows){const t=Va(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 ai({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 ${Sa} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[Ka(t,r.id),t,r.id,(new Date).toISOString(),r.sql.length]}],i=await this.batchOnDb(e,s,{signal:n});return i.ok?ai(void 0):i}async ensureMigrationsTable(e,t){const r=await this.batchOnDb(e,[{sql:Da},{sql:`INSERT OR REPLACE INTO ${Sa} (key, namespace, id, applied_at, statement_count) VALUES (?, ?, ?, ?, ?)`,params:[Ka(Ua,Pa),Ua,Pa,(new Date).toISOString(),1]}],{signal:t});return r.ok?ai(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?Aa.ADMIN:void 0!==r&&xa.has(r)?Aa.SCHEMA:t}actionsForSqlBatch(e){return this.dedupeActions(e.map(e=>this.actionForSql(e.sql,Aa.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(si,n)?n:si.SQL_ERROR,i="number"==typeof r&&Number.isInteger(r)&&r>=400&&r<=599?r:void 0;return oi(ci(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=Pi(e.status,e.statusText,s);if(402===e.status)return oi(la("sql",402,i,s));if(413===e.status&&da(s))return oi(la("sql",413,i,s));const a=zi("sql",`SQL ${t} failed: ${e.status} - ${s}`,e,s);if(a)return oi(a);const o=Di(s),c=Na("sql",t,e.status,s)??this.mapHttpStatusToErrorCode(e.status,o.error),u=Ui("SQL",t,e.status,s,o);if(401===e.status){const{action:e}=Qi(s);e&&n.includes(e)&&(i.requiredAction=e,i.resource=`${this.context.session.spaceId}/sql/${r}`)}return oi(ci(c,u,"sql",{meta:i}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return si.SQL_ERROR;case 401:return si.AUTH_UNAUTHORIZED;case 403:return"sql_readonly_violation"===t?si.SQL_READONLY_VIOLATION:si.SQL_PERMISSION_DENIED;case 404:return si.SQL_DATABASE_NOT_FOUND;case 413:return si.SQL_RESPONSE_TOO_LARGE;case 429:return si.SQL_QUOTA_EXCEEDED;default:return si.NETWORK_ERROR}}}).serviceName="sql";var $a=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)}},Ba={READ:rt.READ,WRITE:rt.WRITE,ADMIN:rt.ADMIN,DESCRIBE:rt.DESCRIBE,EXPORT:rt.EXPORT,IMPORT:rt.IMPORT,EXECUTE:rt.EXECUTE,ALL:rt.ALL};(class extends fa{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 $a(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 oi(Wi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Ba.READ,{action:"query",sql:t,params:r??[]},s.signal);return n.ok?ai(await n.json()):await this.handleErrorResponse(n,"query")}catch(e){return oi(ha("duckdb",e))}finally{s.dispose()}})}async queryArrowOnDb(e,t,r,n){return this.withTelemetry("queryArrow",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Ba.READ,{action:"query",sql:t,params:r??[]},s.signal,{Accept:"application/vnd.apache.arrow.stream"});return n.ok?ai(await n.arrayBuffer()):await this.handleErrorResponse(n,"queryArrow")}catch(e){return oi(ha("duckdb",e))}finally{s.dispose()}})}async executeOnDb(e,t,r,n){return this.withTelemetry("execute",e,async()=>{if(!this.requireAuth())return oi(Wi("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,Ba.WRITE,i,s.signal);return a.ok?ai(await a.json()):await this.handleErrorResponse(a,"execute")}catch(e){return oi(ha("duckdb",e))}finally{s.dispose()}})}async batchOnDb(e,t,r){return this.withTelemetry("batch",e,async()=>{if(!this.requireAuth())return oi(Wi("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,Ba.WRITE,s,n.signal);return i.ok?ai(await i.json()):await this.handleErrorResponse(i,"batch")}catch(e){return oi(ha("duckdb",e))}finally{n.dispose()}})}async executeStatementOnDb(e,t,r,n){return this.withTelemetry("executeStatement",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const s=this.createRequestSignal(n?.signal);try{const n=await this.invokeDuckDb(e,Ba.WRITE,{action:"executeStatement",name:t,params:r??[]},s.signal);return n.ok?ai(await n.json()):await this.handleErrorResponse(n,"executeStatement")}catch(e){return oi(ha("duckdb",e))}finally{s.dispose()}})}async describeDb(e,t){return this.withTelemetry("describe",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,Ba.READ,{action:"describe"},r.signal);return t.ok?ai(await t.json()):await this.handleErrorResponse(t,"describe")}catch(e){return oi(ha("duckdb",e))}finally{r.dispose()}})}async exportOnDb(e,t){return this.withTelemetry("export",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const r=this.createRequestSignal(t?.signal);try{const t=await this.invokeDuckDb(e,Ba.EXPORT,{action:"export"},r.signal);return t.ok?ai(await t.blob()):await this.handleErrorResponse(t,"export")}catch(e){return oi(ha("duckdb",e))}finally{r.dispose()}})}async importOnDb(e,t,r){return this.withTelemetry("import",e,async()=>{if(!this.requireAuth())return oi(Wi("duckdb"));const n=this.createRequestSignal(r?.signal);try{const r=await this.invokeWithRetry(`${this.host}/invoke`,()=>this.context.invoke(this.context.session,"duckdb",e,Ba.IMPORT),{headers:{"Content-Type":"application/x-duckdb"},body:new Blob([t]),signal:n.signal});return r.ok?ai(void 0):await this.handleErrorResponse(r,"import")}catch(e){return oi(ha("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=Pi(e.status,e.statusText,r);if(402===e.status)return oi(la("duckdb",402,n,r));if(413===e.status&&da(r))return oi(la("duckdb",413,n,r));const s=zi("duckdb",`DuckDB ${t} failed: ${e.status} - ${r}`,e,r);if(s)return oi(s);const i=Di(r),a=Na("duckdb",t,e.status,r)??this.mapHttpStatusToErrorCode(e.status,i.error),o=Ui("DuckDB",t,e.status,r,i);if(401===e.status){const{resource:e,action:t}=Qi(r);t&&(n.requiredAction=t),e&&(n.resource=e)}return oi(ci(a,o,"duckdb",{meta:n}))}mapHttpStatusToErrorCode(e,t){switch(e){case 400:return si.DUCKDB_ERROR;case 401:return si.AUTH_UNAUTHORIZED;case 403:return"duckdb_readonly_violation"===t?si.DUCKDB_READONLY_VIOLATION:si.DUCKDB_PERMISSION_DENIED;case 404:return si.DUCKDB_DATABASE_NOT_FOUND;case 413:return si.DUCKDB_RESPONSE_TOO_LARGE;case 429:return si.DUCKDB_QUOTA_EXCEEDED;default:return si.NETWORK_ERROR}}}).serviceName="duckdb";var qa=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 Fa(e,t){const r=so(t);return r?`${e}/${r}`:e}function Ma(e){return"number"==typeof e&&e>=400&&e<500&&408!==e&&429!==e}(class extends fa{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(to),n={requested:r,signatures:r.map(ro),ttlSeconds:t.ttlSeconds,onReady:t.onReady,queue:new qa},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 oi(Wi("hooks"));if("string"!=typeof e.secret||0===e.secret.trim().length)return oi(ci(si.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",Fa(e.service,e.pathPrefix)),{headers:{"content-type":"application/json"},body:JSON.stringify({space:e.space,service:e.service,pathPrefix:so(e.pathPrefix),abilities:e.abilities??[],callbackUrl:e.callbackUrl,secret:e.secret})});if(!t.ok)return oi(await io("hooks","failed to register webhook",t));const r=co(await t.json());return r?ai(r):oi(ha("hooks",new Error("Webhook registration response did not include a record")))}catch(e){return oi(ha("hooks",e))}}async list(e={}){if(!this.requireAuth())return oi(Wi("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=so(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?Fa(e.service,e.pathPrefix):"webhooks"),{method:"GET"});if(!r.ok)return oi(await io("hooks","failed to list webhooks",r));const n=function(e){if(Array.isArray(e))return e.map(e=>co(e)).filter(e=>null!==e);if(!e||"object"!=typeof e)return null;const t=e,r=uo(t.webhooks)??uo(t.subscriptions)??uo(t.hooks)??uo(t.data);if(r)return r;const n=lo(t);return n?[n]:null}(await r.json());return n?ai(n):oi(ha("hooks",new Error("Webhook list response did not include records")))}catch(e){return oi(ha("hooks",e))}}async unregister(e,t={}){if(!this.requireAuth())return oi(Wi("hooks"));try{const r=await this.invokeWithRetry(`${this.host}/hooks/webhooks/${encodeURIComponent(e)}`,()=>this.createHookHeaders("tinycloud.hooks/unregister",t.target?Fa(t.target.service,t.target.pathPrefix):`webhooks/${e}`),{method:"DELETE"});return r.ok?ai(void 0):oi(await io("hooks","failed to unregister webhook",r))}catch(e){return oi(ha("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 Ha(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 Ha(n.signal,()=>io("hooks","failed to mint hook ticket",d));return a()?{kind:"refused",terminal:Ma(e),error:t}:{kind:"stopped"}}const l=await Ha(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 Ha(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:Wa(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=ao(t);r&&(yield r),e=n.indexOf("\n\n")}}n+=r.decode();const s=ao(n.trim());s&&(yield s)}(f.body,n.signal)[Symbol.asyncIterator]();try{for(;;){const t=await Ha(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=oo(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===ja?{kind:"stopped"}:{kind:"failed",error:Ga(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??Xa)(s,e,t))}catch{n.push(Promise.resolve())}s.push(eo(t)),r&&s.push(eo(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(ci(si.INVALID_INPUT,"Hook readiness callback failed","hooks"))}}}dispatch(e){for(const t of this._subscribers)no(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=ci(si.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 ja=Symbol("hooks attempt superseded");async function Ha(e,t){if(e.aborted)throw"function"!=typeof t&&t.then(Za,()=>{}),ja;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(ja))};e.addEventListener("abort",a,{once:!0}),r.then(e=>{s?Za(e):(s=!0,i(),t(e))},e=>{s||(s=!0,i(),n(e))})})}function Za(e){if(e instanceof Response&&e.body)try{e.body.cancel().then(()=>{},()=>{})}catch{}}function Wa(e){const t="number"==typeof e?e:void 0;return ci(si.NETWORK_ERROR,`hook stream open refused: ${t??"unknown status"}`,"hooks",{meta:{phase:"open",status:t}})}var za=new Set(["Error","TypeError","AbortError","TimeoutError","SyntaxError","RangeError","NetworkError"]);function Ga(e,t){const r=Qa(t,"name"),n="string"==typeof r&&za.has(r)?r:"Error",s=Ya(Qa(t,"code"))??Ya(Qa(Qa(t,"cause"),"code"));return ci(si.NETWORK_ERROR,`hook stream ${e} failed: ${n}${s?` (${s})`:""}`,"hooks",{meta:{phase:e,errorName:n,...s?{errorCode:s}:{}}})}var Ja=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 Ya(e){return"string"==typeof e&&Ja.has(e)?e:void 0}function Qa(e,t){if(null!==e&&("object"==typeof e||"function"==typeof e))try{return Reflect.get(e,t)}catch{return}}var Xa=(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 eo(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 to(e){return{...e,pathPrefix:"kv"===e.service?so(e.pathPrefix):e.pathPrefix?.replace(/^\/+/,"")||void 0,abilities:e.abilities?[...e.abilities]:[]}}function ro(e){return JSON.stringify({space:e.space,service:e.service,pathPrefix:e.pathPrefix??"",abilities:[...e.abilities??[]].sort()})}function no(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 so(e){if(!e)return;const t=e.replace(/^\/+|\/+$/g,"");return t.length>0?t:void 0}async function io(e,t,r){let n=r.statusText;try{const e=await r.text();e&&(n=e)}catch{}return ci(408===r.status||504===r.status?si.TIMEOUT:si.NETWORK_ERROR,`${t}: ${r.status} ${n}`,e,{meta:{status:r.status,statusText:r.statusText}})}function ao(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 oo(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 co(e){if(!e||"object"!=typeof e)return null;const t=e;return lo(t)??co(t.webhook)??co(t.hook)??co(t.subscription)??co(t.data)??null}function uo(e){return Array.isArray(e)?e.map(e=>co(e)).filter(e=>null!==e):null}function lo(e){const t=ho(e,"id"),r=ho(e,"space")??ho(e,"spaceId"),n=ho(e,"service"),s=ho(e,"callbackUrl")??ho(e,"callback_url");return t&&r&&n&&s?{id:t,space:r,service:n,pathPrefix:fo(e,"pathPrefix")??fo(e,"path_prefix"),abilities:yo(e,"abilities")??go(e,"abilitiesJson")??go(e,"abilities_json"),callbackUrl:s,active:po(e,"active")??!0,createdAt:ho(e,"createdAt")??ho(e,"created_at")??(new Date).toISOString(),subscriberDid:fo(e,"subscriberDid")??fo(e,"subscriber_did")}:null}function ho(e,t){const r=e[t];return"string"==typeof r?r:void 0}function fo(e,t){return ho(e,t)}function po(e,t){const r=e[t];return"boolean"==typeof r?r:void 0}function yo(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 mo(e){return void 0===e?"":vo(e)}function vo(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(vo).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)}:${vo(t)}`)}return`{${r.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}var _o="0123456789abcdef";function ko(e){let t="";for(let r=0;r<e.length;r++){const n=e[r];t+=_o[n>>4&15]+_o[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 wo(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 bo(e){return(new TextEncoder).encode(e)}function To(e,t){return ko(e(bo(mo(t))))}var Oo=/^[A-Z][A-Z0-9_]{0,63}$/,No="tinychat-bot-history",Ro=new Set(["default","global",No]),Io=/^[a-z0-9]+(-[a-z0-9]+)*$/;function Ao(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&&Io.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",No]);var xo={masterMessage:e=>`tinycloud-vault-master-v1:${e}`,identityMessage:"tinycloud-encryption-identity-v1"},So="x-vault-version",Do="x-vault-cipher",Uo="x-vault-key-id",Po="x-vault-content-type",Lo="x-vault-kdf",Co="x-vault-key-rotation",Ko="x-vault-grant-version",Vo="x-vault-grantor",$o="signatures",Bo="__wrap_key__";function qo(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof crypto&&void 0!==crypto.subtle}catch{return!1}}function Fo(){return new Promise((e,t)=>{const r=indexedDB.open("tinycloud-vault-cache",1);r.onupgradeneeded=()=>{const e=r.result;e.objectStoreNames.contains($o)||e.createObjectStore($o)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}function Mo(e,t){return new Promise((r,n)=>{const s=e.transaction($o,"readonly").objectStore($o).get(t);s.onsuccess=()=>r(s.result),s.onerror=()=>n(s.error)})}function jo(e,t,r){return new Promise((n,s)=>{const i=e.transaction($o,"readwrite").objectStore($o).put(r,t);i.onsuccess=()=>n(),i.onerror=()=>s(i.error)})}function Ho(e,t){return new Promise((r,n)=>{const s=e.transaction($o,"readwrite").objectStore($o).delete(t);s.onsuccess=()=>r(),s.onerror=()=>n(s.error)})}async function Zo(e){const t=await Mo(e,Bo);if(t)return t;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await jo(e,Bo,r),r}function Wo(e){return`sig:${e}`}async function zo(e){if(!qo())return null;try{const t=await Fo(),r=await Mo(t,Wo(e));if(!r)return null;const n=await Zo(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 Go(e,t){if(qo())try{const r=await Fo(),n=await Zo(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 jo(r,Wo(e),s)}catch{}}async function Jo(e){if(qo())try{const t=await Fo();if(e)await Ho(t,Wo(e));else{const e=await function(e){return new Promise((t,r)=>{const n=e.transaction($o,"readonly").objectStore($o).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 Ho(t,r)}}catch{}}function Yo(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function Qo(e){return(new TextEncoder).encode(e)}function Xo(e){return(new TextDecoder).decode(e)}function ec(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}function tc(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function rc(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 nc(e){return null!==e&&"object"==typeof e&&"data"in e?e.data:e}function sc(e){return"number"==typeof e.meta?.status}function ic(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 ac(e){return{ok:!1,error:{...e,service:"vault",message:ic(e)}}}function oc(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 cc(e){return e.replace(/0x[0-9a-fA-F]{40}/g,e=>e.toLowerCase())}function uc(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=Xo(wo(n.aad)))}catch{}const i=`:${r}`;return s.endsWith(i)&&cc(s.slice(0,-i.length))===cc(`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 dc=[500,502,503,504,520,522,524];function lc(e,t){const r=Hi(t);if(r)return ac(r);if(t.code===si.STORAGE_QUOTA_EXCEEDED||t.code===si.STORAGE_LIMIT_REACHED)return ac({code:t.code,message:t.message,meta:t.meta});const n=`${e}: ${t.message}`;return t.code===si.AUTH_UNAUTHORIZED?ac({code:"unauthenticated"===ia(t)?"AUTH_UNAUTHORIZED":"PERMISSION_DENIED",message:n,...void 0!==t.meta?{meta:t.meta}:{},cause:oc(t)}):ac({code:"STORAGE_ERROR",cause:new Error(n,{cause:oc(t)}),...void 0!==t.meta?{meta:t.meta}:{}})}function hc(e){return"not_found"===e||"permission_required"===e||"aad_mismatch"===e?e:"read_failed"}function fc(e,t){return e.length===t.length&&e.every((e,r)=>e===t[r])}(class extends fa{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||cc(String(s))!==cc(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(Hi(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):Qo("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(Xo(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=xo,n=`vault-master:${e}`,s=`vault-identity:${this.tc.address}`;try{if(!this.masterKey){let s=await zo(n);if(!s){if(!t)return ac({code:"VAULT_LOCKED",message:"Signer is required when no cached master signature exists"});s=Qo(await t.signMessage(r.masterMessage(e))),await Go(n,s)}this.masterKey=this.crypto.deriveKey(s,this.crypto.sha256(Qo(e)),Qo("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:rc(a),privateKey:new Uint8Array(0)};else{let e=await zo(s);if(!e){if(!t)return this.encryptionIdentity=null,this._isUnlocked=!0,ai(void 0);e=Qo(await t.signMessage(r.identityMessage)),await Go(s,e)}const n=this.crypto.deriveKey(e,Qo("tinycloud-x25519"),Qo("encryption-identity"));this.encryptionIdentity=this.crypto.x25519FromSeed(n);try{const e=tc(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,ai(void 0)}catch(e){return this.masterKey=null,this.encryptionIdentity=null,ac({code:"STORAGE_ERROR",cause:Yo(e)})}});try{return await this.unlockInFlight}finally{this.unlockInFlight=null}}async clearCache(e){e?await Jo(`vault-master:${e}`):await Jo()}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 ac({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return ac({code:"VAULT_LOCKED",message:"Authentication required"});if(void 0!==r?.ifMatch){if(void 0!==r.ifNoneMatch)return ac({code:"STORAGE_ERROR",cause:new Error("ifMatch cannot be combined with ifNoneMatch")});if(!/^"[^"\s]+"$/.test(r.ifMatch))return ac({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={[So]:"2",[Do]:"tinycloud-network-envelope",[Po]:i,...r?.metadata??{}},o=Qo(`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=Hi(c.error);return ac(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===si.KV_PRECONDITION_FAILED)return ac({code:"ALREADY_EXISTS",key:e,...void 0!==h.error.meta?{meta:h.error.meta}:{},cause:oc(h.error)});if(void 0!==r?.ifMatch){const t=function(e,t){const r=t.meta?.status,n=t.code===si.KV_PRECONDITION_FAILED?"ETAG_MISMATCH":t.code===si.KV_WRITE_FAILED&&400===r?"INVALID_ETAG":t.code===si.OUTCOME_UNKNOWN||t.code===si.KV_WRITE_FAILED&&"number"==typeof r&&dc.includes(r)||(t.code===si.NETWORK_ERROR||t.code===si.TIMEOUT)&&void 0===r&&!1!==t.meta?.requestMayHaveDispatched?"OUTCOME_UNKNOWN":t.code===si.NODE_BUSY||t.code===si.REQUEST_TIMEOUT?"NODE_BUSY":void 0;if(void 0!==n)return ac({code:n,key:e,message:t.message,...void 0!==t.meta?{meta:t.meta}:{},cause:oc(t)})}(e,h.error);if(void 0!==t)return t}return lc("Failed to store encrypted value",h.error)}return{ok:!0,data:void 0}}catch(e){const t=Hi(e);return ac(t||{code:"STORAGE_ERROR",cause:Yo(e)})}}async getNetworkEncrypted(e,t){if(!this.networkEncryption)return ac({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return ac({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=Hi(r.error);return ac(t||{code:"KEY_NOT_FOUND",key:e})}const n=nc(r.data),s="string"==typeof n?JSON.parse(n):n,i=uc(s,this.vaultConfig.spaceId,e,t);if("corrupt"===i)return ac({code:"DECRYPTION_FAILED",message:"envelope is malformed"});if("mismatch"===i)return ac({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=Hi(a.error);if(t)return ac(t);const{code:r,message:n,permissionHint:s}=a.error;return ac("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[Po]??"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=Hi(e);return ac(t||{code:"STORAGE_ERROR",cause:Yo(e)})}}async readNetworkEncrypted(e,t){const r=await this.fetchNetworkEnvelope(e);if("fetched"!==r.status)return r;const{envelope:n,etag:s}=r,i=uc(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[Po]??"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 Ao(e,Oo)}(e.slice(8)):void 0;if(void 0===n||function(e,t){if(!Oo.test(e)||void 0!==t&&(!Io.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===No)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:hc(a.status)};const{envelope:o,etag:c}=a,u=uc(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&&cc(String(o.networkId))===cc(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:hc(d.status)};let l,h,f;try{l=await this.namedKeys(),h=await l.encrypt(t,d.plaintext,{networkId:s.networkId,aad:Qo(i),metadata:o.metadata??{},ensureKey:!0})}catch(e){if(Hi(e))throw e;const{status:t}=e;return{status:"skipped",reason:401===t||403===t?"permission_required":"write_failed"}}try{if(!fc(await l.decrypt(h),d.plaintext))return{status:"skipped",reason:"verify_failed"}}catch(e){if(Hi(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(Hi(e))throw e;return{status:"skipped",reason:"write_failed"}}if(f.ok)return{status:"moved"};if(Hi(f.error))throw f.error;if(f.error.code!==si.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(Hi(e))throw e;return{status:"node_unreachable"}}if(!t.ok){if(Hi(t.error))throw t.error;const e=Zi(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||sc(t.error)?"NODE_NOT_RESPONDING"===t.error.code||"NETWORK_ERROR"===t.error.code||"TIMEOUT"===t.error.code||"ABORTED"===t.error.code?sc(t.error)?{status:"read_failed"}:{status:"node_unreachable"}:{status:"read_failed"}:{status:"not_found"}}try{const e=nc(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(Hi(e))throw e;return{status:"decrypt_failed"}}if(r.ok)return{status:"opened",plaintext:r.data};if(Hi(r.error))throw r.error;const n=Zi(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 ac({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0,source:"network"});if(!t.ok)return ac({code:"KEY_NOT_FOUND",key:e});const r=nc(t.data);return{ok:!0,data:("string"==typeof r?JSON.parse(r):r).metadata??{}}}catch(e){return ac({code:"STORAGE_ERROR",cause:Yo(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 ac({code:"STORAGE_ERROR",cause:new Error("ifNoneMatch is only supported by network-encrypted vaults")});if(void 0!==r?.ifMatch)return ac({code:"STORAGE_ERROR",cause:new Error("ifMatch is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return ac({code:"VAULT_LOCKED",message:"Vault must be unlocked before storing data"});if(!this.requireAuth())return ac({code:"VAULT_LOCKED",message:"Authentication required"});try{let n;n=t instanceof Uint8Array?t:r?.serialize?r.serialize(t):Qo("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=ec(this.crypto.sha256(i)).slice(0,16),o=this.crypto.encrypt(i,n),c=this.crypto.encrypt(this.masterKey,i),u={[So]:"1",[Do]:"aes-256-gcm",[Uo]:a,[Po]:s,[Lo]:"hkdf-sha256",[Co]:this.vaultConfig.keyRotation??"per-write",...r?.metadata??{}},d=JSON.stringify({keyId:a,contentType:s,...u}),l=JSON.stringify({key:tc(c),metadata:d}),h=await this.tc.kv.put(`keys/${e}`,l);if(!h.ok)return lc("Failed to store key blob",h.error);const f=JSON.stringify({data:tc(o),metadata:u}),p=await this.tc.kv.put(`vault/${e}`,f);return p.ok?ai(void 0):lc("Failed to store encrypted value",p.error)}catch(e){return ac({code:"STORAGE_ERROR",cause:Yo(e)})}})}async get(e,t){return this.withTelemetry("get",e,async()=>{if(this.usesNetworkEncryption)return this.getNetworkEncrypted(e,t);if(!0===t?.expectAad)return ac({code:"STORAGE_ERROR",cause:new Error("expectAad is only supported by network-encrypted vaults")});if(!this._isUnlocked||!this.masterKey)return ac({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading data"});if(!this.requireAuth())return ac({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 ac({code:"KEY_NOT_FOUND",key:e});const n=rc(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 ac({code:"KEY_NOT_FOUND",key:e});const a=JSON.parse(i.data.data),o=rc(a.data),c=this.crypto.decrypt(s,o),u=a.metadata??{},d=u[Po]??"application/json",l=u[Uo]??"";let h;return h=t?.raw?c:t?.deserialize?t.deserialize(c):"application/json"===d?JSON.parse(Xo(c)):c,ai({value:h,metadata:u,keyId:l})}catch(e){return e instanceof Error&&e.message.includes("decryption")?ac({code:"DECRYPTION_FAILED",message:e.message}):ac({code:"STORAGE_ERROR",cause:Yo(e)})}})}async delete(e){return this.withTelemetry("delete",e,async()=>{if(!this.isUnlocked)return ac({code:"VAULT_LOCKED",message:"Vault must be unlocked before deleting data"});if(!this.requireAuth())return ac({code:"VAULT_LOCKED",message:"Authentication required"});try{if(this.usesNetworkEncryption){const t=await this.tc.kv.delete(`vault/${e}`);if(!t.ok){const r=Hi(t.error);return ac(r||{code:"KEY_NOT_FOUND",key:e})}return ai(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=Hi(t.error)??Hi(r.error);return ac(n||{code:"KEY_NOT_FOUND",key:e})}return ai(void 0)}catch(e){const t=Hi(e);return ac(t||{code:"STORAGE_ERROR",cause:Yo(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 ac({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing data"});if(!this.requireAuth())return ac({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=Hi(r.error);return ac(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 ai({keys:n,truncated:!0===r.data.truncated,...void 0===r.data.nextCursor?{}:{nextCursor:r.data.nextCursor}})}catch(e){const t=Hi(e);return ac(t||{code:"STORAGE_ERROR",cause:Yo(e)})}})}async head(e){return this.withTelemetry("head",e,async()=>{if(this.usesNetworkEncryption)return this.headNetworkEncrypted(e);if(!this._isUnlocked)return ac({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading metadata"});if(!this.requireAuth())return ac({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.get(`vault/${e}`,{raw:!0});if(!t.ok)return ac({code:"KEY_NOT_FOUND",key:e});return ai(JSON.parse(t.data.data).metadata??{})}catch(e){return ac({code:"STORAGE_ERROR",cause:Yo(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 ac({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 ac({code:"VAULT_LOCKED",message:"Vault must be unlocked before granting access"});if(!this.requireAuth())return ac({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 ac({code:"KEY_NOT_FOUND",key:e});const a=rc(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,Qo("tinycloud-x25519"),Qo("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:tc(f),spaceId:this.vaultConfig.spaceId,metadata:{[Ko]:"1",[Vo]:this.tc.did,...r?.metadata??{}}}),y=await this.tc.kv.put(`grants/${t}/${e}`,p);return y.ok?ai(void 0):lc("Failed to store grant",y.error)}catch(e){return ac({code:"STORAGE_ERROR",cause:Yo(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 ac({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 ac({code:"STORAGE_ERROR",cause:new Error("getShared requires a delegated KV service via options.kv.")});const n=this.networkEncryption;if(!n)return ac({code:"VAULT_LOCKED",message:"Network encryption is not configured"});if(!this.requireAuth())return ac({code:"VAULT_LOCKED",message:"Authentication required"});try{const s=await e.get(`vault/${t}`,{raw:!0});if(!s.ok)return ac({code:"KEY_NOT_FOUND",key:t});const i=nc(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 ac({code:"DECRYPTION_FAILED",message:c.error.message});const u=a.metadata??{},d=u[Po]??"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 ac({code:"STORAGE_ERROR",cause:Yo(e)})}}if(!this._isUnlocked||!this.masterKey||!this.encryptionIdentity)return ac({code:"VAULT_LOCKED",message:"Vault must be unlocked before reading shared data"});if(!this.requireAuth())return ac({code:"VAULT_LOCKED",message:"Authentication required"});try{const n=this.tc.did,s=r?.kv;if(!s)return ac({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 ac({code:"GRANT_NOT_FOUND",grantor:e,key:t});const a=rc(("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,Qo("tinycloud-x25519"),Qo("vault-grant")),l=this.crypto.decrypt(d,c),h=await s.get(`vault/${t}`,{raw:!0});if(!h.ok)return ac({code:"KEY_NOT_FOUND",key:t});const f="string"==typeof h.data?.data?JSON.parse(h.data.data):h.data?.data,p=rc(f.data),y=this.crypto.decrypt(l,p),g=f.metadata??{},m=g[Po]??"application/json",v=g[Uo]??"";let _;return _=r?.raw?y:r?.deserialize?r.deserialize(y):"application/json"===m?JSON.parse(Xo(y)):y,ai({value:_,metadata:g,keyId:v})}catch(e){return e instanceof Error&&e.message.includes("decryption")?ac({code:"DECRYPTION_FAILED",message:e.message}):ac({code:"STORAGE_ERROR",cause:Yo(e)})}})}async resolvePublicKey(e){try{const t=this.parseDID(e);if(!t)return ac({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:rc(n.data)}:ac({code:"PUBLIC_KEY_NOT_FOUND",did:e})}catch(t){return ac({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 ac({code:"VAULT_LOCKED",message:"Vault must be unlocked before listing grants"});if(!this.requireAuth())return ac({code:"VAULT_LOCKED",message:"Authentication required"});try{const t=await this.tc.kv.list({prefix:"grants/",removePrefix:!0});if(!t.ok)return ac({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 ai(r)}catch(e){return ac({code:"STORAGE_ERROR",cause:Yo(e)})}})}async revoke(e,t){return this.withTelemetry("revoke",e,async()=>{if(this.usesNetworkEncryption)return ac({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 ac({code:"VAULT_LOCKED",message:"Vault must be unlocked before revoking access"});if(!this.requireAuth())return ac({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=ec(this.crypto.sha256(a)).slice(0,16);let c;c=i.value instanceof Uint8Array?i.value:Qo(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:tc(d),metadata:JSON.stringify({keyId:o,...l})}),f=await this.tc.kv.put(`keys/${e}`,h);if(!f.ok)return lc("Failed to store rotated key blob",f.error);const p=JSON.stringify({data:tc(u),metadata:l}),y=await this.tc.kv.put(`vault/${e}`,p);if(!y.ok)return lc("Failed to store re-encrypted value",y.error);for(const t of n)(await this.reencrypt(e,t)).ok;return ai(void 0)}catch(e){return ac({code:"STORAGE_ERROR",cause:Yo(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 pc="tinycloud.encryption.decrypt/v1",yc="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 mc(e){return{...e,service:"encryption",message:gc(e)}}function vc(e){return e instanceof Error?e:"object"==typeof e&&null!==e?new Error(JSON.stringify(e)):new Error(String(e))}function _c(e,t,r,n){let s;try{s=Bi(e.networkId)}catch(e){return{ok:!1,error:mc({code:"INVALID_NETWORK_ID",message:`descriptor networkId is malformed: ${e instanceof Error?e.message:String(e)}`})}}if(s.name!==n||!Mi(s.ownerDid,r))return{ok:!1,error:mc({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&&Mi(i,r)&&Mi(i,s.ownerDid)?e.name!==n?{ok:!1,error:mc({code:"INVALID_NETWORK_ID",message:"descriptor name does not match networkId name"})}:"string"!=typeof e.publicEncryptionKey||0===e.publicEncryptionKey.length?{ok:!1,error:mc({code:"INVALID_NETWORK_ID",message:"descriptor publicEncryptionKey must be a non-empty string"})}:{ok:!0,data:{...e,ownerDid:i}}:{ok:!1,error:mc({code:"INVALID_NETWORK_ID",message:"descriptor ownerDid does not match networkId ownerDid"})}}function kc(e){return"active"===e.state||"rotating"===e.state?{ok:!0,data:e}:{ok:!1,error:mc({code:"NETWORK_NOT_ACTIVE",state:e.state})}}var Ec="x25519-hkdf-aes256gcm/v2",wc=bo("TCW2"),bc=bo("tinycloud.encryption.key-wrap/v2");function Tc(...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 Nc(e){if("string"!=typeof e)throw new Error("Invalid key wrap encoding");const t=wo(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 Ic(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=qi(""===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 Ac(e){return e.length>=4&&wc.every((t,r)=>e[r]===t)}function xc(e){if(!Ac(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(Ic(n),Nc(n.salt),Nc(n.ephemeralPublicKey),Nc(n.recipientPublicKey),!Oc(r,bo(mo({...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 Sc(e,t){Ic(t);for(const r of["purpose","networkId","keyPath","keyVersion"])if(e[r]!==t[r])throw new Error("Key wrap context mismatch");if(mo(e.metadata)!==mo(t.metadata))throw new Error("Key wrap metadata mismatch")}function Dc(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(Ac(e)!==(t===Ec))throw new Error("Key wrap algorithm mismatch");t===Ec&&xc(e)}function Uc(e,t=!1){const r=wo(e.encryptedSymmetricKey);Dc(r,e.alg,t),e.alg===Ec&&Sc(xc(r).header,{purpose:"network-key",networkId:e.networkId,keyPath:e.keyPath??"",keyVersion:e.keyVersion,metadata:e.metadata??{}})}function Pc(e){return{ok:!0,data:e}}function Lc(e){return{ok:!1,error:e}}function Cc(e){return mc("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 fa{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:mc({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 $i)return{ok:!1,error:mc({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=_c(s,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"node"}}:e}}catch(e){const t=Hi(e);return t?{ok:!1,error:mc(t)}:{ok:!1,error:mc({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(!Ki.test(e))throw new $i(`network name ${JSON.stringify(e)} must match ${Ki.source}`);return`.well-known/encryption/network/${e}`}(n));if(null!==s){const e=_c(s,t,r,n);return e.ok?{ok:!0,data:{descriptor:e.data,source:"well-known"}}:e}}catch(e){const t=Hi(e);if(t)return{ok:!1,error:mc(t)}}return{ok:!1,error:mc({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?Pc(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=kc(n.data);if(!s.ok)return s;const i=s.data,a=wo(i.publicEncryptionKey);return Pc(function(e,t){if(qi(void 0===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`).keyPath!==t.keyPath||t.keyPath?.endsWith("/"))throw new $i("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(Ic(r),32!==e.length)throw new Error("Invalid recipient public key");const n=Kr(32),s=Bs.getPublicKey(n),i=Kr(32),a=bo(mo({...{...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(wc),new DataView(o.buffer).setUint32(4,a.length);const c=Tc(o,a),u=Kr(12);let d;try{const r=Bs.getSharedSecret(n,e);try{if(r.every(e=>0===e))throw new Error("Invalid key agreement");d=ti(ri,r,i,Tc(bc,s,e),32)}finally{r.fill(0)}return Tc(c,u,gr(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=To(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=Hi(e);return Lc(mc(t||{code:"TRANSPORT_ERROR",cause:vc(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:mc({code:"INVALID_ENVELOPE",message:"envelope must be an object"})};const n=t;if(1!==n.v)return{ok:!1,error:mc({code:"INVALID_ENVELOPE",message:`envelope.v must be 1 (got ${n.v})`})};try{if(void 0!==qi(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(qi(`${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:mc({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:mc({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:mc({code:"INVALID_ENVELOPE",message:"envelope.keyVersion must be an integer"})};if(To(e.sha256,n.encryptedSymmetricKey)!==n.encryptedSymmetricKeyHash)return{ok:!1,error:mc({code:"INVALID_ENVELOPE",message:"envelope.encryptedSymmetricKeyHash does not match canonical hash of encryptedSymmetricKey"})};try{Uc(n,r)}catch{return{ok:!1,error:mc({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 Lc(mc({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 Lc(Cc(t.error));i=t.data}const a=kc(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 Lc(mc({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 Lc(mc({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=To(this.crypto.sha256,u),l={type:pc,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:mo((n={crypto:this.crypto,body:l,receiverPublicKey:c.publicKey}).body),bodyHash:To(n.crypto.sha256,n.body),receiverPublicKeyHash:To(n.crypto.sha256,n.body.receiverPublicKey)},f=function(e){const t=void 0!==e.canonicalBody?ko(e.crypto.sha256(bo(e.canonicalBody))):To(e.crypto.sha256,e.body),r=To(e.crypto.sha256,e.body.receiverPublicKey);return{type:pc,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!==pc)return{ok:!1,error:mc({code:"INVALID_INPUT",message:`body.type must be ${pc}`})};if(t.facts.type!==pc)return{ok:!1,error:mc({code:"INVALID_INPUT",message:`facts.type must be ${pc}`})};if(t.facts.targetNode!==t.targetNode)return{ok:!1,error:mc({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:mc({code:"INVALID_INPUT",message:"body.targetNode must equal targetNode"})};if(t.facts.networkId!==t.networkId)return{ok:!1,error:mc({code:"INVALID_INPUT",message:"facts.networkId must equal networkId"})};if(t.body.networkId!==t.networkId)return{ok:!1,error:mc({code:"INVALID_INPUT",message:"body.networkId must equal networkId"})};if(t.facts.keyPath!==t.body.keyPath)return{ok:!1,error:mc({code:"INVALID_INPUT",message:"facts.keyPath must equal body.keyPath"})};if(t.facts.alg!==t.body.alg)return{ok:!1,error:mc({code:"INVALID_INPUT",message:"facts.alg must equal body.alg"})};if(t.facts.keyVersion!==t.body.keyVersion)return{ok:!1,error:mc({code:"INVALID_INPUT",message:"facts.keyVersion must equal body.keyVersion"})};if(t.facts.encryptedSymmetricKeyHash!==t.body.encryptedSymmetricKeyHash)return{ok:!1,error:mc({code:"INVALID_INPUT",message:"facts.encryptedSymmetricKeyHash must equal body.encryptedSymmetricKeyHash"})};if(t.facts.receiverPublicKeyHash!==t.body.receiverPublicKeyHash)return{ok:!1,error:mc({code:"INVALID_INPUT",message:"facts.receiverPublicKeyHash must equal body.receiverPublicKeyHash"})};try{if(void 0!==qi(t.networkId).keyPath)throw new $i("networkId must identify the network root")}catch(e){return{ok:!1,error:mc({code:"INVALID_NETWORK_ID",message:e instanceof Error?e.message:String(e)})}}try{if(qi(void 0===t.body.keyPath?t.body.networkId:`${t.body.networkId}/${t.body.keyPath}`).keyPath!==t.body.keyPath||t.body.keyPath?.endsWith("/"))throw new $i("keyPath must name an exact encryption key")}catch(e){return{ok:!1,error:mc({code:"INVALID_INPUT",message:e instanceof Error?e.message:String(e)})}}const r=mo(t.body);return To(e.sha256,t.body)!==t.facts.bodyHash?{ok:!1,error:mc({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:mc({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:mc({code:"INVALID_INPUT",message:"decrypt-invocation signer returned an empty authorization or invocationCid"})}}catch(e){return{ok:!1,error:mc({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:Lc(mc({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=Hi(t);return r?Lc(Cc(r)):t instanceof ni.DecryptTransportResponseError?Lc(mc(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"})):Lc(Cc({code:"TRANSPORT_ERROR",cause:vc(t)}))}const g=function(e){const{crypto:t,request:r,facts:n,invocationCid:s,requestBodyHash:i,response:a}=e;if(a.type!==yc)return{ok:!1,error:mc({code:"INVALID_RESPONSE",message:`response.type must be ${yc}`})};if(a.targetNode!==r.targetNode)return{ok:!1,error:mc({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(a.networkId!==r.networkId)return{ok:!1,error:mc({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(a.nodeId!==r.targetNode)return{ok:!1,error:mc({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if("x25519-aes256gcm/v1"!==a.alg&&a.alg!==Ec)return{ok:!1,error:mc({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(a.keyVersion!==r.keyVersion)return{ok:!1,error:mc({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(a.encryptedSymmetricKeyHash!==r.encryptedSymmetricKeyHash)return{ok:!1,error:mc({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(a.receiverPublicKeyHash!==r.receiverPublicKeyHash)return{ok:!1,error:mc({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(a.invocationCid!==s)return{ok:!1,error:mc({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const o=ko(t.sha256(bo(`${s}${i}`)));if(a.requestHash!==o)return{ok:!1,error:mc({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:mc({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const c=(new TextEncoder).encode(function(e){const{nodeSignature:t,...r}=e;return mo(r)}(a)),u=wo(a.nodeSignature);return t.verifyNodeSignature(a.nodeId,c,u)?{ok:!0,data:a}:{ok:!1,error:mc({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=wo(r.wrappedKey);if(Dc(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}=xc(t);Sc(n,r);const o=Bs.getPublicKey(e);if(!Oc(o,Nc(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 ti(ri,s,n,Tc(bc,t,r),32)}finally{s.fill(0)}}(e,Nc(n.ephemeralPublicKey),o,Nc(n.salt));try{return gr(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){Uc(t);const n=wo(t.ciphertext),s=void 0!==t.aad?wo(t.aad):void 0;return e.authDecrypt(r,n,s)}(this.crypto,e,m);return Pc(v)}catch(e){const t=Hi(e);return Lc(t?Cc(t):mc({code:"INVALID_RESPONSE",message:"Local decryption failed"}))}var n}assertActive(){this._config.assertActive?.()}}).serviceName="encryption";var Kc=Me({kty:Ve(),crv:Ve().optional(),x:Ve().optional(),y:Ve().optional(),d:Ve().optional(),e:Ve().optional(),n:Ve().optional(),kid:Ve().optional(),alg:Ve().optional(),use:Ve().optional(),key_ops:Fe(Ve()).optional()}),Vc=We(["main","session","ingested"]),$c=Me({id:Ve(),did:Ve(),type:Vc,jwk:Kc.optional(),priority:$e()}),Bc=(Me({code:Ve(),message:Ve(),service:Ze("delegation"),cause:((e,t={message:`Input not instance of ${e.name}`})=>Ce(t=>t instanceof e,t))(Error).optional(),meta:He(Ve(),qe()).optional()}),{AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_EXPIRED:"AUTH_EXPIRED",NOT_INITIALIZED:"NOT_INITIALIZED",NOT_FOUND:"NOT_FOUND",REVOKED:"REVOKED",NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT:"TIMEOUT",ABORTED:"ABORTED",INVALID_INPUT:"INVALID_INPUT",PERMISSION_DENIED:"PERMISSION_DENIED",CREATION_FAILED:"CREATION_FAILED",REVOCATION_FAILED:"REVOCATION_FAILED",INVALID_TOKEN:"INVALID_TOKEN",KV_SERVICE_UNAVAILABLE:"KV_SERVICE_UNAVAILABLE",DATA_FETCH_FAILED:"DATA_FETCH_FAILED",VALIDATION_ERROR:"VALIDATION_ERROR",UNSUPPORTED_OPERATION:"UNSUPPORTED_OPERATION",CHAIN_TOO_DEEP:"CHAIN_TOO_DEEP",INVALID_CURSOR:"INVALID_CURSOR"}),qc=Me({cid:Ve(),delegateDID:Ve(),spaceId:Ve(),path:Ve(),actions:Fe(Ve()),caveats:Fe(He(Ve(),qe())).optional(),expiry:ze(),isRevoked:Be(),delegatorDID:Ve().optional(),createdAt:ze().optional(),parentCid:Ve().optional(),allowSubDelegation:Be().optional(),authHeader:Ve().optional()}),Fc=Me({cid:Ve().min(1),lease_cid:Ve().min(1),generation:$e().int().nonnegative().safe(),previous_stamp_cid:Ve().min(1),new_end:$e().int().nonnegative().safe(),signed_bytes:Ve().min(1),signature:Ve().min(1)}).strict(),Mc=(Me({cid:Ve().min(1),status:We(["active","revoked","expired","unavailable","not_found"]),exists:Be(),active:Be(),revoked:Be(),expired:Be(),effective_expiry:$e().int().nullable().optional(),renewal_history:Fe(Fc).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:c.custom,message:"delegation status flags do not match status"})}),Me({revoked:Ze(!0),cid:Ve().min(1)}).strict()),jc=Me({resource:Ve().min(1),actions:Fe(Ve()),caveats:Fe(He(Ve(),qe()))}).strict(),Hc=Ve().datetime({offset:!0}).transform(e=>new Date(e)),Zc=Me({cid:Ve().min(1),direction:We(["granted","received"]),delegatorDid:Ve().min(1),delegateDid:Ve().min(1),resources:Fe(jc),parents:Fe(Ve()),issuedAt:Hc.nullable(),notBefore:Hc.nullable(),expiresAt:Hc.nullable(),status:We(["active","pending","expired","revoked","ancestor_revoked"]),revokedAt:Hc.nullable().optional(),revokedBy:Ve().optional(),revokedAncestorCid:Ve().optional()}).strict(),Wc=Me({schemaVersion:Ze(2),items:Fe(Zc),nextCursor:Ve().optional()}).strict(),zc=(Me({direction:We(["granted","received","all","issued"]).optional(),status:We(["active","pending","expired","revoked","ancestor_revoked"]).optional(),space:Ve().trim().min(1).optional(),limit:$e().int().min(1).max(100).optional(),cursor:Ve().min(1).optional()}).strict(),Me({resource:Ve(),action:Ve(),keys:Fe($c),delegation:qc,expiresAt:ze().optional()}),Me({cid:Ve(),spaceId:Ve(),delegator:Ve(),delegatee:Ve(),keyId:Ve().optional(),path:Ve(),actions:Fe(Ve()),expiry:ze().optional(),notBefore:ze().optional(),isRevoked:Be(),createdAt:ze(),parentCid:Ve().optional()}),Me({delegateDID:Ve(),path:Ve(),actions:Fe(Ve()),expiry:ze().optional(),disableSubDelegation:Be().optional(),statement:Ve().optional()}),Fe(qc),Me({root:qc,chain:Fe(qc),leaf:qc}),We(["granted","received","all"])),Gc=(Me({direction:zc.optional(),path:Ve().optional(),actions:Fe(Ve()).optional(),includeRevoked:Be().optional(),delegator:Ve().optional(),delegatee:Ve().optional(),validAt:ze().optional(),limit:$e().optional(),cursor:Ve().optional()}),We(["owned","delegated"])),Jc=(Me({id:Ve(),name:Ve().optional(),owner:Ve(),type:Gc,permissions:Fe(Ve()).optional(),expiresAt:ze().optional()}),We(["base64","compact","ipfs"]));Me({token:Ve(),url:Ve(),delegation:qc,schema:Jc,expiresAt:ze().optional(),description:Ve().optional()}),function(e){Me({data:e,delegation:qc,spaceId:Ve(),path:Ve()})}(qe()),Me({persist:Be().optional(),validateChain:Be().optional(),keyName:Ve().optional(),createSessionKey:Be().optional(),priority:$e().optional()}),Me({includePlacement:Be().optional(),path:Ve().optional(),actions:Fe(Ve()).optional(),resources:Fe(Me({path:Ve(),actions:Fe(Ve()).optional()})).optional(),expiry:ze().optional(),schema:Jc.optional(),description:Ve().optional(),baseUrl:Ve().optional(),allowSubDelegation:Be().optional()}),Me({hosts:Fe(Ve()),accountSpaceId:Ve().min(1).optional(),session:qe().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),invoke:qe().refine(e=>"function"==typeof e,{message:"Expected an invoke function"}),invokeAny:qe().refine(e=>void 0===e||"function"==typeof e,{message:"Expected an invokeAny function or undefined"}).optional(),signOwnerRevocation:Ce().optional(),sessionInvocationSigner:Ce().optional(),resourceTransport:Ce().optional(),fetch:qe().refine(e=>void 0===e||"function"==typeof e,{message:"Expected a fetch function or undefined"}).optional()}),Me({createSessionKey:qe().refine(e=>"function"==typeof e,{message:"Expected a function"}),getJWK:qe().refine(e=>"function"==typeof e,{message:"Expected a function"}),getDID:qe().refine(e=>"function"==typeof e,{message:"Expected a function"})}),Me({siwe:Ve(),signature:Ve(),version:$e(),cid:Ve().optional()});var Yc=Me({service:Ve(),space:Ve(),path:Ve(),actions:Fe(Ve()),caveats:Fe(He(Ve(),qe())).optional()}),Qc=(Me({session:qe().refine(e=>null!==e&&"object"==typeof e,{message:"Expected a ServiceSession object"}),delegateDID:Ve(),spaceId:Ve(),abilities:He(Ve(),He(Ve(),Fe(Ve()))),expirationSecs:$e(),notBeforeSecs:$e().optional(),disableSubDelegation:Be().optional()}),Me({delegation:Ve(),cid:Ve(),delegateDID:Ve(),expiry:ze(),resources:Fe(Yc)}),{REVOKE:"tinycloud.delegation/revoke",STATUS:"tinycloud.delegation/status",LIST:"tinycloud.delegation/list",GET:"tinycloud.delegation/get",CHECK:"tinycloud.delegation/check"});function Xc(e,t,r,n){return{code:e,message:t,service:"delegation",cause:r,meta:n}}var eu="delegation-issued-query-v1";async function tu(e){return(await e.text()).replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,200)}var ru="space not found";async function nu(e,t,r,n){const s=n??await tu(e),i={...r,status:e.status};return 401===e.status||403===e.status?Xc(Bc.PERMISSION_DENIED,""===s?"The node refused the request":s,void 0,i):400===e.status&&s.includes("invalid delegation query cursor")?Xc(Bc.INVALID_CURSOR,"The node rejected the page cursor; list again from the start",void 0,i):503===e.status?Xc(Bc.CHAIN_TOO_DEEP,"This delegation chain is too long for the node to check right now; try again later",void 0,{...i,retryable:!0}):Xc(Bc.NETWORK_ERROR,`${t}: ${e.status} - ${s}`,void 0,i)}var su=class extends Error{};function iu(){return{ok:!1,error:Xc(Bc.UNSUPPORTED_OPERATION,"This node doesn't support listing issued delegations yet",void 0,{feature:eu})}}async function au(e,t){const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:Xc(Bc.NOT_INITIALIZED,"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:Xc(Bc.INVALID_INPUT,"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`]:{[Qc.LIST]:[{}]}},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(eu))throw new su;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:Xc(Bc.NETWORK_ERROR,`Couldn't read the node's info: ${t.status}`,void 0,{status:t.status})};const r=await t.json();return e.state.issuedQuerySupported=Array.isArray(r.features)&&r.features.includes(eu),{ok:!0,data:e.state.issuedQuerySupported}}(e);if(!t.ok)return t;if(!t.data)return iu();i=await s(e.fetchFn,e.host)}if(!i.ok)return{ok:!1,error:await nu(i,"Failed to query issued delegations",{})};const a=Wc.safeParse(await i.json());return a.success?{ok:!0,data:a.data}:{ok:!1,error:Xc(Bc.INVALID_TOKEN,"Node returned an invalid delegation query response")}}catch(e){return Hi(e)?{ok:!1,error:{...ha("delegation",e),service:"delegation"}}:e instanceof su?iu():{ok:!1,error:Xc(Bc.NETWORK_ERROR,`Network error during delegation query: ${String(e)}`,e instanceof Error?e:void 0)}}}async function ou(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:Xc(Bc.INVALID_INPUT,"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:Xc(Bc.INVALID_TOKEN,"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 cu(e,t){if(!t)return{ok:!1,error:Xc(Bc.INVALID_INPUT,"cid is required")};const r=e.sessionInvocationSigner;if(!r)return{ok:!1,error:Xc(Bc.NOT_INITIALIZED,"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}`]:{[Qc.REVOKE]:[{}]}},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 tu(s);return{ok:!1,error:e.toLowerCase()===ru?Xc(Bc.NOT_FOUND,`Delegation not found: ${t}`,void 0,{cid:t,status:404}):await nu(s,"Failed to revoke delegation",{cid:t},e)}}return{ok:!1,error:await nu(s,"Failed to revoke delegation",{cid:t})}}const i=Mc.safeParse(await s.json());return i.success&&i.data.cid===t?{ok:!0,data:i.data}:{ok:!1,error:Xc(Bc.REVOCATION_FAILED,"Node returned an invalid delegation revocation receipt",void 0,{cid:t})}}catch(e){return Hi(e)?{ok:!1,error:{...ha("delegation",e),service:"delegation"}}:{ok:!1,error:Xc(Bc.NETWORK_ERROR,`Network error during delegation revocation: ${String(e)}`,e instanceof Error?e:void 0)}}}module.exports=i})();
|