@dvmkit/dvmctl 0.3.0-rc.1 → 0.3.2-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/dvmctl.js +11 -11
- package/package.json +1 -1
package/dist/dvmctl.js
CHANGED
|
@@ -22,7 +22,7 @@ Expecting one of '${allowedValues.join("', '")}'`)}if(this._lifeCycleHooks[event
|
|
|
22
22
|
`)}else if(this._showHelpAfterError){this._outputConfiguration.writeErr("\n");this.outputHelp({error:true})}const config2=errorOptions||{};const exitCode=config2.exitCode||1;const code=config2.code||"commander.error";this._exit(exitCode,code,message2)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process3.env){const optionKey=option.attributeName();if(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey))){if(option.required||option.optional){this.emit(`optionEnv:${option.name()}`,process3.env[option.envVar])}else{this.emit(`optionEnv:${option.name()}`)}}}})}_parseOptionsImplied(){const dualHelper=new DualOptions(this.options);const hasCustomOptionValue=optionKey=>{return this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey))};this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){const message2=`error: missing required argument '${name}'`;this.error(message2,{code:"commander.missingArgument"})}optionMissingArgument(option){const message2=`error: option '${option.flags}' argument missing`;this.error(message2,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){const message2=`error: required option '${option.flags}' not specified`;this.error(message2,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){const findBestOptionFromValue=option2=>{const optionKey=option2.attributeName();const optionValue=this.getOptionValue(optionKey);const negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName());const positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());if(negativeOption&&(negativeOption.presetArg===void 0&&optionValue===false||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)){return negativeOption}return positiveOption||option2};const getErrorMessage=option2=>{const bestOption=findBestOptionFromValue(option2);const optionKey=bestOption.attributeName();const source=this.getOptionValueSource(optionKey);if(source==="env"){return`environment variable '${bestOption.envVar}'`}return`option '${bestOption.flags}'`};const message2=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message2,{code:"commander.conflictingOption"})}unknownOption(flag){if(this._allowUnknownOption)return;let suggestion="";if(flag.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[];let command=this;do{const moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags);command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag,candidateFlags)}const message2=`error: unknown option '${flag}'${suggestion}`;this.error(message2,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;const expected=this.registeredArguments.length;const s=expected===1?"":"s";const forSubcommand=this.parent?` for '${this.name()}'`:"";const message2=`error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message2,{code:"commander.excessArguments"})}unknownCommand(){const unknownName=this.args[0];let suggestion="";if(this._showSuggestionAfterError){const candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name());if(command.alias())candidateNames.push(command.alias())});suggestion=suggestSimilar(unknownName,candidateNames)}const message2=`error: unknown command '${unknownName}'${suggestion}`;this.error(message2,{code:"commander.unknownCommand"})}version(str2,flags,description){if(str2===void 0)return this._version;this._version=str2;flags=flags||"-V, --version";description=description||"output the version number";const versionOption=this.createOption(flags,description);this._versionOptionName=versionOption.attributeName();this._registerOption(versionOption);this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str2}
|
|
23
23
|
`);this._exit(0,"commander.version",str2)});return this}description(str2,argsDescription){if(str2===void 0&&argsDescription===void 0)return this._description;this._description=str2;if(argsDescription){this._argsDescription=argsDescription}return this}summary(str2){if(str2===void 0)return this._summary;this._summary=str2;return this}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler){command=this.commands[this.commands.length-1]}if(alias===command._name)throw new Error("Command alias can't be the same as its name");const matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){const existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}command._aliases.push(alias);return this}aliases(aliases){if(aliases===void 0)return this._aliases;aliases.forEach(alias=>this.alias(alias));return this}usage(str2){if(str2===void 0){if(this._usage)return this._usage;const args=this.registeredArguments.map(arg=>{return humanReadableArgName(arg)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}this._usage=str2;return this}name(str2){if(str2===void 0)return this._name;this._name=str2;return this}helpGroup(heading){if(heading===void 0)return this._helpGroupHeading??"";this._helpGroupHeading=heading;return this}commandsGroup(heading){if(heading===void 0)return this._defaultCommandGroup??"";this._defaultCommandGroup=heading;return this}optionsGroup(heading){if(heading===void 0)return this._defaultOptionGroup??"";this._defaultOptionGroup=heading;return this}_initOptionGroup(option){if(this._defaultOptionGroup&&!option.helpGroupHeading)option.helpGroup(this._defaultOptionGroup)}_initCommandGroup(cmd){if(this._defaultCommandGroup&&!cmd.helpGroup())cmd.helpGroup(this._defaultCommandGroup)}nameFromFilename(filename){this._name=path.basename(filename,path.extname(filename));return this}executableDir(path2){if(path2===void 0)return this._executableDir;this._executableDir=path2;return this}helpInformation(contextOptions){const helper=this.createHelp();const context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});const text=helper.formatHelp(this,helper);if(context.hasColors)return text;return this._outputConfiguration.stripColor(text)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};const error51=!!contextOptions.error;let baseWrite;let hasColors;let helpWidth;if(error51){baseWrite=str2=>this._outputConfiguration.writeErr(str2);hasColors=this._outputConfiguration.getErrHasColors();helpWidth=this._outputConfiguration.getErrHelpWidth()}else{baseWrite=str2=>this._outputConfiguration.writeOut(str2);hasColors=this._outputConfiguration.getOutHasColors();helpWidth=this._outputConfiguration.getOutHelpWidth()}const write=str2=>{if(!hasColors)str2=this._outputConfiguration.stripColor(str2);return baseWrite(str2)};return{error:error51,write,hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;if(typeof contextOptions==="function"){deprecatedCallback=contextOptions;contextOptions=void 0}const outputContext=this._getOutputContext(contextOptions);const eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext));this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback){helpInformation=deprecatedCallback(helpInformation);if(typeof helpInformation!=="string"&&!Buffer.isBuffer(helpInformation)){throw new Error("outputHelp callback must return a string or a Buffer")}}outputContext.write(helpInformation);if(this._getHelpOption()?.long){this.emit(this._getHelpOption().long)}this.emit("afterHelp",eventContext);this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){if(typeof flags==="boolean"){if(flags){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup){this._initOptionGroup(this._getHelpOption())}}else{this._helpOption=null}return this}this._helpOption=this.createOption(flags??"-h, --help",description??"display help for command");if(flags||description)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0){this.helpOption(void 0,void 0)}return this._helpOption}addHelpOption(option){this._helpOption=option;this._initOptionGroup(option);return this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process3.exitCode??0);if(exitCode===0&&contextOptions&&typeof contextOptions!=="function"&&contextOptions.error){exitCode=1}this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text){const allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position)){throw new Error(`Unexpected value for position to addHelpText.
|
|
24
24
|
Expecting one of '${allowedValues.join("', '")}'`)}const helpEvent=`${position}Help`;this.on(helpEvent,context=>{let helpStr;if(typeof text==="function"){helpStr=text({error:context.error,command:context.command})}else{helpStr=text}if(helpStr){context.write(`${helpStr}
|
|
25
|
-
`)}});return this}_outputHelpIfRequested(args){const helpOption=this._getHelpOption();const helpRequested=helpOption&&args.find(arg=>helpOption.is(arg));if(helpRequested){this.outputHelp();this._exit(0,"commander.helpDisplayed","(outputHelp)")}}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect")){return arg}let debugOption;let debugHost="127.0.0.1";let debugPort="9229";let match;if((match=arg.match(/^(--inspect(-brk)?)$/))!==null){debugOption=match[1]}else if((match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null){debugOption=match[1];if(/^\d+$/.test(match[3])){debugPort=match[3]}else{debugHost=match[3]}}else if((match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null){debugOption=match[1];debugHost=match[3];debugPort=match[4]}if(debugOption&&debugPort!=="0"){return`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`}return arg})}function useColor(){if(process3.env.NO_COLOR||process3.env.FORCE_COLOR==="0"||process3.env.FORCE_COLOR==="false")return false;if(process3.env.FORCE_COLOR||process3.env.CLICOLOR_FORCE!==void 0)return true;return void 0}exports.Command=Command2;exports.useColor=useColor}});var require_commander=__commonJS({"node_modules/commander/index.js"(exports){"use strict";var{Argument:Argument2}=require_argument();var{Command:Command2}=require_command();var{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error();var{Help:Help2}=require_help();var{Option:Option2}=require_option();exports.program=new Command2;exports.createCommand=name=>new Command2(name);exports.createOption=(flags,description)=>new Option2(flags,description);exports.createArgument=(name,description)=>new Argument2(name,description);exports.Command=Command2;exports.Option=Option2;exports.Argument=Argument2;exports.Help=Help2;exports.CommanderError=CommanderError2;exports.InvalidArgumentError=InvalidArgumentError2;exports.InvalidOptionArgumentError=InvalidArgumentError2}});import{writeSync}from"fs";function setOutputTraceId(id){_traceId=id}function json(data){const out=_traceId!==null&&typeof data==="object"&&data!==null&&!Array.isArray(data)&&!("trace_id"in data)?{trace_id:_traceId,...data}:data;writeAllSync(1,JSON.stringify(out)+"\n")}function info(msg){writeAllSync(2,msg+"\n")}function raw(msg){writeAllSync(1,msg+"\n")}function progress(event){writeAllSync(2,JSON.stringify(event)+"\n")}function writeAllSync(fd,text){const buf=Buffer.from(text,"utf8");let offset=0;while(offset<buf.length){try{offset+=writeSync(fd,buf,offset,buf.length-offset)}catch(err){const code=err.code;if(code==="EAGAIN"||code==="EINTR")continue;throw err}}}var _traceId;var init_output=__esm({"src/shared/output.ts"(){"use strict";_traceId=null}});function parseTraceparent(header){if(!header)return null;const match=TRACEPARENT_RE.exec(header.trim());if(!match)return null;const[,traceId,parentSpanId,flagsHex]=match;if(traceId===ALL_ZERO_TRACE||parentSpanId===ALL_ZERO_SPAN)return null;return{traceId,parentSpanId,flags:parseInt(flagsHex,16)}}var TRACEPARENT_RE,ALL_ZERO_TRACE,ALL_ZERO_SPAN;var init_traceparent=__esm({"src/shared/traceparent.ts"(){"use strict";TRACEPARENT_RE=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;ALL_ZERO_TRACE="00000000000000000000000000000000";ALL_ZERO_SPAN="0000000000000000"}});function dvmFetch(input,init2){return globalThis.fetch(input,withDecodableAcceptEncoding(input,init2))}function installGlobalAcceptEncoding(){const current=globalThis.fetch;if(current.__dvmkitAcceptEncodingPatched)return;const wrapper=((input,init2)=>nativeFetch(input,withDecodableAcceptEncoding(input,init2)));wrapper.__dvmkitAcceptEncodingPatched=true;globalThis.fetch=wrapper}function withDecodableAcceptEncoding(input,init2){const source=init2?.headers??(input instanceof Request?input.headers:void 0);if(source instanceof Headers||Array.isArray(source)){const headers=new Headers(source);if(!headers.has("accept-encoding")){headers.set("accept-encoding",DECODABLE_ACCEPT_ENCODING)}return{...init2,headers}}const record2={...source};if(!Object.keys(record2).some(name=>name.toLowerCase()==="accept-encoding")){record2["Accept-Encoding"]=DECODABLE_ACCEPT_ENCODING}return{...init2,headers:record2}}var DECODABLE_ACCEPT_ENCODING,nativeFetch;var init_http=__esm({"src/lib/http.ts"(){"use strict";DECODABLE_ACCEPT_ENCODING="gzip, deflate, br";nativeFetch=globalThis.fetch}});var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports,module){"use strict";var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module){"use strict";var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat3(list2,totalLength){if(list2.length===0)return EMPTY_BUFFER;if(list2.length===1)return list2[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list2.length;i++){const buf=list2[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer2(data){toBuffer2.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer2.readOnly=false}return buf}module.exports={concat:concat3,mask:_mask,toArrayBuffer,toBuffer:toBuffer2,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=__require("bufferutil");module.exports.mask=function(source,mask,output,offset,length){if(length<48)_mask(source,mask,output,offset,length);else bufferUtil.mask(source,mask,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e17){}}}});var require_limiter=__commonJS({"node_modules/ws/lib/limiter.js"(exports,module){"use strict";var kDone=Symbol("kDone");var kRun=Symbol("kRun");var Limiter=class{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}};module.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module){"use strict";var zlib=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;var PerMessageDeflate2=class{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==void 0?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find(params=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&!params.client_max_window_bits){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data2)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data2)})}};module.exports=PerMessageDeflate2;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007;this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module){"use strict";var{isUtf8}=__require("buffer");var{hasBlob}=require_constants();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=__require("utf-8-validate");module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e17){}}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream");var PerMessageDeflate2=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat:concat3,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;var Receiver2=class extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=void 0;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=void 0;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error51=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error51);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate2.extensionName]){const error51=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error51);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error51=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error51);return}if(!this._fragmented){const error51=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error51);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error51=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error51);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error51=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error51);return}if(compressed){const error51=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error51);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error51=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error51);return}}else{const error51=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error51);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error51=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error51);return}}else if(this._masked){const error51=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error51);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error51=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error51);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error51=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error51);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const error51=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error51);return}this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error51=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error51);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const error51=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error51);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat3(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat3(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat3(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error51=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error51);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error51=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error51);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error51=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error51);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message2,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message2}`:message2);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}};module.exports=Receiver2}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports,module){"use strict";var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate2=require_permessage_deflate();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer:toBuffer2}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;var Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=void 0}static frame(data,options){let mask;let merge3=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===void 0){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==void 0){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge3=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge3?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge3){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===void 0){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===void 0||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(_Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer2(data);byteLength=data.length;readOnly=toBuffer2.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer2(data);byteLength=data.length;readOnly=toBuffer2.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer2(data);byteLength=data.length;readOnly=toBuffer2.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then(arrayBuffer=>{if(this._socket.destroyed){const err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer2(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(_Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch(err=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(_Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list2,cb){if(list2.length===2){this._socket.cork();this._socket.write(list2[0]);this._socket.write(list2[1],cb);this._socket.uncork()}else{this._socket.write(list2[0],cb)}}};module.exports=Sender2;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb);sender.onerror(err)}}});var require_event_target=__commonJS({"node_modules/ws/lib/event-target.js"(exports,module){"use strict";var{kForOnEventAttribute,kListener}=require_constants();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");var Event=class{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}};Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});var CloseEvent=class extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===void 0?0:options.code;this[kReason]=options.reason===void 0?"":options.reason;this[kWasClean]=options.wasClean===void 0?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}};Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});var ErrorEvent=class extends Event{constructor(type,options={}){super(type);this[kError]=options.error===void 0?null:options.error;this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}};Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});var MessageEvent=class extends Event{constructor(type,options={}){super(type);this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}};Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message2){const event=new CloseEvent("close",{code,reason:message2.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error51){const event=new ErrorEvent("error",{error:error51,message:error51.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}}});var require_extension=__commonJS({"node_modules/ws/lib/extension.js"(exports,module){"use strict";var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===void 0)dest[name]=[elem];else dest[name].push(elem)}function parse3(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}paramName=void 0;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===void 0){push(offers,token,params)}else{if(paramName===void 0){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).map(extension2=>{let configurations=extensions[extension2];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map(params=>{return[extension2].concat(Object.keys(params).map(k2=>{let values=params[k2];if(!Array.isArray(values))values=[values];return values.map(v=>v===true?k2:`${k2}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse:parse3}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter2=__require("events");var https=__require("https");var http=__require("http");var net=__require("net");var tls=__require("tls");var{randomBytes:randomBytes5,createHash:createHash2}=__require("crypto");var{Duplex,Readable}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate2=require_permessage_deflate();var Receiver2=require_receiver();var Sender2=require_sender();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse:parse3}=require_extension();var{toBuffer:toBuffer2}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var WebSocket3=class _WebSocket extends EventEmitter2{constructor(address3,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=_WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address3!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===void 0){protocols=[]}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;protocols=[]}else{protocols=[protocols]}}initAsClient(this,address3,protocols,options)}else{this._autoPong=options.autoPong;this._closeTimeout=options.closeTimeout;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=_WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate2.extensionName]){this._extensions[PerMessageDeflate2.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===_WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=_WebSocket.CLOSING;this._sender.close(code,data,!this._isServer,err=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});setCloseTimer(this)}pause(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate2.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=_WebSocket.CLOSING;this._socket.destroy()}}};Object.defineProperty(WebSocket3,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket3.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket3.prototype,property,{enumerable:true})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket3.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket3.prototype.addEventListener=addEventListener;WebSocket3.prototype.removeEventListener=removeEventListener;module.exports=WebSocket3;function initAsClient(websocket,address3,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};websocket._autoPong=opts.autoPong;websocket._closeTimeout=opts.closeTimeout;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address3 instanceof URL2){parsedUrl=address3}else{try{parsedUrl=new URL2(address3)}catch{throw new SyntaxError(`Invalid URL: ${address3}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol="ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes5(16).toString("base64");const request=isSecure?https.request:http.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key2,value]of Object.entries(headers)){options.headers[key2.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=void 0}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",err=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",res=>{const location=res.headers.location;const statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address3)}catch(e17){const err=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket3.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash2("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==void 0){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){const message2="Server sent a Sec-WebSocket-Extensions header but no extension was requested";abortHandshake(websocket,socket,message2);return}let extensions;try{extensions=parse3(secWebSocketExtensions)}catch(err){const message2="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message2);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){const message2="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message2);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch(err){const message2="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message2);return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket3.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=void 0;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message2){websocket._readyState=WebSocket3.CLOSING;const err=new Error(message2);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer2(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===void 0)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume2,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==void 0){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume2,websocket._socket);websocket.close(err[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume2(stream){stream.resume()}function senderOnError(err){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket3.CLOSED)return;if(websocket.readyState===WebSocket3.OPEN){websocket._readyState=WebSocket3.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket3.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=void 0;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket3.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket3.CLOSING;this.destroy()}}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket3=require_websocket();var{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream2(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message2(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error51(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error51(err2){called=true;callback(err2)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse3(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol2=header.slice(start,end);if(protocols.has(protocol2)){throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`)}protocols.add(protocol2);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse:parse3}}});var require_websocket_server=__commonJS({"node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter2=__require("events");var http=__require("http");var{Duplex}=__require("stream");var{createHash:createHash2}=__require("crypto");var extension2=require_extension();var PerMessageDeflate2=require_permessage_deflate();var subprotocol2=require_subprotocol();var WebSocket3=require_websocket();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;var WebSocketServer2=class extends EventEmitter2{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket3,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified')}if(options.port!=null){this._server=http.createServer((req,res)=>{const body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version4=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message2="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message2);return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){const message2="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2);return}if(key===void 0||!keyRegex.test(key)){const message2="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2);return}if(version4!==13&&version4!==8){const message2="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==void 0){try{protocols=subprotocol2.parse(secWebSocketProtocol)}catch(err){const message2="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){const perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension2.parse(secWebSocketExtensions);if(offers[PerMessageDeflate2.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}}catch(err){const message2="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2);return}}if(this.options.verifyClient){const info2={origin:req.headers[`${version4===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info2,(verified,code,message2,headers)=>{if(!verified){return abortHandshake(socket,code||401,message2,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info2))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash2("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate2.extensionName]){const params=extensions[PerMessageDeflate2.extensionName].params;const value=extension2.format({[PerMessageDeflate2.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat("\r\n").join("\r\n"));socket.removeListener("error",socketOnError);ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws);ws.on("close",()=>{this.clients.delete(ws);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws,req)}};module.exports=WebSocketServer2;function addListeners(server,map2){for(const event of Object.keys(map2))server.on(event,map2[event]);return function removeListeners(){for(const event of Object.keys(map2)){server.removeListener(event,map2[event])}}}function emitClose(server){server._state=CLOSED;server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message2,headers){message2=message2||http.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message2),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
25
|
+
`)}});return this}_outputHelpIfRequested(args){const helpOption=this._getHelpOption();const helpRequested=helpOption&&args.find(arg=>helpOption.is(arg));if(helpRequested){this.outputHelp();this._exit(0,"commander.helpDisplayed","(outputHelp)")}}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect")){return arg}let debugOption;let debugHost="127.0.0.1";let debugPort="9229";let match;if((match=arg.match(/^(--inspect(-brk)?)$/))!==null){debugOption=match[1]}else if((match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null){debugOption=match[1];if(/^\d+$/.test(match[3])){debugPort=match[3]}else{debugHost=match[3]}}else if((match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null){debugOption=match[1];debugHost=match[3];debugPort=match[4]}if(debugOption&&debugPort!=="0"){return`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`}return arg})}function useColor(){if(process3.env.NO_COLOR||process3.env.FORCE_COLOR==="0"||process3.env.FORCE_COLOR==="false")return false;if(process3.env.FORCE_COLOR||process3.env.CLICOLOR_FORCE!==void 0)return true;return void 0}exports.Command=Command2;exports.useColor=useColor}});var require_commander=__commonJS({"node_modules/commander/index.js"(exports){"use strict";var{Argument:Argument2}=require_argument();var{Command:Command2}=require_command();var{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error();var{Help:Help2}=require_help();var{Option:Option2}=require_option();exports.program=new Command2;exports.createCommand=name=>new Command2(name);exports.createOption=(flags,description)=>new Option2(flags,description);exports.createArgument=(name,description)=>new Argument2(name,description);exports.Command=Command2;exports.Option=Option2;exports.Argument=Argument2;exports.Help=Help2;exports.CommanderError=CommanderError2;exports.InvalidArgumentError=InvalidArgumentError2;exports.InvalidOptionArgumentError=InvalidArgumentError2}});import{writeSync}from"fs";function setOutputTraceId(id){_traceId=id}function json(data){const out=_traceId!==null&&typeof data==="object"&&data!==null&&!Array.isArray(data)&&!("trace_id"in data)?{trace_id:_traceId,...data}:data;writeAllSync(1,JSON.stringify(out)+"\n")}function info(msg){writeAllSync(2,msg+"\n")}function raw(msg){writeAllSync(1,msg+"\n")}function progress(event){writeAllSync(2,JSON.stringify(event)+"\n")}function writeAllSync(fd,text){const buf=Buffer.from(text,"utf8");let offset=0;while(offset<buf.length){try{offset+=writeSync(fd,buf,offset,buf.length-offset)}catch(err){const code=err.code;if(code==="EAGAIN"||code==="EINTR")continue;throw err}}}var _traceId;var init_output=__esm({"src/shared/output.ts"(){"use strict";_traceId=null}});function parseTraceparent(header){if(!header)return null;const match=TRACEPARENT_RE.exec(header.trim());if(!match)return null;const[,traceId,parentSpanId,flagsHex]=match;if(traceId===ALL_ZERO_TRACE||parentSpanId===ALL_ZERO_SPAN)return null;return{traceId,parentSpanId,flags:parseInt(flagsHex,16)}}var TRACEPARENT_RE,ALL_ZERO_TRACE,ALL_ZERO_SPAN;var init_traceparent=__esm({"src/shared/traceparent.ts"(){"use strict";TRACEPARENT_RE=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;ALL_ZERO_TRACE="00000000000000000000000000000000";ALL_ZERO_SPAN="0000000000000000"}});function dvmFetch(input,init2){return globalThis.fetch(input,withDecodableAcceptEncoding(input,init2))}function installGlobalAcceptEncoding(){const current=globalThis.fetch;if(current.__dvmkitAcceptEncodingPatched)return;const wrapper=((input,init2)=>nativeFetch(input,withDecodableAcceptEncoding(input,init2)));wrapper.__dvmkitAcceptEncodingPatched=true;globalThis.fetch=wrapper}function withDecodableAcceptEncoding(input,init2){const source=init2?.headers??(input instanceof Request?input.headers:void 0);if(source instanceof Headers||Array.isArray(source)){const headers=new Headers(source);if(!headers.has("accept-encoding")){headers.set("accept-encoding",DECODABLE_ACCEPT_ENCODING)}return{...init2,headers}}const record2={...source};if(!Object.keys(record2).some(name=>name.toLowerCase()==="accept-encoding")){record2["Accept-Encoding"]=DECODABLE_ACCEPT_ENCODING}return{...init2,headers:record2}}var DECODABLE_ACCEPT_ENCODING,nativeFetch;var init_http=__esm({"src/lib/http.ts"(){"use strict";DECODABLE_ACCEPT_ENCODING="gzip, deflate, br";nativeFetch=globalThis.fetch}});var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports,module){"use strict";var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module){"use strict";var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat3(list2,totalLength){if(list2.length===0)return EMPTY_BUFFER;if(list2.length===1)return list2[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list2.length;i++){const buf=list2[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer2(data){toBuffer2.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer2.readOnly=false}return buf}module.exports={concat:concat3,mask:_mask,toArrayBuffer,toBuffer:toBuffer2,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=__require("bufferutil");module.exports.mask=function(source,mask,output,offset,length){if(length<48)_mask(source,mask,output,offset,length);else bufferUtil.mask(source,mask,output,offset,length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e17){}}}});var require_limiter=__commonJS({"node_modules/ws/lib/limiter.js"(exports,module){"use strict";var kDone=Symbol("kDone");var kRun=Symbol("kRun");var Limiter=class{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}};module.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module){"use strict";var zlib=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("error");var zlibLimiter;var PerMessageDeflate2=class{constructor(options){this._options=options||{};this._threshold=this._options.threshold!==void 0?this._options.threshold:1024;this._maxPayload=this._options.maxPayload|0;this._isServer=!!this._options.isServer;this._deflate=null;this._inflate=null;this.params=null;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"permessage-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.find(params=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&!params.client_max_window_bits){return false}return true});if(!accepted){throw new Error("None of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this._inflate=null;callback(err);return}const data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data2)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data2=new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data2)})}};module.exports=PerMessageDeflate2;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007;this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module){"use strict";var{isUtf8}=__require("buffer");var{hasBlob}=require_constants();var tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function isValidStatusCode(code){return code>=1e3&&code<=1014&&code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=__require("utf-8-validate");module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e17){}}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream");var PerMessageDeflate2=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat:concat3,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;var INFLATING=5;var DEFER_EVENT=6;var Receiver2=class extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.skipUTF8Validation;this[kWebSocket]=void 0;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=void 0;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error51=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error51);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate2.extensionName]){const error51=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error51);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error51=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error51);return}if(!this._fragmented){const error51=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error51);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const error51=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error51);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error51=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error51);return}if(compressed){const error51=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error51);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const error51=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error51);return}}else{const error51=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error51);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error51=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error51);return}}else if(this._masked){const error51=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error51);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error51=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error51);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this._payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error51=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error51);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const error51=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error51);return}this._messageLength=this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error51=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error51);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const error51=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error51);return}this._fragments.push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat3(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat3(fragments,messageLength))}else if(this._binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat3(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error51=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error51);return}if(this._state===INFLATING||this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error51=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");cb(error51);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error51=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error51);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message2,prefix,statusCode,errorCode2){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message2}`:message2);Error.captureStackTrace(err,this.createError);err.code=errorCode2;err[kStatusCode]=statusCode;return err}};module.exports=Receiver2}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports,module){"use strict";var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate2=require_permessage_deflate();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer:toBuffer2}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;var Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=void 0}static frame(data,options){let mask;let merge3=false;let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===void 0){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==void 0){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge3=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge3?dataLength+offset:offset);target[0]=options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge3){applyMask(data,mask,target,offset,dataLength);return[target]}applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===void 0){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===void 0||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(_Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer2(data);byteLength=data.length;readOnly=toBuffer2.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer2(data);byteLength=data.length;readOnly=toBuffer2.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}send(data,options,cb){const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer2(data);byteLength=data.length;readOnly=toBuffer2.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then(arrayBuffer=>{if(this._socket.destroyed){const err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer2(arrayBuffer);if(!compress){this._state=DEFAULT;this.sendFrame(_Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch(err=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){const err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(_Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];this._queue.push(params)}sendFrame(list2,cb){if(list2.length===2){this._socket.cork();this._socket.write(list2[0]);this._socket.write(list2[1],cb);this._socket.uncork()}else{this._socket.write(list2[0],cb)}}};module.exports=Sender2;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(sender,err,cb);sender.onerror(err)}}});var require_event_target=__commonJS({"node_modules/ws/lib/event-target.js"(exports,module){"use strict";var{kForOnEventAttribute,kListener}=require_constants();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");var Event=class{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){return this[kType]}};Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});var CloseEvent=class extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===void 0?0:options.code;this[kReason]=options.reason===void 0?"":options.reason;this[kWasClean]=options.wasClean===void 0?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}};Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});var ErrorEvent=class extends Event{constructor(type,options={}){super(type);this[kError]=options.error===void 0?null:options.error;this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}};Object.defineProperty(ErrorEvent.prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});var MessageEvent=class extends Event{constructor(type,options={}){super(type);this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}};Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message2){const event=new CloseEvent("close",{code,reason:message2.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="error"){wrapper=function onError(error51){const event=new ErrorEvent("error",{error:error51,message:error51.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}}});var require_extension=__commonJS({"node_modules/ws/lib/extension.js"(exports,module){"use strict";var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===void 0)dest[name]=[elem];else dest[name].push(elem)}function parse3(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(i);if(extensionName===void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}paramName=void 0;start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===void 0){push(offers,token,params)}else{if(paramName===void 0){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).map(extension2=>{let configurations=extensions[extension2];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map(params=>{return[extension2].concat(Object.keys(params).map(k2=>{let values=params[k2];if(!Array.isArray(values))values=[values];return values.map(v=>v===true?k2:`${k2}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse:parse3}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter2=__require("events");var https=__require("https");var http=__require("http");var net=__require("net");var tls=__require("tls");var{randomBytes:randomBytes5,createHash:createHash2}=__require("crypto");var{Duplex,Readable}=__require("stream");var{URL:URL2}=__require("url");var PerMessageDeflate2=require_permessage_deflate();var Receiver2=require_receiver();var Sender2=require_sender();var{isBlob}=require_validation();var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse:parse3}=require_extension();var{toBuffer:toBuffer2}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var WebSocket3=class _WebSocket extends EventEmitter2{constructor(address3,protocols,options){super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=_WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address3!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===void 0){protocols=[]}else if(!Array.isArray(protocols)){if(typeof protocols==="object"&&protocols!==null){options=protocols;protocols=[]}else{protocols=[protocols]}}initAsClient(this,address3,protocols,options)}else{this._autoPong=options.autoPong;this._closeTimeout=options.closeTimeout;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(socket,head,options){const receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=_WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate2.extensionName]){this._extensions[PerMessageDeflate2.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this.readyState===_WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=_WebSocket.CLOSING;this._sender.close(code,data,!this._isServer,err=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});setCloseTimer(this)}pause(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.ping(data||EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===_WebSocket.CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this._isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate2.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=_WebSocket.CLOSING;this._socket.destroy()}}};Object.defineProperty(WebSocket3,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket3,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket3,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3.prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket3,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket3.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket3.prototype,property,{enumerable:true})});["open","error","close","message"].forEach(method=>{Object.defineProperty(WebSocket3.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket3.prototype.addEventListener=addEventListener;WebSocket3.prototype.removeEventListener=removeEventListener;module.exports=WebSocket3;function initAsClient(websocket,address3,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};websocket._autoPong=opts.autoPong;websocket._closeTimeout=opts.closeTimeout;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address3 instanceof URL2){parsedUrl=address3}else{try{parsedUrl=new URL2(address3)}catch{throw new SyntaxError(`Invalid URL: ${address3}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol="ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="The URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes5(16).toString("base64");const request=isSecure?https.request:http.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort;opts.port=parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Sec-WebSocket-Extensions"]=format({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){for(const[key2,value]of Object.entries(headers)){options.headers[key2.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=void 0}}if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",err=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("response",res=>{const location=res.headers.location;const statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL2(location,address3)}catch(e17){const err=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpected-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket3.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash2("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websocket-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==void 0){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){const message2="Server sent a Sec-WebSocket-Extensions header but no extension was requested";abortHandshake(websocket,socket,message2);return}let extensions;try{extensions=parse3(secWebSocketExtensions)}catch(err){const message2="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message2);return}const extensionNames=Object.keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){const message2="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message2);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch(err){const message2="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message2);return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket3.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=void 0;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message2){websocket._readyState=WebSocket3.CLOSING;const err=new Error(message2);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer2(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===void 0)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume2,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==void 0){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume2,websocket._socket);websocket.close(err[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("message",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume2(stream){stream.resume()}function senderOnError(err){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket3.CLOSED)return;if(websocket.readyState===WebSocket3.OPEN){websocket._readyState=WebSocket3.CLOSING;setCloseTimer(websocket)}this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket3.CLOSING;if(!this._readableState.endEmitted&&!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=void 0;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket3.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket3.CLOSING;this.destroy()}}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket3=require_websocket();var{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream2(ws,options){let terminateOnDestroy=true;const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message2(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error51(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error51(err2){called=true;callback(err2)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse3(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const protocol2=header.slice(start,end);if(protocols.has(protocol2)){throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`)}protocols.add(protocol2);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}module.exports={parse:parse3}}});var require_websocket_server=__commonJS({"node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter2=__require("events");var http=__require("http");var{Duplex}=__require("stream");var{createHash:createHash2}=__require("crypto");var extension2=require_extension();var PerMessageDeflate2=require_permessage_deflate();var subprotocol2=require_subprotocol();var WebSocket3=require_websocket();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;var CLOSING=1;var CLOSED=2;var WebSocketServer2=class extends EventEmitter2{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket3,...options};if(options.port==null&&!options.server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified')}if(options.port!=null){this._server=http.createServer((req,res)=>{const body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version4=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message2="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message2);return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){const message2="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2);return}if(key===void 0||!keyRegex.test(key)){const message2="Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2);return}if(version4!==13&&version4!==8){const message2="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==void 0){try{protocols=subprotocol2.parse(secWebSocketProtocol)}catch(err){const message2="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){const perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension2.parse(secWebSocketExtensions);if(offers[PerMessageDeflate2.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}}catch(err){const message2="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message2);return}}if(this.options.verifyClient){const info2={origin:req.headers[`${version4===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info2,(verified,code,message2,headers)=>{if(!verified){return abortHandshake(socket,code||401,message2,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info2))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash2("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate2.extensionName]){const params=extensions[PerMessageDeflate2.extensionName].params;const value=extension2.format({[PerMessageDeflate2.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",headers,req);socket.write(headers.concat("\r\n").join("\r\n"));socket.removeListener("error",socketOnError);ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws);ws.on("close",()=>{this.clients.delete(ws);if(this._shouldEmitClose&&!this.clients.size){process.nextTick(emitClose,this)}})}cb(ws,req)}};module.exports=WebSocketServer2;function addListeners(server,map2){for(const event of Object.keys(map2))server.on(event,map2[event]);return function removeListeners(){for(const event of Object.keys(map2)){server.removeListener(event,map2[event])}}}function emitClose(server){server._state=CLOSED;server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message2,headers){message2=message2||http.STATUS_CODES[code];headers={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message2),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
26
26
|
`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join("\r\n")+"\r\n\r\n"+message2)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message2,headers){if(server.listenerCount("wsClientError")){const err=new Error(message2);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message2,headers)}}}});var wrapper_exports={};__export(wrapper_exports,{PerMessageDeflate:()=>import_permessage_deflate.default,Receiver:()=>import_receiver.default,Sender:()=>import_sender.default,WebSocket:()=>import_websocket.default,WebSocketServer:()=>import_websocket_server.default,createWebSocketStream:()=>import_stream.default,default:()=>wrapper_default,extension:()=>import_extension.default,subprotocol:()=>import_subprotocol.default});var import_stream,import_extension,import_permessage_deflate,import_receiver,import_sender,import_subprotocol,import_websocket,import_websocket_server,wrapper_default;var init_wrapper=__esm({"node_modules/ws/wrapper.mjs"(){"use strict";import_stream=__toESM(require_stream(),1);import_extension=__toESM(require_extension(),1);import_permessage_deflate=__toESM(require_permessage_deflate(),1);import_receiver=__toESM(require_receiver(),1);import_sender=__toESM(require_sender(),1);import_subprotocol=__toESM(require_subprotocol(),1);import_websocket=__toESM(require_websocket(),1);import_websocket_server=__toESM(require_websocket_server(),1);wrapper_default=import_websocket.default}});import{homedir as homedir2}from"os";import{join as join2}from"path";var CONFIG_DIR,CONFIG_FILE,CONFIG_BACKUP_FILE,CONFIG_AUDIT_FILE,CONFIG_PINNED_FILE,JOBS_FILE,REQUEST_INTENTS_DIR,FAVORITES_FILE,MESSAGES_DIR,RECEIPTS_FILE,CREDITS_FILE,X402_CHANNELS_FILE,TEMPO_CHANNELS_FILE,FEEDBACK_NUDGES_FILE,RECOVERY_MNEMONIC_FILE,WALLET_FILE,AGENT_MNEMONIC_FILE,IDENTITIES_FILE,PAIRINGS_DIR,BUDGET_FILE,BTC_RATE_FILE,ADMIN_DIR,PROXY_STATE_FILE,BUILDER_CONFIG_DIR,BUILDER_FILE,BUILDER_MNEMONIC_FILE,LEGACY_BUILDER_MNEMONIC_FILE,BUILDER_KEY_FILE,MELT_PENDING_LOG_FILE,DRAIN_PARK_LOG_FILE,DRAIN_HOLD_STATE_FILE,MELT_SUCCESS_FILE;var init_defaults=__esm({"src/shared/defaults.ts"(){"use strict";CONFIG_DIR=process.env.DVM_CONFIG_DIR??join2(homedir2(),".dvm");CONFIG_FILE=join2(CONFIG_DIR,"config.json");CONFIG_BACKUP_FILE=join2(CONFIG_DIR,"config.json.bak");CONFIG_AUDIT_FILE=join2(CONFIG_DIR,"config-audit.jsonl");CONFIG_PINNED_FILE=join2(CONFIG_DIR,"config.json.pinned");JOBS_FILE=join2(CONFIG_DIR,"jobs.json");REQUEST_INTENTS_DIR=join2(CONFIG_DIR,"request-intents");FAVORITES_FILE=join2(CONFIG_DIR,"favorites.json");MESSAGES_DIR=join2(CONFIG_DIR,"messages");RECEIPTS_FILE=join2(CONFIG_DIR,"receipts.jsonl");CREDITS_FILE=join2(CONFIG_DIR,"credits.json");X402_CHANNELS_FILE=join2(CONFIG_DIR,"x402-channels.json");TEMPO_CHANNELS_FILE=join2(CONFIG_DIR,"tempo-channels.json");FEEDBACK_NUDGES_FILE=join2(CONFIG_DIR,"feedback-nudges.json");RECOVERY_MNEMONIC_FILE=join2(CONFIG_DIR,"recovery.mnemonic");WALLET_FILE=join2(CONFIG_DIR,"wallet.json");AGENT_MNEMONIC_FILE=join2(CONFIG_DIR,"wallet.mnemonic");IDENTITIES_FILE=join2(CONFIG_DIR,"identities.json");PAIRINGS_DIR=join2(CONFIG_DIR,"pairings");BUDGET_FILE=join2(CONFIG_DIR,"budget.json");BTC_RATE_FILE=join2(CONFIG_DIR,"btc-rate.json");ADMIN_DIR=join2(CONFIG_DIR,"admin");PROXY_STATE_FILE=join2(ADMIN_DIR,"proxy.json");BUILDER_CONFIG_DIR=process.env.DVMKIT_CONFIG_DIR??join2(homedir2(),".dvmkit");BUILDER_FILE=join2(BUILDER_CONFIG_DIR,"builder.json");BUILDER_MNEMONIC_FILE=join2(BUILDER_CONFIG_DIR,"builder.mnemonic");LEGACY_BUILDER_MNEMONIC_FILE=join2(BUILDER_CONFIG_DIR,"recovery.mnemonic");BUILDER_KEY_FILE=join2(BUILDER_CONFIG_DIR,"builder.key");MELT_PENDING_LOG_FILE=join2(BUILDER_CONFIG_DIR,"melt-pending.log");DRAIN_PARK_LOG_FILE=join2(BUILDER_CONFIG_DIR,"drain-park.log");DRAIN_HOLD_STATE_FILE=join2(BUILDER_CONFIG_DIR,"drain-hold.json");MELT_SUCCESS_FILE=join2(BUILDER_CONFIG_DIR,"melt-success.json")}});import{backupSecretFile,DvmError as DvmError4}from"@dvmkit/sdk/internal";import{chmodSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,renameSync,unlinkSync,writeFileSync as writeFileSync2}from"fs";function loadBuilderStore(){if(!existsSync2(BUILDER_FILE)){return{version:CURRENT_VERSION,dvms:{}}}const raw2=readFileSync2(BUILDER_FILE,"utf-8");let parsed;try{parsed=JSON.parse(raw2)}catch(err){throw new Error(`${BUILDER_FILE} is not valid JSON: ${err instanceof Error?err.message:String(err)}`,{cause:err})}if(typeof parsed!=="object"||parsed===null){throw new Error(`${BUILDER_FILE} is not a JSON object`)}const values=parsed;const version4=values.version;if(version4===1){return migrateV1Store(parsed)}if(version4!==CURRENT_VERSION){throw new Error(`${BUILDER_FILE} has unknown version ${String(version4)} (expected ${CURRENT_VERSION})`)}if(typeof values.dvms!=="object"||values.dvms===null){throw new Error(`${BUILDER_FILE} is missing the dvms object`)}return{version:CURRENT_VERSION,...typeof values.identity_pubkey==="string"?{identity_pubkey:values.identity_pubkey}:{},dvms:values.dvms}}function loadIdentityPubkey(){return loadBuilderStore().identity_pubkey??null}function getBuilderDvm(dvmId){return loadBuilderStore().dvms[dvmId]}function getSelfHostedBuilderDvm(handle2){return Object.values(loadBuilderStore().dvms).find(entry=>entry.self_hosted&&entry.handle===handle2)}function findBuilderDvmsByHandle(handle2){return Object.values(loadBuilderStore().dvms).filter(entry=>entry.handle===handle2)}function requireSelectedBuilderDvm(dvmId){const entry=getBuilderDvm(dvmId);if(!entry){throw new DvmError4("dvm_not_initialized",`No builder.json entry for selected DVM ${dvmId}.`,"Run `dvmctl deploy` first so this DVM's canonical_dvm_id is recorded.")}return entry}function requireBuilderDvmByHandle(handle2){const matches2=findBuilderDvmsByHandle(handle2);if(matches2.length>1){throw new DvmError4("ambiguous_dvm_handle",`${matches2.length} builder.json entries claim the handle "${handle2}".`,`Addressing a DVM by handle cannot choose between them, and either choice derives lock keys that open nothing. Candidates: ${matches2.map(entry=>entry.canonical_dvm_id).join(", ")}. Select this DVM through the platform instead, or remove the entry you no longer operate from ${BUILDER_FILE}.`)}if(matches2.length===0){throw new DvmError4("dvm_not_initialized",`No builder.json entry on this machine for "${handle2}".`,`An entry is recorded by the deploy that created the DVM, so check the handle and that you are on the machine that deployed it. For a DVM you host yourself and have never initialized here, \`dvmctl init ${handle2} --self-hosted\` records one \u2014 but never run that against a DVM already holding proofs: it mints a fresh canonical_dvm_id, and every proof locked under the old one becomes underivable.`)}return matches2[0]}function upsertBuilderDvm(dvmId,entry){if(entry.canonical_dvm_id!==dvmId){throw new Error(`Builder-store key ${dvmId} does not match canonical_dvm_id ${entry.canonical_dvm_id}`)}mkdirSync2(BUILDER_CONFIG_DIR,{recursive:true,mode:448});const store=loadBuilderStore();store.dvms[dvmId]={...entry,updated_at:new Date().toISOString()};writeBuilderStore(store)}function patchBuilderDvm(dvmId,patch){mkdirSync2(BUILDER_CONFIG_DIR,{recursive:true,mode:448});const store=loadBuilderStore();if(!Object.prototype.hasOwnProperty.call(store.dvms,dvmId)){throw new Error(`Cannot patch DVM ${dvmId}: no entry exists in ${BUILDER_FILE}. Run \`dvmctl deploy\` or \`dvmctl init --self-hosted\` first.`)}const existing=store.dvms[dvmId];const next={...existing,...patch,updated_at:new Date().toISOString()};store.dvms[dvmId]=next;writeBuilderStore(store);return next}function writeBuilderStore(store){const content=JSON.stringify(store,null,2)+"\n";backupSecretFile(BUILDER_FILE,content);const tmp=`${BUILDER_FILE}.tmp`;try{writeFileSync2(tmp,content,{mode:384});renameSync(tmp,BUILDER_FILE)}catch(err){try{unlinkSync(tmp)}catch{}throw err}try{chmodSync(BUILDER_FILE,384)}catch{}}function migrateV1Store(parsed){if(typeof parsed.dvms!=="object"||parsed.dvms===null){throw new Error(`${BUILDER_FILE} is missing the dvms object`)}const dvms={};for(const[handle2,rawEntry]of Object.entries(parsed.dvms)){if(typeof rawEntry!=="object"||rawEntry===null){throw new Error(`${BUILDER_FILE} has an invalid DVM entry for ${handle2}`)}const entry=rawEntry;const dvmId=entry.canonical_dvm_id;if(typeof dvmId!=="string"){throw new Error(`${BUILDER_FILE} has no canonical_dvm_id for ${handle2}`)}if(Object.prototype.hasOwnProperty.call(dvms,dvmId)){throw new Error(`${BUILDER_FILE} has multiple entries for canonical_dvm_id ${dvmId}`)}dvms[dvmId]={...entry,handle:handle2}}return{version:CURRENT_VERSION,...typeof parsed.identity_pubkey==="string"?{identity_pubkey:parsed.identity_pubkey}:{},dvms}}var CURRENT_VERSION;var init_builder_store=__esm({"src/shared/builder-store.ts"(){"use strict";init_defaults();CURRENT_VERSION=2}});function isBytes(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function anumber(n,title=""){if(!Number.isSafeInteger(n)||n<0){const prefix=title&&`"${title}" `;throw new Error(`${prefix}expected integer >= 0, got ${n}`)}}function abytes(value,length,title=""){const bytes=isBytes(value);const len=value?.length;const needsLen=length!==void 0;if(!bytes||needsLen&&len!==length){const prefix=title&&`"${title}" `;const ofLen=needsLen?` of length ${length}`:"";const got=bytes?`length=${len}`:`type=${typeof value}`;throw new Error(prefix+"expected Uint8Array"+ofLen+", got "+got)}return value}function aexists(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function aoutput(out,instance){abytes(out,void 0,"digestInto() output");const min=instance.outputLen;if(out.length<min){throw new Error('"digestInto() output" expected to be of length >='+min)}}function clean(...arrays){for(let i=0;i<arrays.length;i++){arrays[i].fill(0)}}function createView(arr){return new DataView(arr.buffer,arr.byteOffset,arr.byteLength)}function rotr(word,shift){return word<<32-shift|word>>>shift}function createHasher(hashCons,info2={}){const hashC=(msg,opts)=>hashCons(opts).update(msg).digest();const tmp=hashCons(void 0);hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=opts=>hashCons(opts);Object.assign(hashC,info2);return Object.freeze(hashC)}function randomBytes2(bytesLength=32){const cr=typeof globalThis==="object"?globalThis.crypto:null;if(typeof cr?.getRandomValues!=="function")throw new Error("crypto.getRandomValues must be defined");return cr.getRandomValues(new Uint8Array(bytesLength))}var oidNist;var init_utils=__esm({"node_modules/@scure/bip39/node_modules/@noble/hashes/utils.js"(){"use strict";oidNist=suffix=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,suffix])})}});function Chi(a,b2,c){return a&b2^~a&c}function Maj(a,b2,c){return a&b2^a&c^b2&c}var HashMD,SHA256_IV;var init_md=__esm({"node_modules/@scure/bip39/node_modules/@noble/hashes/_md.js"(){"use strict";init_utils();HashMD=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(blockLen,outputLen,padOffset,isLE3){this.blockLen=blockLen;this.outputLen=outputLen;this.padOffset=padOffset;this.isLE=isLE3;this.buffer=new Uint8Array(blockLen);this.view=createView(this.buffer)}update(data){aexists(this);abytes(data);const{view,buffer,blockLen}=this;const len=data.length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){const dataView=createView(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);continue}buffer.set(data.subarray(pos,pos+take),this.pos);this.pos+=take;pos+=take;if(this.pos===blockLen){this.process(view,0);this.pos=0}}this.length+=data.length;this.roundClean();return this}digestInto(out){aexists(this);aoutput(out,this);this.finished=true;const{buffer,view,blockLen,isLE:isLE3}=this;let{pos}=this;buffer[pos++]=128;clean(this.buffer.subarray(pos));if(this.padOffset>blockLen-pos){this.process(view,0);pos=0}for(let i=pos;i<blockLen;i++)buffer[i]=0;view.setBigUint64(blockLen-8,BigInt(this.length*8),isLE3);this.process(view,0);const oview=createView(out);const len=this.outputLen;if(len%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const outLen=len/4;const state=this.get();if(outLen>state.length)throw new Error("_sha2: outputLen bigger than state");for(let i=0;i<outLen;i++)oview.setUint32(4*i,state[i],isLE3)}digest(){const{buffer,outputLen}=this;this.digestInto(buffer);const res=buffer.slice(0,outputLen);this.destroy();return res}_cloneInto(to){to||=new this.constructor;to.set(...this.get());const{blockLen,buffer,length,finished,destroyed,pos}=this;to.destroyed=destroyed;to.finished=finished;to.length=length;to.pos=pos;if(length%blockLen)to.buffer.set(buffer);return to}clone(){return this._cloneInto()}};SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])}});var SHA256_K,SHA256_W,SHA2_32B,_SHA256,sha256;var init_sha2=__esm({"node_modules/@scure/bip39/node_modules/@noble/hashes/sha2.js"(){"use strict";init_md();init_utils();SHA256_K=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]);SHA256_W=new Uint32Array(64);SHA2_32B=class extends HashMD{constructor(outputLen){super(64,outputLen,8,false)}get(){const{A:A2,B:B2,C,D:D2,E:E2,F,G:G2,H:H2}=this;return[A2,B2,C,D2,E2,F,G2,H2]}set(A2,B2,C,D2,E2,F,G2,H2){this.A=A2|0;this.B=B2|0;this.C=C|0;this.D=D2|0;this.E=E2|0;this.F=F|0;this.G=G2|0;this.H=H2|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,false);for(let i=16;i<64;i++){const W15=SHA256_W[i-15];const W2=SHA256_W[i-2];const s0=rotr(W15,7)^rotr(W15,18)^W15>>>3;const s1=rotr(W2,17)^rotr(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A:A2,B:B2,C,D:D2,E:E2,F,G:G2,H:H2}=this;for(let i=0;i<64;i++){const sigma1=rotr(E2,6)^rotr(E2,11)^rotr(E2,25);const T12=H2+sigma1+Chi(E2,F,G2)+SHA256_K[i]+SHA256_W[i]|0;const sigma0=rotr(A2,2)^rotr(A2,13)^rotr(A2,22);const T2=sigma0+Maj(A2,B2,C)|0;H2=G2;G2=F;F=E2;E2=D2+T12|0;D2=C;C=B2;B2=A2;A2=T12+T2|0}A2=A2+this.A|0;B2=B2+this.B|0;C=C+this.C|0;D2=D2+this.D|0;E2=E2+this.E|0;F=F+this.F|0;G2=G2+this.G|0;H2=H2+this.H|0;this.set(A2,B2,C,D2,E2,F,G2,H2)}roundClean(){clean(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0);clean(this.buffer)}};_SHA256=class extends SHA2_32B{A=SHA256_IV[0]|0;B=SHA256_IV[1]|0;C=SHA256_IV[2]|0;D=SHA256_IV[3]|0;E=SHA256_IV[4]|0;F=SHA256_IV[5]|0;G=SHA256_IV[6]|0;H=SHA256_IV[7]|0;constructor(){super(32)}};sha256=createHasher(()=>new _SHA256,oidNist(1))}});function isBytes2(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function isArrayOf(isString,arr){if(!Array.isArray(arr))return false;if(arr.length===0)return true;if(isString){return arr.every(item=>typeof item==="string")}else{return arr.every(item=>Number.isSafeInteger(item))}}function afn(input){if(typeof input!=="function")throw new Error("function expected");return true}function astr(label,input){if(typeof input!=="string")throw new Error(`${label}: string expected`);return true}function anumber2(n){if(!Number.isSafeInteger(n))throw new Error(`invalid integer: ${n}`)}function aArr(input){if(!Array.isArray(input))throw new Error("array expected")}function astrArr(label,input){if(!isArrayOf(true,input))throw new Error(`${label}: array of strings expected`)}function anumArr(label,input){if(!isArrayOf(false,input))throw new Error(`${label}: array of numbers expected`)}function chain(...args){const id=a=>a;const wrap=(a,b2)=>c=>a(b2(c));const encode2=args.map(x2=>x2.encode).reduceRight(wrap,id);const decode2=args.map(x2=>x2.decode).reduce(wrap,id);return{encode:encode2,decode:decode2}}function alphabet(letters){const lettersA=typeof letters==="string"?letters.split(""):letters;const len=lettersA.length;astrArr("alphabet",lettersA);const indexes=new Map(lettersA.map((l,i)=>[l,i]));return{encode:digits=>{aArr(digits);return digits.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=len)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);return lettersA[i]})},decode:input=>{aArr(input);return input.map(letter=>{astr("alphabet.decode",letter);const i=indexes.get(letter);if(i===void 0)throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);return i})}}}function join3(separator=""){astr("join",separator);return{encode:from10=>{astrArr("join.decode",from10);return from10.join(separator)},decode:to=>{astr("join.decode",to);return to.split(separator)}}}function padding(bits,chr="="){anumber2(bits);astr("padding",chr);return{encode(data){astrArr("padding.encode",data);while(data.length*bits%8)data.push(chr);return data},decode(input){astrArr("padding.decode",input);let end=input.length;if(end*bits%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;end>0&&input[end-1]===chr;end--){const last=end-1;const byte=last*bits;if(byte%8===0)throw new Error("padding: invalid, string has too much padding")}return input.slice(0,end)}}}function convertRadix(data,from10,to){if(from10<2)throw new Error(`convertRadix: invalid from=${from10}, base cannot be less than 2`);if(to<2)throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);aArr(data);if(!data.length)return[];let pos=0;const res=[];const digits=Array.from(data,d=>{anumber2(d);if(d<0||d>=from10)throw new Error(`invalid integer: ${d}`);return d});const dlen=digits.length;while(true){let carry2=0;let done=true;for(let i=pos;i<dlen;i++){const digit=digits[i];const fromCarry=from10*carry2;const digitBase=fromCarry+digit;if(!Number.isSafeInteger(digitBase)||fromCarry/from10!==carry2||digitBase-digit!==fromCarry){throw new Error("convertRadix: carry overflow")}const div=digitBase/to;carry2=digitBase%to;const rounded=Math.floor(div);digits[i]=rounded;if(!Number.isSafeInteger(rounded)||rounded*to+carry2!==digitBase)throw new Error("convertRadix: carry overflow");if(!done)continue;else if(!rounded)pos=i;else done=false}res.push(carry2);if(done)break}for(let i=0;i<data.length-1&&data[i]===0;i++)res.push(0);return res.reverse()}function convertRadix2(data,from10,to,padding3){aArr(data);if(from10<=0||from10>32)throw new Error(`convertRadix2: wrong from=${from10}`);if(to<=0||to>32)throw new Error(`convertRadix2: wrong to=${to}`);if(radix2carry(from10,to)>32){throw new Error(`convertRadix2: carry overflow from=${from10} to=${to} carryBits=${radix2carry(from10,to)}`)}let carry2=0;let pos=0;const max=powers[from10];const mask=powers[to]-1;const res=[];for(const n of data){anumber2(n);if(n>=max)throw new Error(`convertRadix2: invalid data word=${n} from=${from10}`);carry2=carry2<<from10|n;if(pos+from10>32)throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from10}`);pos+=from10;for(;pos>=to;pos-=to)res.push((carry2>>pos-to&mask)>>>0);const pow3=powers[pos];if(pow3===void 0)throw new Error("invalid carry");carry2&=pow3-1}carry2=carry2<<to-pos&mask;if(!padding3&&pos>=from10)throw new Error("Excess padding");if(!padding3&&carry2>0)throw new Error(`Non-zero padding: ${carry2}`);if(padding3&&pos>0)res.push(carry2>>>0);return res}function radix(num){anumber2(num);const _256=2**8;return{encode:bytes=>{if(!isBytes2(bytes))throw new Error("radix.encode input should be Uint8Array");return convertRadix(Array.from(bytes),_256,num)},decode:digits=>{anumArr("radix.decode",digits);return Uint8Array.from(convertRadix(digits,num,_256))}}}function radix2(bits,revPadding=false){anumber2(bits);if(bits<=0||bits>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry(8,bits)>32||radix2carry(bits,8)>32)throw new Error("radix2: carry overflow");return{encode:bytes=>{if(!isBytes2(bytes))throw new Error("radix2.encode input should be Uint8Array");return convertRadix2(Array.from(bytes),8,bits,!revPadding)},decode:digits=>{anumArr("radix2.decode",digits);return Uint8Array.from(convertRadix2(digits,bits,8,revPadding))}}}function checksum(len,fn){anumber2(len);afn(fn);return{encode(data){if(!isBytes2(data))throw new Error("checksum.encode: input should be Uint8Array");const sum2=fn(data).slice(0,len);const res=new Uint8Array(data.length+len);res.set(data);res.set(sum2,data.length);return res},decode(data){if(!isBytes2(data))throw new Error("checksum.decode: input should be Uint8Array");const payload=data.slice(0,-len);const oldChecksum=data.slice(-len);const newChecksum=fn(payload).slice(0,len);for(let i=0;i<len;i++)if(newChecksum[i]!==oldChecksum[i])throw new Error("Invalid checksum");return payload}}}var gcd,radix2carry,powers,utils;var init_base=__esm({"node_modules/@scure/bip39/node_modules/@scure/base/index.js"(){"use strict";gcd=(a,b2)=>b2===0?a:gcd(b2,a%b2);radix2carry=(from10,to)=>from10+(to-gcd(from10,to));powers=(()=>{let res=[];for(let i=0;i<40;i++)res.push(2**i);return res})();utils={alphabet,chain,checksum,convertRadix,convertRadix2,radix,radix2,join:join3,padding}}});function nfkd(str2){if(typeof str2!=="string")throw new TypeError("invalid mnemonic type: "+typeof str2);return str2.normalize("NFKD")}function normalize(str2){const norm=nfkd(str2);const words=norm.split(" ");if(![12,15,18,21,24].includes(words.length))throw new Error("Invalid mnemonic");return{nfkd:norm,words}}function aentropy(ent){abytes(ent);if(![16,20,24,28,32].includes(ent.length))throw new Error("invalid entropy length")}function generateMnemonic(wordlist2,strength=128){anumber(strength);if(strength%32!==0||strength>256)throw new TypeError("Invalid entropy");return entropyToMnemonic(randomBytes2(strength/8),wordlist2)}function getCoder(wordlist2){if(!Array.isArray(wordlist2)||wordlist2.length!==2048||typeof wordlist2[0]!=="string")throw new Error("Wordlist: expected array of 2048 strings");wordlist2.forEach(i=>{if(typeof i!=="string")throw new Error("wordlist: non-string element: "+i)});return utils.chain(utils.checksum(1,calcChecksum),utils.radix2(11,true),utils.alphabet(wordlist2))}function mnemonicToEntropy(mnemonic,wordlist2){const{words}=normalize(mnemonic);const entropy=getCoder(wordlist2).decode(words);aentropy(entropy);return entropy}function entropyToMnemonic(entropy,wordlist2){aentropy(entropy);const words=getCoder(wordlist2).encode(entropy);return words.join(isJapanese(wordlist2)?"\u3000":" ")}function validateMnemonic(mnemonic,wordlist2){try{mnemonicToEntropy(mnemonic,wordlist2)}catch(e17){return false}return true}var isJapanese,calcChecksum;var init_bip39=__esm({"node_modules/@scure/bip39/index.js"(){"use strict";init_sha2();init_utils();init_base();isJapanese=wordlist2=>wordlist2[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";calcChecksum=entropy=>{const bitsLeft=8-entropy.length/4;return new Uint8Array([sha256(entropy)[0]>>bitsLeft<<bitsLeft])}}});var wordlist;var init_english=__esm({"node_modules/@scure/bip39/wordlists/english.js"(){"use strict";wordlist=`abandon
|
|
27
27
|
ability
|
|
28
28
|
able
|
|
@@ -2131,7 +2131,7 @@ zoo`.split("\n")}});import{chmodSync as chmodSync2,copyFileSync,existsSync as ex
|
|
|
2131
2131
|
|
|
2132
2132
|
`)}}doc.write(`payload.value = newResult;`);doc.write(`return payload;`);const fn=doc.compile();return(payload,ctx)=>fn(shape2,payload,ctx)};let fastpass;const isObject2=isObject;const jit=!globalConfig.jitless;const allowsEval2=allowsEval;const fastEnabled=jit&&allowsEval2.value;const catchall2=def.catchall;let value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);const input=payload.value;if(!isObject2(input)){payload.issues.push({expected:"object",code:"invalid_type",input,inst});return payload}if(jit&&fastEnabled&&ctx?.async===false&&ctx.jitless!==true){if(!fastpass)fastpass=generateFastpass(def.shape);payload=fastpass(payload,ctx);if(!catchall2)return payload;return handleCatchall([],input,payload,ctx,value,inst)}return superParse(payload,ctx)}});$ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def);defineLazy(inst._zod,"optin",()=>def.options.some(o=>o._zod.optin==="optional")?"optional":void 0);defineLazy(inst._zod,"optout",()=>def.options.some(o=>o._zod.optout==="optional")?"optional":void 0);defineLazy(inst._zod,"values",()=>{if(def.options.every(o=>o._zod.values)){return new Set(def.options.flatMap(option=>Array.from(option._zod.values)))}return void 0});defineLazy(inst._zod,"pattern",()=>{if(def.options.every(o=>o._zod.pattern)){const patterns=def.options.map(o=>o._zod.pattern);return new RegExp(`^(${patterns.map(p=>cleanRegex(p.source)).join("|")})$`)}return void 0});const first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first){return first(payload,ctx)}let async=false;const results=[];for(const option of def.options){const result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise){results.push(result);async=true}else{if(result.issues.length===0)return result;results.push(result)}}if(!async)return handleUnionResults(results,payload,inst,ctx);return Promise.all(results).then(results2=>{return handleUnionResults(results2,payload,inst,ctx)})}});$ZodXor=$constructor("$ZodXor",(inst,def)=>{$ZodUnion.init(inst,def);def.inclusive=false;const first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first){return first(payload,ctx)}let async=false;const results=[];for(const option of def.options){const result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise){results.push(result);async=true}else{results.push(result)}}if(!async)return handleExclusiveUnionResults(results,payload,inst,ctx);return Promise.all(results).then(results2=>{return handleExclusiveUnionResults(results2,payload,inst,ctx)})}});$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=false;$ZodUnion.init(inst,def);const _super=inst._zod.parse;defineLazy(inst._zod,"propValues",()=>{const propValues={};for(const option of def.options){const pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(const[k2,v]of Object.entries(pv)){if(!propValues[k2])propValues[k2]=new Set;for(const val of v){propValues[k2].add(val)}}}return propValues});const disc=cached(()=>{const opts=def.options;const map2=new Map;for(const o of opts){const values=o._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);for(const v of values){if(map2.has(v)){throw new Error(`Duplicate discriminator value "${String(v)}"`)}map2.set(v,o)}}return map2});inst._zod.parse=(payload,ctx)=>{const input=payload.value;if(!isObject(input)){payload.issues.push({code:"invalid_type",expected:"object",input,inst});return payload}const opt=disc.value.get(input?.[def.discriminator]);if(opt){return opt._zod.run(payload,ctx)}if(def.unionFallback||ctx.direction==="backward"){return _super(payload,ctx)}payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,options:Array.from(disc.value.keys()),input,path:[def.discriminator],inst});return payload}});$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{const input=payload.value;const left=def.left._zod.run({value:input,issues:[]},ctx);const right=def.right._zod.run({value:input,issues:[]},ctx);const async=left instanceof Promise||right instanceof Promise;if(async){return Promise.all([left,right]).then(([left2,right2])=>{return handleIntersectionResults(payload,left2,right2)})}return handleIntersectionResults(payload,left,right)}});$ZodTuple=$constructor("$ZodTuple",(inst,def)=>{$ZodType.init(inst,def);const items=def.items;inst._zod.parse=(payload,ctx)=>{const input=payload.value;if(!Array.isArray(input)){payload.issues.push({input,inst,expected:"tuple",code:"invalid_type"});return payload}payload.value=[];const proms=[];const optinStart=getTupleOptStart(items,"optin");const optoutStart=getTupleOptStart(items,"optout");if(!def.rest){if(input.length<optinStart){payload.issues.push({code:"too_small",minimum:optinStart,inclusive:true,input,inst,origin:"array"});return payload}if(input.length>items.length){payload.issues.push({code:"too_big",maximum:items.length,inclusive:true,input,inst,origin:"array"})}}const itemResults=new Array(items.length);for(let i=0;i<items.length;i++){const r=items[i]._zod.run({value:input[i],issues:[]},ctx);if(r instanceof Promise){proms.push(r.then(rr=>{itemResults[i]=rr}))}else{itemResults[i]=r}}if(def.rest){let i=items.length-1;const rest=input.slice(items.length);for(const el of rest){i++;const result=def.rest._zod.run({value:el,issues:[]},ctx);if(result instanceof Promise){proms.push(result.then(r=>handleTupleResult(r,payload,i)))}else{handleTupleResult(result,payload,i)}}}if(proms.length){return Promise.all(proms).then(()=>handleTupleResults(itemResults,payload,items,input,optoutStart))}return handleTupleResults(itemResults,payload,items,input,optoutStart)}});$ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{const input=payload.value;if(!isPlainObject(input)){payload.issues.push({expected:"record",code:"invalid_type",input,inst});return payload}const proms=[];const values=def.keyType._zod.values;if(values){payload.value={};const recordKeys=new Set;for(const key of values){if(typeof key==="string"||typeof key==="number"||typeof key==="symbol"){recordKeys.add(typeof key==="number"?key.toString():key);const keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise){throw new Error("Async schemas not supported in object keys currently")}if(keyResult.issues.length){payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}const outKey=keyResult.value;const result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise){proms.push(result.then(result2=>{if(result2.issues.length){payload.issues.push(...prefixIssues(key,result2.issues))}payload.value[outKey]=result2.value}))}else{if(result.issues.length){payload.issues.push(...prefixIssues(key,result.issues))}payload.value[outKey]=result.value}}}let unrecognized;for(const key in input){if(!recordKeys.has(key)){unrecognized=unrecognized??[];unrecognized.push(key)}}if(unrecognized&&unrecognized.length>0){payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized})}}else{payload.value={};for(const key of Reflect.ownKeys(input)){if(key==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(input,key))continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise){throw new Error("Async schemas not supported in object keys currently")}const checkNumericKey=typeof key==="string"&&number.test(key)&&keyResult.issues.length;if(checkNumericKey){const retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise){throw new Error("Async schemas not supported in object keys currently")}if(retryResult.issues.length===0){keyResult=retryResult}}if(keyResult.issues.length){if(def.mode==="loose"){payload.value[key]=input[key]}else{payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst})}continue}const result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise){proms.push(result.then(result2=>{if(result2.issues.length){payload.issues.push(...prefixIssues(key,result2.issues))}payload.value[keyResult.value]=result2.value}))}else{if(result.issues.length){payload.issues.push(...prefixIssues(key,result.issues))}payload.value[keyResult.value]=result.value}}}if(proms.length){return Promise.all(proms).then(()=>payload)}return payload}});$ZodMap=$constructor("$ZodMap",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{const input=payload.value;if(!(input instanceof Map)){payload.issues.push({expected:"map",code:"invalid_type",input,inst});return payload}const proms=[];payload.value=new Map;for(const[key,value]of input){const keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);const valueResult=def.valueType._zod.run({value,issues:[]},ctx);if(keyResult instanceof Promise||valueResult instanceof Promise){proms.push(Promise.all([keyResult,valueResult]).then(([keyResult2,valueResult2])=>{handleMapResult(keyResult2,valueResult2,payload,key,input,inst,ctx)}))}else{handleMapResult(keyResult,valueResult,payload,key,input,inst,ctx)}}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodSet=$constructor("$ZodSet",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{const input=payload.value;if(!(input instanceof Set)){payload.issues.push({input,inst,expected:"set",code:"invalid_type"});return payload}const proms=[];payload.value=new Set;for(const item of input){const result=def.valueType._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise){proms.push(result.then(result2=>handleSetResult(result2,payload)))}else handleSetResult(result,payload)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);const values=getEnumValues(def.entries);const valuesSet=new Set(values);inst._zod.values=valuesSet;inst._zod.pattern=new RegExp(`^(${values.filter(k2=>propertyKeyTypes.has(typeof k2)).map(o=>typeof o==="string"?escapeRegex(o):o.toString()).join("|")})$`);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(valuesSet.has(input)){return payload}payload.issues.push({code:"invalid_value",values,input,inst});return payload}});$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{$ZodType.init(inst,def);if(def.values.length===0){throw new Error("Cannot create literal schema with no valid values")}const values=new Set(def.values);inst._zod.values=values;inst._zod.pattern=new RegExp(`^(${def.values.map(o=>typeof o==="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(values.has(input)){return payload}payload.issues.push({code:"invalid_value",values:def.values,input,inst});return payload}});$ZodFile=$constructor("$ZodFile",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(input instanceof File)return payload;payload.issues.push({expected:"file",code:"invalid_type",input,inst});return payload}});$ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def);inst._zod.optin="optional";inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){throw new $ZodEncodeError(inst.constructor.name)}const _out=def.transform(payload.value,payload);if(ctx.async){const output=_out instanceof Promise?_out:Promise.resolve(_out);return output.then(output2=>{payload.value=output2;payload.fallback=true;return payload})}if(_out instanceof Promise){throw new $ZodAsyncError}payload.value=_out;payload.fallback=true;return payload}});$ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def);inst._zod.optin="optional";inst._zod.optout="optional";defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0});defineLazy(inst._zod,"pattern",()=>{const pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0});inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin==="optional"){const input=payload.value;const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then(r=>handleOptionalResult(r,input));return handleOptionalResult(result,input)}if(payload.value===void 0){return payload}return def.innerType._zod.run(payload,ctx)}});$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def);defineLazy(inst._zod,"values",()=>def.innerType._zod.values);defineLazy(inst._zod,"pattern",()=>def.innerType._zod.pattern);inst._zod.parse=(payload,ctx)=>{return def.innerType._zod.run(payload,ctx)}});$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def);defineLazy(inst._zod,"optin",()=>def.innerType._zod.optin);defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout);defineLazy(inst._zod,"pattern",()=>{const pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0});defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0});inst._zod.parse=(payload,ctx)=>{if(payload.value===null)return payload;return def.innerType._zod.run(payload,ctx)}});$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def);inst._zod.optin="optional";defineLazy(inst._zod,"values",()=>def.innerType._zod.values);inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){return def.innerType._zod.run(payload,ctx)}if(payload.value===void 0){payload.value=def.defaultValue;return payload}const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise){return result.then(result2=>handleDefaultResult(result2,def))}return handleDefaultResult(result,def)}});$ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def);inst._zod.optin="optional";defineLazy(inst._zod,"values",()=>def.innerType._zod.values);inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){return def.innerType._zod.run(payload,ctx)}if(payload.value===void 0){payload.value=def.defaultValue}return def.innerType._zod.run(payload,ctx)}});$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def);defineLazy(inst._zod,"values",()=>{const v=def.innerType._zod.values;return v?new Set([...v].filter(x2=>x2!==void 0)):void 0});inst._zod.parse=(payload,ctx)=>{const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise){return result.then(result2=>handleNonOptionalResult(result2,inst))}return handleNonOptionalResult(result,inst)}});$ZodSuccess=$constructor("$ZodSuccess",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){throw new $ZodEncodeError("ZodSuccess")}const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise){return result.then(result2=>{payload.value=result2.issues.length===0;return payload})}payload.value=result.issues.length===0;return payload}});$ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def);inst._zod.optin="optional";defineLazy(inst._zod,"optout",()=>def.innerType._zod.optout);defineLazy(inst._zod,"values",()=>def.innerType._zod.values);inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){return def.innerType._zod.run(payload,ctx)}const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise){return result.then(result2=>{payload.value=result2.value;if(result2.issues.length){payload.value=def.catchValue({...payload,error:{issues:result2.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value});payload.issues=[];payload.fallback=true}return payload})}payload.value=result.value;if(result.issues.length){payload.value=def.catchValue({...payload,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value});payload.issues=[];payload.fallback=true}return payload}});$ZodNaN=$constructor("$ZodNaN",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="number"||!Number.isNaN(payload.value)){payload.issues.push({input:payload.value,inst,expected:"nan",code:"invalid_type"});return payload}return payload}});$ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def);defineLazy(inst._zod,"values",()=>def.in._zod.values);defineLazy(inst._zod,"optin",()=>def.in._zod.optin);defineLazy(inst._zod,"optout",()=>def.out._zod.optout);defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues);inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){const right=def.out._zod.run(payload,ctx);if(right instanceof Promise){return right.then(right2=>handlePipeResult(right2,def.in,ctx))}return handlePipeResult(right,def.in,ctx)}const left=def.in._zod.run(payload,ctx);if(left instanceof Promise){return left.then(left2=>handlePipeResult(left2,def.out,ctx))}return handlePipeResult(left,def.out,ctx)}});$ZodCodec=$constructor("$ZodCodec",(inst,def)=>{$ZodType.init(inst,def);defineLazy(inst._zod,"values",()=>def.in._zod.values);defineLazy(inst._zod,"optin",()=>def.in._zod.optin);defineLazy(inst._zod,"optout",()=>def.out._zod.optout);defineLazy(inst._zod,"propValues",()=>def.in._zod.propValues);inst._zod.parse=(payload,ctx)=>{const direction=ctx.direction||"forward";if(direction==="forward"){const left=def.in._zod.run(payload,ctx);if(left instanceof Promise){return left.then(left2=>handleCodecAResult(left2,def,ctx))}return handleCodecAResult(left,def,ctx)}else{const right=def.out._zod.run(payload,ctx);if(right instanceof Promise){return right.then(right2=>handleCodecAResult(right2,def,ctx))}return handleCodecAResult(right,def,ctx)}}});$ZodPreprocess=$constructor("$ZodPreprocess",(inst,def)=>{$ZodPipe.init(inst,def)});$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def);defineLazy(inst._zod,"propValues",()=>def.innerType._zod.propValues);defineLazy(inst._zod,"values",()=>def.innerType._zod.values);defineLazy(inst._zod,"optin",()=>def.innerType?._zod?.optin);defineLazy(inst._zod,"optout",()=>def.innerType?._zod?.optout);inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){return def.innerType._zod.run(payload,ctx)}const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise){return result.then(handleReadonlyResult)}return handleReadonlyResult(result)}});$ZodTemplateLiteral=$constructor("$ZodTemplateLiteral",(inst,def)=>{$ZodType.init(inst,def);const regexParts=[];for(const part of def.parts){if(typeof part==="object"&&part!==null){if(!part._zod.pattern){throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`)}const source=part._zod.pattern instanceof RegExp?part._zod.pattern.source:part._zod.pattern;if(!source)throw new Error(`Invalid template literal part: ${part._zod.traits}`);const start=source.startsWith("^")?1:0;const end=source.endsWith("$")?source.length-1:source.length;regexParts.push(source.slice(start,end))}else if(part===null||primitiveTypes.has(typeof part)){regexParts.push(escapeRegex(`${part}`))}else{throw new Error(`Invalid template literal part: ${part}`)}}inst._zod.pattern=new RegExp(`^${regexParts.join("")}$`);inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="string"){payload.issues.push({input:payload.value,inst,expected:"string",code:"invalid_type"});return payload}inst._zod.pattern.lastIndex=0;if(!inst._zod.pattern.test(payload.value)){payload.issues.push({input:payload.value,inst,code:"invalid_format",format:def.format??"template_literal",pattern:inst._zod.pattern.source});return payload}return payload}});$ZodFunction=$constructor("$ZodFunction",(inst,def)=>{$ZodType.init(inst,def);inst._def=def;inst._zod.def=def;inst.implement=func=>{if(typeof func!=="function"){throw new Error("implement() must be called with a function")}return function(...args){const parsedArgs=inst._def.input?parse2(inst._def.input,args):args;const result=Reflect.apply(func,this,parsedArgs);if(inst._def.output){return parse2(inst._def.output,result)}return result}};inst.implementAsync=func=>{if(typeof func!=="function"){throw new Error("implementAsync() must be called with a function")}return async function(...args){const parsedArgs=inst._def.input?await parseAsync(inst._def.input,args):args;const result=await Reflect.apply(func,this,parsedArgs);if(inst._def.output){return await parseAsync(inst._def.output,result)}return result}};inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="function"){payload.issues.push({code:"invalid_type",expected:"function",input:payload.value,inst});return payload}const hasPromiseOutput=inst._def.output&&inst._def.output._zod.def.type==="promise";if(hasPromiseOutput){payload.value=inst.implementAsync(payload.value)}else{payload.value=inst.implement(payload.value)}return payload};inst.input=(...args)=>{const F=inst.constructor;if(Array.isArray(args[0])){return new F({type:"function",input:new $ZodTuple({type:"tuple",items:args[0],rest:args[1]}),output:inst._def.output})}return new F({type:"function",input:args[0],output:inst._def.output})};inst.output=output=>{const F=inst.constructor;return new F({type:"function",input:inst._def.input,output})};return inst});$ZodPromise=$constructor("$ZodPromise",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{return Promise.resolve(payload.value).then(inner=>def.innerType._zod.run({value:inner,issues:[]},ctx))}});$ZodLazy=$constructor("$ZodLazy",(inst,def)=>{$ZodType.init(inst,def);defineLazy(inst._zod,"innerType",()=>{const d=def;if(!d._cachedInner)d._cachedInner=def.getter();return d._cachedInner});defineLazy(inst._zod,"pattern",()=>inst._zod.innerType?._zod?.pattern);defineLazy(inst._zod,"propValues",()=>inst._zod.innerType?._zod?.propValues);defineLazy(inst._zod,"optin",()=>inst._zod.innerType?._zod?.optin??void 0);defineLazy(inst._zod,"optout",()=>inst._zod.innerType?._zod?.optout??void 0);inst._zod.parse=(payload,ctx)=>{const inner=inst._zod.innerType;return inner._zod.run(payload,ctx)}});$ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def);$ZodType.init(inst,def);inst._zod.parse=(payload,_)=>{return payload};inst._zod.check=payload=>{const input=payload.value;const r=def.fn(input);if(r instanceof Promise){return r.then(r2=>handleRefineResult(r2,payload,input,inst))}handleRefineResult(r,payload,input,inst);return}})}});function ar_default(){return{localeError:error()}}var error;var init_ar=__esm({"node_modules/zod/v4/locales/ar.js"(){"use strict";init_util();error=()=>{const Sizable={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`}return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`;return`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"\u0639\u0646\u0635\u0631"}`;return`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`}return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`;if(_issue.format==="ends_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`;if(_issue.format==="regex")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${issue2.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${issue2.keys.length>1?"\u0629":""}: ${joinValues(issue2.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}}}});function az_default(){return{localeError:error2()}}var error2;var init_az=__esm({"node_modules/zod/v4/locales/az.js"(){"use strict";init_util();error2=()=>{const Sizable={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`}return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin??"d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin??"d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(_issue.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`;if(_issue.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`;if(_issue.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return`Yanl\u0131\u015F d\u0259y\u0259r`}}}}});function getBelarusianPlural(count,one,few,many){const absCount=Math.abs(count);const lastDigit=absCount%10;const lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19){return many}if(lastDigit===1){return one}if(lastDigit>=2&&lastDigit<=4){return few}return many}function be_default(){return{localeError:error3()}}var error3;var init_be=__esm({"node_modules/zod/v4/locales/be.js"(){"use strict";init_util();error3=()=>{const Sizable={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"};const TypeDictionary={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`}return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){const maxValue=Number(issue2.maximum);const unit=getBelarusianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){const minValue=Number(issue2.minimum);const unit=getBelarusianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`;if(_issue.format==="ends_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`;if(_issue.format==="regex")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`;default:return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`}}}}});function bg_default(){return{localeError:error4()}}var error4;var init_bg=__esm({"node_modules/zod/v4/locales/bg.js"(){"use strict";init_util();error4=()=>{const Sizable={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"};const TypeDictionary={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`}return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`}if(_issue.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`;if(_issue.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`;let invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";if(_issue.format==="emoji")invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(_issue.format==="datetime")invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(_issue.format==="date")invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";if(_issue.format==="time")invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(_issue.format==="duration")invalid_adj="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";return`${invalid_adj} ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${issue2.keys.length>1?"\u043E\u0432\u0435":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`;default:return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`}}}}});function ca_default(){return{localeError:error5()}}var error5;var init_ca=__esm({"node_modules/zod/v4/locales/ca.js"(){"use strict";init_util();error5=()=>{const Sizable={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`}return`Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`}case"invalid_value":if(issue2.values.length===1)return`Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values," o ")}`;case"too_big":{const adj=issue2.inclusive?"com a m\xE0xim":"menys de";const sizing=getSizing(issue2.origin);if(sizing)return`Massa gran: s'esperava que ${issue2.origin??"el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elements"}`;return`Massa gran: s'esperava que ${issue2.origin??"el valor"} fos ${adj} ${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?"com a m\xEDnim":"m\xE9s de";const sizing=getSizing(issue2.origin);if(sizing){return`Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`}return`Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`}if(_issue.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`;if(_issue.format==="includes")return`Format inv\xE0lid: ha d'incloure "${_issue.includes}"`;if(_issue.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`;return`Format inv\xE0lid per a ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`;case"unrecognized_keys":return`Clau${issue2.keys.length>1?"s":""} no reconeguda${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${issue2.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${issue2.origin}`;default:return`Entrada inv\xE0lida`}}}}});function cs_default(){return{localeError:error6()}}var error6;var init_cs=__esm({"node_modules/zod/v4/locales/cs.js"(){"use strict";init_util();error6=()=>{const Sizable={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"};const TypeDictionary={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`}return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`}case"invalid_value":if(issue2.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin??"hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit??"prvk\u016F"}`}return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin??"hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin??"hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit??"prvk\u016F"}`}return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin??"hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`;if(_issue.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`;if(_issue.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`;return`Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${issue2.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${issue2.origin}`;default:return`Neplatn\xFD vstup`}}}}});function da_default(){return{localeError:error7()}}var error7;var init_da=__esm({"node_modules/zod/v4/locales/da.js"(){"use strict";init_util();error7=()=>{const Sizable={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};const TypeDictionary={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`}return`Ugyldigt input: forventede ${expected}, fik ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`;return`Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);const origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`For stor: forventede ${origin??"value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor: forventede ${origin??"value"} havde ${adj} ${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);const origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing){return`For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`}return`For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Ugyldig streng: skal starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: skal ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: skal indeholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`;return`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${issue2.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${issue2.origin}`;default:return`Ugyldigt input`}}}}});function de_default(){return{localeError:error8()}}var error8;var init_de=__esm({"node_modules/zod/v4/locales/de.js"(){"use strict";init_util();error8=()=>{const Sizable={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};const TypeDictionary={nan:"NaN",number:"Zahl",array:"Array"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`}return`Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Zu gro\xDF: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${issue2.origin??"Wert"} ${adj}${issue2.maximum.toString()} ist`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`}return`Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`;if(_issue.format==="ends_with")return`Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`;if(_issue.format==="includes")return`Ung\xFCltiger String: muss "${_issue.includes}" enthalten`;if(_issue.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`;return`Ung\xFCltig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;case"unrecognized_keys":return`${issue2.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${issue2.origin}`;default:return`Ung\xFCltige Eingabe`}}}}});function el_default(){return{localeError:error9()}}var error9;var init_el=__esm({"node_modules/zod/v4/locales/el.js"(){"use strict";init_util();error9=()=>{const Sizable={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(typeof issue2.expected==="string"&&/^[A-Z]/.test(issue2.expected)){return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${issue2.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`}return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${stringifyPrimitive(issue2.values[0])}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${_issue.prefix}"`}if(_issue.format==="ends_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${_issue.includes}"`;if(_issue.format==="regex")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${_issue.pattern}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${issue2.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue2.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue2.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue2.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${issue2.origin}`;default:return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2`}}}}});function en_default(){return{localeError:error10()}}var error10;var init_en=__esm({"node_modules/zod/v4/locales/en.js"(){"use strict";init_util();error10=()=>{const Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":if(issue2.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;return`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`;return`Too big: expected ${issue2.origin??"value"} to be ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`Invalid string: must start with "${_issue.prefix}"`}if(_issue.format==="ends_with")return`Invalid string: must end with "${_issue.suffix}"`;if(_issue.format==="includes")return`Invalid string: must include "${_issue.includes}"`;if(_issue.format==="regex")return`Invalid string: must match pattern ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue2.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue2.origin}`;case"invalid_union":if(issue2.options&&Array.isArray(issue2.options)&&issue2.options.length>0){const opts=issue2.options.map(o=>`'${o}'`).join(" | ");return`Invalid discriminator value. Expected ${opts}`}return"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return`Invalid input`}}}}});function eo_default(){return{localeError:error11()}}var error11;var init_eo=__esm({"node_modules/zod/v4/locales/eo.js"(){"use strict";init_util();error11=()=>{const Sizable={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};const TypeDictionary={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`}return`Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`}case"invalid_value":if(issue2.values.length===1)return`Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`;return`Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Tro granda: atendi\u011Dis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementojn"}`;return`Tro granda: atendi\u011Dis ke ${issue2.origin??"valoro"} havu ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`;if(_issue.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;if(_issue.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;return`Nevalida ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${issue2.divisor}`;case"unrecognized_keys":return`Nekonata${issue2.keys.length>1?"j":""} \u015Dlosilo${issue2.keys.length>1?"j":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${issue2.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${issue2.origin}`;default:return`Nevalida enigo`}}}}});function es_default(){return{localeError:error12()}}var error12;var init_es=__esm({"node_modules/zod/v4/locales/es.js"(){"use strict";init_util();error12=()=>{const Sizable={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};const TypeDictionary={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`}return`Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);const origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`Demasiado grande: se esperaba que ${origin??"valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${origin??"valor"} fuera ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);const origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing){return`Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`;if(_issue.format==="includes")return`Cadena inv\xE1lida: debe incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`;return`Inv\xE1lido ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Llave${issue2.keys.length>1?"s":""} desconocida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${TypeDictionary[issue2.origin]??issue2.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${TypeDictionary[issue2.origin]??issue2.origin}`;default:return`Entrada inv\xE1lida`}}}}});function fa_default(){return{localeError:error13()}}var error13;var init_fa=__esm({"node_modules/zod/v4/locales/fa.js"(){"use strict";init_util();error13=()=>{const Sizable={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"};const TypeDictionary={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":if(issue2.values.length===1){return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`}return`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`}return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`}return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`}if(_issue.format==="ends_with"){return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`}if(_issue.format==="includes"){return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`}if(_issue.format==="regex"){return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`}return`${FormatDictionary[_issue.format]??issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${issue2.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`;case"invalid_union":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`;default:return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}}}}});function fi_default(){return{localeError:error14()}}var error14;var init_fi=__esm({"node_modules/zod/v4/locales/fi.js"(){"use strict";init_util();error14=()=>{const Sizable={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`}return`Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`}case"invalid_value":if(issue2.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){return`Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim()}return`Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim()}return`Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`;if(_issue.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`;if(_issue.format==="regex"){return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`}return`Virheellinen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`;case"unrecognized_keys":return`${issue2.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return`Virheellinen sy\xF6te`}}}}});function fr_default(){return{localeError:error15()}}var error15;var init_fr=__esm({"node_modules/zod/v4/locales/fr.js"(){"use strict";init_util();error15=()=>{const Sizable={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};const TypeDictionary={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`}return`Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`}case"invalid_value":if(issue2.values.length===1)return`Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;return`Option invalide : une valeur parmi ${joinValues(issue2.values,"|")} attendue`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Trop grand : ${TypeDictionary[issue2.origin]??"valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${TypeDictionary[issue2.origin]??"valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing)return`Trop petit : ${TypeDictionary[issue2.origin]??"valeur"} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`Trop petit : ${TypeDictionary[issue2.origin]??"valeur"} doit \xEAtre ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Cha\xEEne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Cl\xE9${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${issue2.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return`Entr\xE9e invalide`}}}}});function fr_CA_default(){return{localeError:error16()}}var error16;var init_fr_CA=__esm({"node_modules/zod/v4/locales/fr-CA.js"(){"use strict";init_util();error16=()=>{const Sizable={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`}return`Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"\u2264":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Trop grand : attendu que ${issue2.origin??"la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`Trop grand : attendu que ${issue2.origin??"la valeur"} soit ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?"\u2265":">";const sizing=getSizing(issue2.origin);if(sizing){return`Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`}if(_issue.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Cha\xEEne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;case"unrecognized_keys":return`Cl\xE9${issue2.keys.length>1?"s":""} non reconnue${issue2.keys.length>1?"s":""} : ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${issue2.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${issue2.origin}`;default:return`Entr\xE9e invalide`}}}}});function he_default(){return{localeError:error17()}}var error17;var init_he=__esm({"node_modules/zod/v4/locales/he.js"(){"use strict";init_util();error17=()=>{const TypeNames={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}};const Sizable={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}};const typeEntry=t2=>t2?TypeNames[t2]:void 0;const typeLabel=t2=>{const e17=typeEntry(t2);if(e17)return e17.label;return t2??TypeNames.unknown.label};const withDefinite=t2=>`\u05D4${typeLabel(t2)}`;const verbFor=t2=>{const e17=typeEntry(t2);const gender=e17?.gender??"m";return gender==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"};const getSizing=origin=>{if(!origin)return null;return Sizable[origin]??null};const FormatDictionary={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expectedKey=issue2.expected;const expected=TypeDictionary[expectedKey??""]??typeLabel(expectedKey);const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??TypeNames[receivedType]?.label??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`}return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`}case"invalid_value":{if(issue2.values.length===1){return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`}const stringified=issue2.values.map(v=>stringifyPrimitive(v));if(issue2.values.length===2){return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`}const lastValue=stringified[stringified.length-1];const restValues=stringified.slice(0,-1).join(", ");return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`}case"too_big":{const sizing=getSizing(issue2.origin);const subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string"){return`${sizing?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim()}if(issue2.origin==="number"){const comparison=issue2.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){const verb=issue2.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";const comparison=issue2.inclusive?`${issue2.maximum} ${sizing?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim()}const adj=issue2.inclusive?"<=":"<";const be2=verbFor(issue2.origin??"value");if(sizing?.unit){return`${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be2} ${adj}${issue2.maximum.toString()} ${sizing.unit}`}return`${sizing?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be2} ${adj}${issue2.maximum.toString()}`}case"too_small":{const sizing=getSizing(issue2.origin);const subject=withDefinite(issue2.origin??"value");if(issue2.origin==="string"){return`${sizing?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit??""} ${issue2.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim()}if(issue2.origin==="number"){const comparison=issue2.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`}if(issue2.origin==="array"||issue2.origin==="set"){const verb=issue2.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(issue2.minimum===1&&issue2.inclusive){const singularPhrase=issue2.origin==="set"?"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3":"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`}const comparison=issue2.inclusive?`${issue2.minimum} ${sizing?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim()}const adj=issue2.inclusive?">=":">";const be2=verbFor(issue2.origin??"value");if(sizing?.unit){return`${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be2} ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`${sizing?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be2} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`;if(_issue.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`;if(_issue.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;const nounEntry=FormatDictionary[_issue.format];const noun=nounEntry?.label??_issue.format;const gender=nounEntry?.gender??"m";const adjective=gender==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${noun} \u05DC\u05D0 ${adjective}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${issue2.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":{return`\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`}case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":{const place=withDefinite(issue2.origin??"array");return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`}default:return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}}}}});function hr_default(){return{localeError:error18()}}var error18;var init_hr=__esm({"node_modules/zod/v4/locales/hr.js"(){"use strict";init_util();error18=()=>{const Sizable={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"};const TypeDictionary={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Neispravan unos: o\u010Dekuje se instanceof ${issue2.expected}, a primljeno je ${received}`}return`Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`}case"invalid_value":if(issue2.values.length===1)return`Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue2.values[0])}`;return`Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);const origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing)return`Preveliko: o\u010Dekivano da ${origin??"vrijednost"} ima ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemenata"}`;return`Preveliko: o\u010Dekivano da ${origin??"vrijednost"} bude ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);const origin=TypeDictionary[issue2.origin]??issue2.origin;if(sizing){return`Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Neispravan tekst: mora zapo\u010Dinjati s "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neispravan tekst: mora zavr\u0161avati s "${_issue.suffix}"`;if(_issue.format==="includes")return`Neispravan tekst: mora sadr\u017Eavati "${_issue.includes}"`;if(_issue.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`;return`Neispravna ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${issue2.divisor}`;case"unrecognized_keys":return`Neprepoznat${issue2.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${TypeDictionary[issue2.origin]??issue2.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${TypeDictionary[issue2.origin]??issue2.origin}`;default:return`Neispravan unos`}}}}});function hu_default(){return{localeError:error19()}}var error19;var init_hu=__esm({"node_modules/zod/v4/locales/hu.js"(){"use strict";init_util();error19=()=>{const Sizable={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"};const TypeDictionary={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`}return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`}case"invalid_value":if(issue2.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`T\xFAl nagy: ${issue2.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(_issue.format==="ends_with")return`\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(_issue.format==="includes")return`\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(_issue.format==="regex")return`\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${issue2.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`;default:return`\xC9rv\xE9nytelen bemenet`}}}}});function getArmenianPlural(count,one,many){return Math.abs(count)===1?one:many}function withDefiniteArticle(word){if(!word)return"";const vowels=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"];const lastChar=word[word.length-1];return word+(vowels.includes(lastChar)?"\u0576":"\u0568")}function hy_default(){return{localeError:error20()}}var error20;var init_hy=__esm({"node_modules/zod/v4/locales/hy.js"(){"use strict";init_util();error20=()=>{const Sizable={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"};const TypeDictionary={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`}return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`;return`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){const maxValue=Number(issue2.maximum);const unit=getArmenianPlural(maxValue,sizing.unit.one,sizing.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){const minValue=Number(issue2.minimum);const unit=getArmenianPlural(minValue,sizing.unit.one,sizing.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`;if(_issue.format==="ends_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`;if(_issue.format==="includes")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`;if(_issue.format==="regex")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;return`\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length>1?"\u0576\u0565\u0580":""}. ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;default:return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`}}}}});function id_default(){return{localeError:error21()}}var error21;var init_id=__esm({"node_modules/zod/v4/locales/id.js"(){"use strict";init_util();error21=()=>{const Sizable={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`}return`Input tidak valid: diharapkan ${expected}, diterima ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Terlalu besar: diharapkan ${issue2.origin??"value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: diharapkan ${issue2.origin??"value"} menjadi ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`String tidak valid: harus dimulai dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak valid: harus berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak valid: harus menyertakan "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak valid: harus sesuai pola ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${issue2.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${issue2.origin}`;default:return`Input tidak valid`}}}}});function is_default(){return{localeError:error22()}}var error22;var init_is=__esm({"node_modules/zod/v4/locales/is.js"(){"use strict";init_util();error22=()=>{const Sizable={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"};const TypeDictionary={nan:"NaN",number:"n\xFAmer",array:"fylki"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`}return`Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`}case"invalid_value":if(issue2.values.length===1)return`Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`;return`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin??"gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit??"hluti"}`;return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin??"gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`}if(_issue.format==="ends_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`;if(_issue.format==="includes")return`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`;if(_issue.format==="regex")return`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`;return`Rangt ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${issue2.keys.length>1?"ir lyklar":"ur lykill"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${issue2.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${issue2.origin}`;default:return`Rangt gildi`}}}}});function it_default(){return{localeError:error23()}}var error23;var init_it=__esm({"node_modules/zod/v4/locales/it.js"(){"use strict";init_util();error23=()=>{const Sizable={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};const TypeDictionary={nan:"NaN",number:"numero",array:"vettore"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`}return`Input non valido: atteso ${expected}, ricevuto ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;return`Opzione non valida: atteso uno tra ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Troppo grande: ${issue2.origin??"valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementi"}`;return`Troppo grande: ${issue2.origin??"valore"} deve essere ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Stringa non valida: deve iniziare con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Stringa non valida: deve terminare con "${_issue.suffix}"`;if(_issue.format==="includes")return`Stringa non valida: deve includere "${_issue.includes}"`;if(_issue.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;return`Input non valido: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${issue2.divisor}`;case"unrecognized_keys":return`Chiav${issue2.keys.length>1?"i":"e"} non riconosciut${issue2.keys.length>1?"e":"a"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${issue2.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${issue2.origin}`;default:return`Input non valido`}}}}});function ja_default(){return{localeError:error24()}}var error24;var init_ja=__esm({"node_modules/zod/v4/locales/ja.js"(){"use strict";init_util();error24=()=>{const Sizable={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"};const TypeDictionary={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}return`\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":if(issue2.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{const adj=issue2.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044";const sizing=getSizing(issue2.origin);if(sizing)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin??"\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit??"\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin??"\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{const adj=issue2.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044";const sizing=getSizing(issue2.origin);if(sizing)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(_issue.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(_issue.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(_issue.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length>1?"\u7FA4":""}: ${joinValues(issue2.keys,"\u3001")}`;case"invalid_key":return`${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return`\u7121\u52B9\u306A\u5165\u529B`}}}}});function ka_default(){return{localeError:error25()}}var error25;var init_ka=__esm({"node_modules/zod/v4/locales/ka.js"(){"use strict";init_util();error25=()=>{const Sizable={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"};const TypeDictionary={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`}return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`}if(_issue.format==="ends_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`;if(_issue.format==="includes")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`;if(_issue.format==="regex")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`;default:return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`}}}}});function km_default(){return{localeError:error26()}}var error26;var init_km=__esm({"node_modules/zod/v4/locales/km.js"(){"use strict";init_util();error26=()=>{const Sizable={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"};const TypeDictionary={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`}return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`;return`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit??"\u1792\u17B6\u178F\u17BB"}`;return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`}return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`}if(_issue.format==="ends_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`;if(_issue.format==="regex")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`;return`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;case"invalid_union":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;default:return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`}}}}});function kh_default(){return km_default()}var init_kh=__esm({"node_modules/zod/v4/locales/kh.js"(){"use strict";init_km()}});function ko_default(){return{localeError:error27()}}var error27;var init_ko=__esm({"node_modules/zod/v4/locales/ko.js"(){"use strict";init_util();error27=()=>{const Sizable={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`}return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`}case"invalid_value":if(issue2.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{const adj=issue2.inclusive?"\uC774\uD558":"\uBBF8\uB9CC";const suffix=adj==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4";const sizing=getSizing(issue2.origin);const unit=sizing?.unit??"\uC694\uC18C";if(sizing)return`${issue2.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;return`${issue2.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`}case"too_small":{const adj=issue2.inclusive?"\uC774\uC0C1":"\uCD08\uACFC";const suffix=adj==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4";const sizing=getSizing(issue2.origin);const unit=sizing?.unit??"\uC694\uC18C";if(sizing){return`${issue2.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`}return`${issue2.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`}if(_issue.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(_issue.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(_issue.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`;case"invalid_union":return`\uC798\uBABB\uB41C \uC785\uB825`;case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`;default:return`\uC798\uBABB\uB41C \uC785\uB825`}}}}});function getUnitTypeFromNumber(number4){const abs=Math.abs(number4);const last=abs%10;const last2=abs%100;if(last2>=11&&last2<=19||last===0)return"many";if(last===1)return"one";return"few"}function lt_default(){return{localeError:error28()}}var capitalizeFirstCharacter,error28;var init_lt=__esm({"node_modules/zod/v4/locales/lt.js"(){"use strict";init_util();capitalizeFirstCharacter=text=>{return text.charAt(0).toUpperCase()+text.slice(1)};error28=()=>{const Sizable={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function getSizing(origin,unitType,inclusive,targetShouldBe){const result=Sizable[origin]??null;if(result===null)return result;return{unit:result.unit[unitType],verb:result.verb[targetShouldBe][inclusive?"inclusive":"notInclusive"]}}const FormatDictionary={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"};const TypeDictionary={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`}return`Gautas tipas ${received}, o tik\u0117tasi - ${expected}`}case"invalid_value":if(issue2.values.length===1)return`Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`;return`Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values,"|")} pasirinkim\u0173`;case"too_big":{const origin=TypeDictionary[issue2.origin]??issue2.origin;const sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.maximum)),issue2.inclusive??false,"smaller");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit??"element\u0173"}`;const adj=issue2.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`}case"too_small":{const origin=TypeDictionary[issue2.origin]??issue2.origin;const sizing=getSizing(issue2.origin,getUnitTypeFromNumber(Number(issue2.minimum)),issue2.inclusive??false,"bigger");if(sizing?.verb)return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit??"element\u0173"}`;const adj=issue2.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`}if(_issue.format==="ends_with")return`Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`;if(_issue.format==="includes")return`Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`;if(_issue.format==="regex")return`Eilut\u0117 privalo atitikti ${_issue.pattern}`;return`Neteisingas ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${issue2.keys.length>1?"i":"as"} rakt${issue2.keys.length>1?"ai":"as"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{const origin=TypeDictionary[issue2.origin]??issue2.origin;return`${capitalizeFirstCharacter(origin??issue2.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}}}});function mk_default(){return{localeError:error29()}}var error29;var init_mk=__esm({"node_modules/zod/v4/locales/mk.js"(){"use strict";init_util();error29=()=>{const Sizable={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"};const TypeDictionary={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`}return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`}case"invalid_value":if(issue2.values.length===1)return`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;return`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`}if(_issue.format==="ends_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`;if(_issue.format==="includes")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`;if(_issue.format==="regex")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;return`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`;default:return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`}}}}});function ms_default(){return{localeError:error30()}}var error30;var init_ms=__esm({"node_modules/zod/v4/locales/ms.js"(){"use strict";init_util();error30=()=>{const Sizable={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};const TypeDictionary={nan:"NaN",number:"nombor"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`}return`Input tidak sah: dijangka ${expected}, diterima ${received}`}case"invalid_value":if(issue2.values.length===1)return`Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Terlalu besar: dijangka ${issue2.origin??"nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: dijangka ${issue2.origin??"nilai"} adalah ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`String tidak sah: mesti bermula dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak sah: mesti mengandungi "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${issue2.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${issue2.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${issue2.origin}`;default:return`Input tidak sah`}}}}});function nl_default(){return{localeError:error31()}}var error31;var init_nl=__esm({"node_modules/zod/v4/locales/nl.js"(){"use strict";init_util();error31=()=>{const Sizable={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};const TypeDictionary={nan:"NaN",number:"getal"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`}return`Ongeldige invoer: verwacht ${expected}, ontving ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;return`Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);const longName=issue2.origin==="date"?"laat":issue2.origin==="string"?"lang":"groot";if(sizing)return`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementen"} ${sizing.verb}`;return`Te ${longName}: verwacht dat ${issue2.origin??"waarde"} ${adj}${issue2.maximum.toString()} is`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);const shortName=issue2.origin==="date"?"vroeg":issue2.origin==="string"?"kort":"klein";if(sizing){return`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`}return`Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`Ongeldige tekst: moet met "${_issue.prefix}" beginnen`}if(_issue.format==="ends_with")return`Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;if(_issue.format==="includes")return`Ongeldige tekst: moet "${_issue.includes}" bevatten`;if(_issue.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;return`Ongeldig: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${issue2.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${issue2.origin}`;default:return`Ongeldige invoer`}}}}});function no_default(){return{localeError:error32()}}var error32;var init_no=__esm({"node_modules/zod/v4/locales/no.js"(){"use strict";init_util();error32=()=>{const Sizable={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};const TypeDictionary={nan:"NaN",number:"tall",array:"liste"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`}return`Ugyldig input: forventet ${expected}, fikk ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;return`Ugyldig valg: forventet en av ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`For stor(t): forventet ${issue2.origin??"value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor(t): forventet ${issue2.origin??"value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`;return`Ugyldig ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${issue2.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${issue2.origin}`;default:return`Ugyldig input`}}}}});function ota_default(){return{localeError:error33()}}var error33;var init_ota=__esm({"node_modules/zod/v4/locales/ota.js"(){"use strict";init_util();error33=()=>{const Sizable={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"};const TypeDictionary={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`}return`F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`}case"invalid_value":if(issue2.values.length===1)return`F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Fazla b\xFCy\xFCk: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${issue2.origin??"value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`}return`Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`;if(_issue.format==="ends_with")return`F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`;if(_issue.format==="includes")return`F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`;if(_issue.format==="regex")return`F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return`K\u0131ymet tan\u0131namad\u0131.`}}}}});function ps_default(){return{localeError:error34()}}var error34;var init_ps=__esm({"node_modules/zod/v4/locales/ps.js"(){"use strict";init_util();error34=()=>{const Sizable={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"};const TypeDictionary={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":if(issue2.values.length===1){return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`}return`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`}return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`}return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`}if(_issue.format==="ends_with"){return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`}if(_issue.format==="includes"){return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`}if(_issue.format==="regex"){return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`}return`${FormatDictionary[_issue.format]??issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${issue2.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;case"invalid_union":return`\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;default:return`\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`}}}}});function pl_default(){return{localeError:error35()}}var error35;var init_pl=__esm({"node_modules/zod/v4/locales/pl.js"(){"use strict";init_util();error35=()=>{const Sizable={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"};const TypeDictionary={nan:"NaN",number:"liczba",array:"tablica"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`}return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`}case"invalid_value":if(issue2.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit??"element\xF3w"}`}return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit??"element\xF3w"}`}return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`;if(_issue.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`;if(_issue.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${issue2.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`;default:return`Nieprawid\u0142owe dane wej\u015Bciowe`}}}}});function pt_default(){return{localeError:error36()}}var error36;var init_pt=__esm({"node_modules/zod/v4/locales/pt.js"(){"use strict";init_util();error36=()=>{const Sizable={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};const TypeDictionary={nan:"NaN",number:"n\xFAmero",null:"nulo"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`}return`Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`}case"invalid_value":if(issue2.values.length===1)return`Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Muito grande: esperado que ${issue2.origin??"valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementos"}`;return`Muito grande: esperado que ${issue2.origin??"valor"} fosse ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`;if(_issue.format==="includes")return`Texto inv\xE1lido: deve incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;case"unrecognized_keys":return`Chave${issue2.keys.length>1?"s":""} desconhecida${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${issue2.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${issue2.origin}`;default:return`Campo inv\xE1lido`}}}}});function ro_default(){return{localeError:error37()}}var error37;var init_ro=__esm({"node_modules/zod/v4/locales/ro.js"(){"use strict";init_util();error37=()=>{const Sizable={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"intrare",email:"adres\u0103 de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"};const TypeDictionary={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;return`Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`}case"invalid_value":if(issue2.values.length===1)return`Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue2.values[0])}`;return`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Prea mare: a\u0219teptat ca ${issue2.origin??"valoarea"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"elemente"}`;return`Prea mare: a\u0219teptat ca ${issue2.origin??"valoarea"} s\u0103 fie ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Prea mic: a\u0219teptat ca ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Prea mic: a\u0219teptat ca ${issue2.origin} s\u0103 fie ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${_issue.prefix}"`}if(_issue.format==="ends_with")return`\u0218ir invalid: trebuie s\u0103 se termine cu "${_issue.suffix}"`;if(_issue.format==="includes")return`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${_issue.includes}"`;if(_issue.format==="regex")return`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${_issue.pattern}`;return`Format invalid: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue2.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${issue2.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${issue2.origin}`;default:return`Intrare invalid\u0103`}}}}});function getRussianPlural(count,one,few,many){const absCount=Math.abs(count);const lastDigit=absCount%10;const lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19){return many}if(lastDigit===1){return one}if(lastDigit>=2&&lastDigit<=4){return few}return many}function ru_default(){return{localeError:error38()}}var error38;var init_ru=__esm({"node_modules/zod/v4/locales/ru.js"(){"use strict";init_util();error38=()=>{const Sizable={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"};const TypeDictionary={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`}return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){const maxValue=Number(issue2.maximum);const unit=getRussianPlural(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){const minValue=Number(issue2.minimum);const unit=getRussianPlural(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`;if(_issue.format==="ends_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`;if(_issue.format==="regex")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length>1?"\u0438":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`;default:return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`}}}}});function sl_default(){return{localeError:error39()}}var error39;var init_sl=__esm({"node_modules/zod/v4/locales/sl.js"(){"use strict";init_util();error39=()=>{const Sizable={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"};const TypeDictionary={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`}return`Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`}case"invalid_value":if(issue2.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Preveliko: pri\u010Dakovano, da bo ${issue2.origin??"vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${issue2.origin??"vrednost"} ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`}if(_issue.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`;if(_issue.format==="includes")return`Neveljaven niz: mora vsebovati "${_issue.includes}"`;if(_issue.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;return`Neveljaven ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`;case"unrecognized_keys":return`Neprepoznan${issue2.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${issue2.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${issue2.origin}`;default:return"Neveljaven vnos"}}}}});function sv_default(){return{localeError:error40()}}var error40;var init_sv=__esm({"node_modules/zod/v4/locales/sv.js"(){"use strict";init_util();error40=()=>{const Sizable={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};const TypeDictionary={nan:"NaN",number:"antal",array:"lista"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`}return`Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`;return`Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){return`F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin??"v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit??"element"}`}return`F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin??"v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin??"v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin??"v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`}if(_issue.format==="ends_with")return`Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`;if(_issue.format==="regex")return`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`;return`Ogiltig(t) ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`;case"unrecognized_keys":return`${issue2.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${issue2.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${issue2.origin??"v\xE4rdet"}`;default:return`Ogiltig input`}}}}});function ta_default(){return{localeError:error41()}}var error41;var init_ta=__esm({"node_modules/zod/v4/locales/ta.js"(){"use strict";init_util();error41=()=>{const Sizable={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"};const TypeDictionary={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`}return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing){return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(_issue.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(_issue.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(_issue.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`}}}}});function th_default(){return{localeError:error42()}}var error42;var init_th=__esm({"node_modules/zod/v4/locales/th.js"(){"use strict";init_util();error42=()=>{const Sizable={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"};const TypeDictionary={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`}return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`;return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32";const sizing=getSizing(issue2.origin);if(sizing)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32";const sizing=getSizing(issue2.origin);if(sizing){return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`}return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`}if(_issue.format==="ends_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(_issue.format==="regex")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;default:return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`}}}}});function tr_default(){return{localeError:error43()}}var error43;var init_tr=__esm({"node_modules/zod/v4/locales/tr.js"(){"use strict";init_util();error43=()=>{const Sizable={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`}return`Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin??"de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin??"de\u011Fer"} ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`;if(_issue.format==="ends_with")return`Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`;if(_issue.format==="includes")return`Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`;if(_issue.format==="regex")return`Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return`Ge\xE7ersiz de\u011Fer`}}}}});function uk_default(){return{localeError:error44()}}var error44;var init_uk=__esm({"node_modules/zod/v4/locales/uk.js"(){"use strict";init_util();error44=()=>{const Sizable={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"};const TypeDictionary={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`}return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`;if(_issue.format==="ends_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;if(_issue.format==="includes")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`;if(_issue.format==="regex")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length>1?"\u0456":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`;default:return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`}}}}});function ua_default(){return uk_default()}var init_ua=__esm({"node_modules/zod/v4/locales/ua.js"(){"use strict";init_uk()}});function ur_default(){return{localeError:error45()}}var error45;var init_ur=__esm({"node_modules/zod/v4/locales/ur.js"(){"use strict";init_util();error45=()=>{const Sizable={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"};const TypeDictionary={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":if(issue2.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`}return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`}if(_issue.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(_issue.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(_issue.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length>1?"\u0632":""}: ${joinValues(issue2.keys,"\u060C ")}`;case"invalid_key":return`${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`}}}}});function uz_default(){return{localeError:error46()}}var error46;var init_uz=__esm({"node_modules/zod/v4/locales/uz.js"(){"use strict";init_util();error46=()=>{const Sizable={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"};const TypeDictionary={nan:"NaN",number:"raqam",array:"massiv"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`}return`Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`}case"invalid_value":if(issue2.values.length===1)return`Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`;return`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`;return`Juda katta: kutilgan ${issue2.origin??"qiymat"} ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`}return`Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;if(_issue.format==="ends_with")return`Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`;if(_issue.format==="includes")return`Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`;if(_issue.format==="regex")return`Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;return`Noto\u2018g\u2018ri ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${issue2.keys.length>1?"lar":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${issue2.origin} da noto\u2018g\u2018ri qiymat`;default:return`Noto\u2018g\u2018ri kirish`}}}}});function vi_default(){return{localeError:error47()}}var error47;var init_vi=__esm({"node_modules/zod/v4/locales/vi.js"(){"use strict";init_util();error47=()=>{const Sizable={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"};const TypeDictionary={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`}return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`;return`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin??"gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin??"gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`;if(_issue.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`;if(_issue.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`;return`${FormatDictionary[_issue.format]??issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;default:return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`}}}}});function zh_CN_default(){return{localeError:error48()}}var error48;var init_zh_CN=__esm({"node_modules/zod/v4/locales/zh-CN.js"(){"use strict";init_util();error48=()=>{const Sizable={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"};const TypeDictionary={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`}return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin??"\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin??"\u503C"} ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`;if(_issue.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`;if(_issue.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`;if(_issue.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`;return`\u65E0\u6548${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return`\u65E0\u6548\u8F93\u5165`}}}}});function zh_TW_default(){return{localeError:error49()}}var error49;var init_zh_TW=__esm({"node_modules/zod/v4/locales/zh-TW.js"(){"use strict";init_util();error49=()=>{const Sizable={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"};const TypeDictionary={nan:"NaN"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`}return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`}case"invalid_value":if(issue2.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin??"\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin??"\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing){return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`}return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with"){return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`}if(_issue.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`;if(_issue.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`;if(_issue.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;return`\u7121\u6548\u7684 ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length>1?"\u5011":""}\uFF1A${joinValues(issue2.keys,"\u3001")}`;case"invalid_key":return`${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return`\u7121\u6548\u7684\u8F38\u5165\u503C`}}}}});function yo_default(){return{localeError:error50()}}var error50;var init_yo=__esm({"node_modules/zod/v4/locales/yo.js"(){"use strict";init_util();error50=()=>{const Sizable={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function getSizing(origin){return Sizable[origin]??null}const FormatDictionary={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"};const TypeDictionary={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return issue2=>{switch(issue2.code){case"invalid_type":{const expected=TypeDictionary[issue2.expected]??issue2.expected;const receivedType=parsedType(issue2.input);const received=TypeDictionary[receivedType]??receivedType;if(/^[A-Z]/.test(issue2.expected)){return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`}return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`}case"invalid_value":if(issue2.values.length===1)return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`;return`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values,"|")}`;case"too_big":{const adj=issue2.inclusive?"<=":"<";const sizing=getSizing(issue2.origin);if(sizing)return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin??"iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`}case"too_small":{const adj=issue2.inclusive?">=":">";const sizing=getSizing(issue2.origin);if(sizing)return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`}case"invalid_format":{const _issue=issue2;if(_issue.format==="starts_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`;if(_issue.format==="ends_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`;if(_issue.format==="includes")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`;if(_issue.format==="regex")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`;return`A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}}}});var locales_exports={};__export(locales_exports,{ar:()=>ar_default,az:()=>az_default,be:()=>be_default,bg:()=>bg_default,ca:()=>ca_default,cs:()=>cs_default,da:()=>da_default,de:()=>de_default,el:()=>el_default,en:()=>en_default,eo:()=>eo_default,es:()=>es_default,fa:()=>fa_default,fi:()=>fi_default,fr:()=>fr_default,frCA:()=>fr_CA_default,he:()=>he_default,hr:()=>hr_default,hu:()=>hu_default,hy:()=>hy_default,id:()=>id_default,is:()=>is_default,it:()=>it_default,ja:()=>ja_default,ka:()=>ka_default,kh:()=>kh_default,km:()=>km_default,ko:()=>ko_default,lt:()=>lt_default,mk:()=>mk_default,ms:()=>ms_default,nl:()=>nl_default,no:()=>no_default,ota:()=>ota_default,pl:()=>pl_default,ps:()=>ps_default,pt:()=>pt_default,ro:()=>ro_default,ru:()=>ru_default,sl:()=>sl_default,sv:()=>sv_default,ta:()=>ta_default,th:()=>th_default,tr:()=>tr_default,ua:()=>ua_default,uk:()=>uk_default,ur:()=>ur_default,uz:()=>uz_default,vi:()=>vi_default,yo:()=>yo_default,zhCN:()=>zh_CN_default,zhTW:()=>zh_TW_default});var init_locales=__esm({"node_modules/zod/v4/locales/index.js"(){"use strict";init_ar();init_az();init_be();init_bg();init_ca();init_cs();init_da();init_de();init_el();init_en();init_eo();init_es();init_fa();init_fi();init_fr();init_fr_CA();init_he();init_hr();init_hu();init_hy();init_id();init_is();init_it();init_ja();init_ka();init_kh();init_km();init_ko();init_lt();init_mk();init_ms();init_nl();init_no();init_ota();init_ps();init_pl();init_pt();init_ro();init_ru();init_sl();init_sv();init_ta();init_th();init_tr();init_ua();init_uk();init_ur();init_uz();init_vi();init_zh_CN();init_zh_TW();init_yo()}});function registry(){return new $ZodRegistry}var _a2,$output,$input,$ZodRegistry,globalRegistry;var init_registries=__esm({"node_modules/zod/v4/core/registries.js"(){"use strict";$output=Symbol("ZodOutput");$input=Symbol("ZodInput");$ZodRegistry=class{constructor(){this._map=new WeakMap;this._idmap=new Map}add(schema,..._meta){const meta4=_meta[0];this._map.set(schema,meta4);if(meta4&&typeof meta4==="object"&&"id"in meta4){this._idmap.set(meta4.id,schema)}return this}clear(){this._map=new WeakMap;this._idmap=new Map;return this}remove(schema){const meta4=this._map.get(schema);if(meta4&&typeof meta4==="object"&&"id"in meta4){this._idmap.delete(meta4.id)}this._map.delete(schema);return this}get(schema){const p=schema._zod.parent;if(p){const pm={...this.get(p)??{}};delete pm.id;const f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}};(_a2=globalThis).__zod_globalRegistry??(_a2.__zod_globalRegistry=registry());globalRegistry=globalThis.__zod_globalRegistry}});function _string(Class2,params){return new Class2({type:"string",...normalizeParams(params)})}function _coercedString(Class2,params){return new Class2({type:"string",coerce:true,...normalizeParams(params)})}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:false,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:false,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:false,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:false,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:false,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:false,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:false,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:false,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:false,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:false,...normalizeParams(params)})}function _mac(Class2,params){return new Class2({type:"string",format:"mac",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:false,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:false,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:false,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:false,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:false,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:false,local:false,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2({type:"number",checks:[],...normalizeParams(params)})}function _coercedNumber(Class2,params){return new Class2({type:"number",coerce:true,checks:[],...normalizeParams(params)})}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:false,format:"safeint",...normalizeParams(params)})}function _float32(Class2,params){return new Class2({type:"number",check:"number_format",abort:false,format:"float32",...normalizeParams(params)})}function _float64(Class2,params){return new Class2({type:"number",check:"number_format",abort:false,format:"float64",...normalizeParams(params)})}function _int32(Class2,params){return new Class2({type:"number",check:"number_format",abort:false,format:"int32",...normalizeParams(params)})}function _uint32(Class2,params){return new Class2({type:"number",check:"number_format",abort:false,format:"uint32",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _coercedBoolean(Class2,params){return new Class2({type:"boolean",coerce:true,...normalizeParams(params)})}function _bigint(Class2,params){return new Class2({type:"bigint",...normalizeParams(params)})}function _coercedBigint(Class2,params){return new Class2({type:"bigint",coerce:true,...normalizeParams(params)})}function _int64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:false,format:"int64",...normalizeParams(params)})}function _uint64(Class2,params){return new Class2({type:"bigint",check:"bigint_format",abort:false,format:"uint64",...normalizeParams(params)})}function _symbol(Class2,params){return new Class2({type:"symbol",...normalizeParams(params)})}function _undefined2(Class2,params){return new Class2({type:"undefined",...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _any(Class2){return new Class2({type:"any"})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _void(Class2,params){return new Class2({type:"void",...normalizeParams(params)})}function _date(Class2,params){return new Class2({type:"date",...normalizeParams(params)})}function _coercedDate(Class2,params){return new Class2({type:"date",coerce:true,...normalizeParams(params)})}function _nan(Class2,params){return new Class2({type:"nan",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:false})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:true})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:false})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:true})}function _positive(params){return _gt(0,params)}function _negative(params){return _lt(0,params)}function _nonpositive(params){return _lte(0,params)}function _nonnegative(params){return _gte(0,params)}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxSize(maximum,params){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(params),maximum})}function _minSize(minimum,params){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(params),minimum})}function _size(size4,params){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(params),size:size4})}function _maxLength(maximum,params){const ch=new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum});return ch}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _property(property,schema,params){return new $ZodCheckProperty({check:"property",property,schema,...normalizeParams(params)})}function _mime(types,params){return new $ZodCheckMimeType({check:"mime_type",mime:types,...normalizeParams(params)})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite(input=>input.normalize(form))}function _trim(){return _overwrite(input=>input.trim())}function _toLowerCase(){return _overwrite(input=>input.toLowerCase())}function _toUpperCase(){return _overwrite(input=>input.toUpperCase())}function _slugify(){return _overwrite(input=>slugify(input))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _union(Class2,options,params){return new Class2({type:"union",options,...normalizeParams(params)})}function _xor(Class2,options,params){return new Class2({type:"union",options,inclusive:false,...normalizeParams(params)})}function _discriminatedUnion(Class2,discriminator,options,params){return new Class2({type:"union",options,discriminator,...normalizeParams(params)})}function _intersection(Class2,left,right){return new Class2({type:"intersection",left,right})}function _tuple(Class2,items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new Class2({type:"tuple",items,rest,...normalizeParams(params)})}function _record(Class2,keyType,valueType,params){return new Class2({type:"record",keyType,valueType,...normalizeParams(params)})}function _map(Class2,keyType,valueType,params){return new Class2({type:"map",keyType,valueType,...normalizeParams(params)})}function _set(Class2,valueType,params){return new Class2({type:"set",valueType,...normalizeParams(params)})}function _enum(Class2,values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new Class2({type:"enum",entries,...normalizeParams(params)})}function _nativeEnum(Class2,entries,params){return new Class2({type:"enum",entries,...normalizeParams(params)})}function _literal(Class2,value,params){return new Class2({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function _file(Class2,params){return new Class2({type:"file",...normalizeParams(params)})}function _transform(Class2,fn){return new Class2({type:"transform",transform:fn})}function _optional(Class2,innerType){return new Class2({type:"optional",innerType})}function _nullable(Class2,innerType){return new Class2({type:"nullable",innerType})}function _default(Class2,innerType,defaultValue){return new Class2({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function _nonoptional(Class2,innerType,params){return new Class2({type:"nonoptional",innerType,...normalizeParams(params)})}function _success(Class2,innerType){return new Class2({type:"success",innerType})}function _catch(Class2,innerType,catchValue){return new Class2({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function _pipe(Class2,in_,out){return new Class2({type:"pipe",in:in_,out})}function _readonly(Class2,innerType){return new Class2({type:"readonly",innerType})}function _templateLiteral(Class2,parts,params){return new Class2({type:"template_literal",parts,...normalizeParams(params)})}function _lazy(Class2,getter){return new Class2({type:"lazy",getter})}function _promise(Class2,innerType){return new Class2({type:"promise",innerType})}function _custom(Class2,fn,_params){const norm=normalizeParams(_params);norm.abort??(norm.abort=true);const schema=new Class2({type:"custom",check:"custom",fn,...norm});return schema}function _refine(Class2,fn,_params){const schema=new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)});return schema}function _superRefine(fn,params){const ch=_check(payload=>{payload.addIssue=issue2=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,ch._zod.def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");_issue.input??(_issue.input=payload.value);_issue.inst??(_issue.inst=ch);_issue.continue??(_issue.continue=!ch._zod.def.abort);payload.issues.push(issue(_issue))}};return fn(payload.value,payload)},params);return ch}function _check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function describe(description){const ch=new $ZodCheck({check:"describe"});ch._zod.onattach=[inst=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,description})}];ch._zod.check=()=>{};return ch}function meta(metadata){const ch=new $ZodCheck({check:"meta"});ch._zod.onattach=[inst=>{const existing=globalRegistry.get(inst)??{};globalRegistry.add(inst,{...existing,...metadata})}];ch._zod.check=()=>{};return ch}function _stringbool(Classes,_params){const params=normalizeParams(_params);let truthyArray=params.truthy??["true","1","yes","on","y","enabled"];let falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive"){truthyArray=truthyArray.map(v=>typeof v==="string"?v.toLowerCase():v);falsyArray=falsyArray.map(v=>typeof v==="string"?v.toLowerCase():v)}const truthySet=new Set(truthyArray);const falsySet=new Set(falsyArray);const _Codec=Classes.Codec??$ZodCodec;const _Boolean=Classes.Boolean??$ZodBoolean;const _String=Classes.String??$ZodString;const stringSchema=new _String({type:"string",error:params.error});const booleanSchema=new _Boolean({type:"boolean",error:params.error});const codec2=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:((input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data)){return true}else if(falsySet.has(data)){return false}else{payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec2,continue:false});return{}}}),reverseTransform:((input,_payload)=>{if(input===true){return truthyArray[0]||"true"}else{return falsyArray[0]||"false"}}),error:params.error});return codec2}function _stringFormat(Class2,format,fnOrRegex,_params={}){const params=normalizeParams(_params);const def={...normalizeParams(_params),check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:val=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp){def.pattern=fnOrRegex}const inst=new Class2(def);return inst}var TimePrecision;var init_api=__esm({"node_modules/zod/v4/core/api.js"(){"use strict";init_checks();init_registries();init_schemas();init_util();TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}}});function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,cycles:params?.cycles??"ref",reused:params?.reused??"inline",external:params?.external??void 0}}function process2(schema,ctx,_params={path:[],schemaPath:[]}){var _a4;const def=schema._zod.def;const seen=ctx.seen.get(schema);if(seen){seen.count++;const isCycle=_params.schemaPath.includes(schema);if(isCycle){seen.cycle=_params.path}return seen.schema}const result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result);const overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema){result.schema=overrideSchema}else{const params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema){schema._zod.processJSONSchema(ctx,result.schema,params)}else{const _json=result.schema;const processor=ctx.processors[def.type];if(!processor){throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`)}processor(schema,ctx,_json,params)}const parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;process2(parent,ctx,params);ctx.seen.get(parent).isParent=true}}const meta4=ctx.metadataRegistry.get(schema);if(meta4)Object.assign(result.schema,meta4);if(ctx.io==="input"&&isTransforming(schema)){delete result.schema.examples;delete result.schema.default}if(ctx.io==="input"&&"_prefault"in result.schema)(_a4=result.schema).default??(_a4.default=result.schema._prefault);delete result.schema._prefault;const _result=ctx.seen.get(schema);return _result.schema}function extractDefs(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const idToSchema=new Map;for(const entry of ctx.seen.entries()){const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){const existing=idToSchema.get(id);if(existing&&existing!==entry[0]){throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`)}idToSchema.set(id,entry[0])}}const makeURI=entry=>{const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){const externalId=ctx.external.registry.get(entry[0])?.id;const uriGenerator=ctx.external.uri??(id2=>id2);if(externalId){return{ref:uriGenerator(externalId)}}const id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;entry[1].defId=id;return{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${id}`}}if(entry[1]===root){return{ref:"#"}}const uriPrefix=`#`;const defUriPrefix=`${uriPrefix}/${defsSegment}/`;const defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}};const extractToDef=entry=>{if(entry[1].schema.$ref){return}const seen=entry[1];const{ref,defId}=makeURI(entry);seen.def={...seen.schema};if(defId)seen.defId=defId;const schema2=seen.schema;for(const key in schema2){delete schema2[key]}schema2.$ref=ref};if(ctx.cycles==="throw"){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.cycle){throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
|
|
2133
2133
|
|
|
2134
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=zodSchema=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema2=seen.def??seen.schema;const _cached={...schema2};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema2.allOf=schema2.allOf??[];schema2.allOf.push(refSchema)}else{Object.assign(schema2,refSchema)}Object.assign(schema2,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema2[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])){delete schema2[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema2.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])){delete schema2[key]}}}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}else{}if(ctx.external?.uri){const id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==void 0&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;defs[seen.defId]=seen.def}}if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"){return isTransforming(def.innerType,ctx)}if(def.type==="intersection"){return isTransforming(def.left,ctx)||isTransforming(def.right,ctx)}if(def.type==="record"||def.type==="map"){return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx)}if(def.type==="pipe"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod,createStandardJSONSchemaMethod;var init_to_json_schema=__esm({"node_modules/zod/v4/core/to-json-schema.js"(){"use strict";init_registries();createToJSONSchemaMethod=(schema,processors={})=>params=>{const ctx=initializeContext({...params,processors});process2(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{const{libraryOptions,target}=params??{};const ctx=initializeContext({...libraryOptions??{},target,io,processors});process2(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)}}});function toJSONSchema(input,params){if("_idmap"in input){const registry2=input;const ctx2=initializeContext({...params,processors:allProcessors});const defs={};for(const entry of registry2._idmap.entries()){const[_,schema]=entry;process2(schema,ctx2)}const schemas={};const external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(const entry of registry2._idmap.entries()){const[key,schema]=entry;extractDefs(ctx2,schema);schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){const defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}const ctx=initializeContext({...params,processors:allProcessors});process2(input,ctx);extractDefs(ctx,input);return finalize(ctx,input)}var formatMap,stringProcessor,numberProcessor,booleanProcessor,bigintProcessor,symbolProcessor,nullProcessor,undefinedProcessor,voidProcessor,neverProcessor,anyProcessor,unknownProcessor,dateProcessor,enumProcessor,literalProcessor,nanProcessor,templateLiteralProcessor,fileProcessor,successProcessor,customProcessor,functionProcessor,transformProcessor,mapProcessor,setProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,tupleProcessor,recordProcessor,nullableProcessor,nonoptionalProcessor,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,promiseProcessor,optionalProcessor,lazyProcessor,allProcessors;var init_json_schema_processors=__esm({"node_modules/zod/v4/core/json-schema-processors.js"(){"use strict";init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};stringProcessor=(schema,ctx,_json,_params)=>{const json3=_json;json3.type="string";const{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json3.minLength=minimum;if(typeof maximum==="number")json3.maxLength=maximum;if(format){json3.format=formatMap[format]??format;if(json3.format==="")delete json3.format;if(format==="time"){delete json3.format}}if(contentEncoding)json3.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){const regexes=[...patterns];if(regexes.length===1)json3.pattern=regexes[0].source;else if(regexes.length>1){json3.allOf=[...regexes.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}}};numberProcessor=(schema,ctx,_json,_params)=>{const json3=_json;const{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json3.type="integer";else json3.type="number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json3.minimum=exclusiveMinimum;json3.exclusiveMinimum=true}else{json3.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json3.minimum=minimum}if(exMax){if(legacy){json3.maximum=exclusiveMaximum;json3.exclusiveMaximum=true}else{json3.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json3.maximum=maximum}if(typeof multipleOf==="number")json3.multipleOf=multipleOf};booleanProcessor=(_schema,_ctx,json3,_params)=>{json3.type="boolean"};bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("BigInt cannot be represented in JSON Schema")}};symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Symbols cannot be represented in JSON Schema")}};nullProcessor=(_schema,ctx,json3,_params)=>{if(ctx.target==="openapi-3.0"){json3.type="string";json3.nullable=true;json3.enum=[null]}else{json3.type="null"}};undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Undefined cannot be represented in JSON Schema")}};voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Void cannot be represented in JSON Schema")}};neverProcessor=(_schema,_ctx,json3,_params)=>{json3.not={}};anyProcessor=(_schema,_ctx,_json,_params)=>{};unknownProcessor=(_schema,_ctx,_json,_params)=>{};dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Date cannot be represented in JSON Schema")}};enumProcessor=(schema,_ctx,json3,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.every(v=>typeof v==="number"))json3.type="number";if(values.every(v=>typeof v==="string"))json3.type="string";json3.enum=values};literalProcessor=(schema,ctx,json3,_params)=>{const def=schema._zod.def;const vals=[];for(const val of def.values){if(val===void 0){if(ctx.unrepresentable==="throw"){throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else{}}else if(typeof val==="bigint"){if(ctx.unrepresentable==="throw"){throw new Error("BigInt literals cannot be represented in JSON Schema")}else{vals.push(Number(val))}}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json3.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json3.enum=[val]}else{json3.const=val}}else{if(vals.every(v=>typeof v==="number"))json3.type="number";if(vals.every(v=>typeof v==="string"))json3.type="string";if(vals.every(v=>typeof v==="boolean"))json3.type="boolean";if(vals.every(v=>v===null))json3.type="null";json3.enum=vals}};nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("NaN cannot be represented in JSON Schema")}};templateLiteralProcessor=(schema,_ctx,json3,_params)=>{const _json=json3;const pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string";_json.pattern=pattern.source};fileProcessor=(schema,_ctx,json3,_params)=>{const _json=json3;const file2={type:"string",format:"binary",contentEncoding:"binary"};const{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file2.minLength=minimum;if(maximum!==void 0)file2.maxLength=maximum;if(mime){if(mime.length===1){file2.contentMediaType=mime[0];Object.assign(_json,file2)}else{Object.assign(_json,file2);_json.anyOf=mime.map(m=>({contentMediaType:m}))}}else{Object.assign(_json,file2)}};successProcessor=(_schema,_ctx,json3,_params)=>{json3.type="boolean"};customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Custom types cannot be represented in JSON Schema")}};functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Function types cannot be represented in JSON Schema")}};transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Transforms cannot be represented in JSON Schema")}};mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Map cannot be represented in JSON Schema")}};setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Set cannot be represented in JSON Schema")}};arrayProcessor=(schema,ctx,_json,params)=>{const json3=_json;const def=schema._zod.def;const{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json3.minItems=minimum;if(typeof maximum==="number")json3.maxItems=maximum;json3.type="array";json3.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})};objectProcessor=(schema,ctx,_json,params)=>{const json3=_json;const def=schema._zod.def;json3.type="object";json3.properties={};const shape2=def.shape;for(const key in shape2){json3.properties[key]=process2(shape2[key],ctx,{...params,path:[...params.path,"properties",key]})}const allKeys=new Set(Object.keys(shape2));const requiredKeys=new Set([...allKeys].filter(key=>{const v=def.shape[key]._zod;if(ctx.io==="input"){return v.optin===void 0}else{return v.optout===void 0}}));if(requiredKeys.size>0){json3.required=Array.from(requiredKeys)}if(def.catchall?._zod.def.type==="never"){json3.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json3.additionalProperties=false}else if(def.catchall){json3.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};unionProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x2,i)=>process2(x2,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json3.oneOf=options}else{json3.anyOf=options}};intersectionProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;const a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b2=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b2)?b2.allOf:[b2]];json3.allOf=allOf};tupleProcessor=(schema,ctx,_json,params)=>{const json3=_json;const def=schema._zod.def;json3.type="array";const prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items";const restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems";const prefixItems=def.items.map((x2,i)=>process2(x2,ctx,{...params,path:[...params.path,prefixPath,i]}));const rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(ctx.target==="draft-2020-12"){json3.prefixItems=prefixItems;if(rest){json3.items=rest}}else if(ctx.target==="openapi-3.0"){json3.items={anyOf:prefixItems};if(rest){json3.items.anyOf.push(rest)}json3.minItems=prefixItems.length;if(!rest){json3.maxItems=prefixItems.length}}else{json3.items=prefixItems;if(rest){json3.additionalItems=rest}}const{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json3.minItems=minimum;if(typeof maximum==="number")json3.maxItems=maximum};recordProcessor=(schema,ctx,_json,params)=>{const json3=_json;const def=schema._zod.def;json3.type="object";const keyType=def.keyType;const keyBag=keyType._zod.bag;const patterns=keyBag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){const valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json3.patternProperties={};for(const pattern of patterns){json3.patternProperties[pattern.source]=valueSchema}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json3.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]})}json3.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;if(keyValues){const validKeyValues=[...keyValues].filter(v=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json3.required=validKeyValues}}};nullableProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;const inner=process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json3.nullable=true}else{json3.anyOf=[inner,{type:"null"}]}};nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};defaultProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json3.default=JSON.parse(JSON.stringify(def.defaultValue))};prefaultProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io==="input")json3._prefault=JSON.parse(JSON.stringify(def.defaultValue))};catchProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}json3.default=catchValue};pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;process2(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};readonlyProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json3.readOnly=true};promiseProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};lazyProcessor=(schema,ctx,_json,params)=>{const innerType=schema._zod.innerType;process2(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}}});var JSONSchemaGenerator;var init_json_schema_generator=__esm({"node_modules/zod/v4/core/json-schema-generator.js"(){"use strict";init_json_schema_processors();init_to_json_schema();JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process2(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}extractDefs(this.ctx,schema);const result=finalize(this.ctx,schema);const{"~standard":_,...plainResult}=result;return plainResult}}}});var json_schema_exports={};var init_json_schema=__esm({"node_modules/zod/v4/core/json-schema.js"(){"use strict"}});var core_exports2={};__export(core_exports2,{$ZodAny:()=>$ZodAny,$ZodArray:()=>$ZodArray,$ZodAsyncError:()=>$ZodAsyncError,$ZodBase64:()=>$ZodBase64,$ZodBase64URL:()=>$ZodBase64URL,$ZodBigInt:()=>$ZodBigInt,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBoolean:()=>$ZodBoolean,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCUID:()=>$ZodCUID,$ZodCUID2:()=>$ZodCUID2,$ZodCatch:()=>$ZodCatch,$ZodCheck:()=>$ZodCheck,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCodec:()=>$ZodCodec,$ZodCustom:()=>$ZodCustom,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodDate:()=>$ZodDate,$ZodDefault:()=>$ZodDefault,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodE164:()=>$ZodE164,$ZodEmail:()=>$ZodEmail,$ZodEmoji:()=>$ZodEmoji,$ZodEncodeError:()=>$ZodEncodeError,$ZodEnum:()=>$ZodEnum,$ZodError:()=>$ZodError,$ZodExactOptional:()=>$ZodExactOptional,$ZodFile:()=>$ZodFile,$ZodFunction:()=>$ZodFunction,$ZodGUID:()=>$ZodGUID,$ZodIPv4:()=>$ZodIPv4,$ZodIPv6:()=>$ZodIPv6,$ZodISODate:()=>$ZodISODate,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODuration:()=>$ZodISODuration,$ZodISOTime:()=>$ZodISOTime,$ZodIntersection:()=>$ZodIntersection,$ZodJWT:()=>$ZodJWT,$ZodKSUID:()=>$ZodKSUID,$ZodLazy:()=>$ZodLazy,$ZodLiteral:()=>$ZodLiteral,$ZodMAC:()=>$ZodMAC,$ZodMap:()=>$ZodMap,$ZodNaN:()=>$ZodNaN,$ZodNanoID:()=>$ZodNanoID,$ZodNever:()=>$ZodNever,$ZodNonOptional:()=>$ZodNonOptional,$ZodNull:()=>$ZodNull,$ZodNullable:()=>$ZodNullable,$ZodNumber:()=>$ZodNumber,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodObject:()=>$ZodObject,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodOptional:()=>$ZodOptional,$ZodPipe:()=>$ZodPipe,$ZodPrefault:()=>$ZodPrefault,$ZodPreprocess:()=>$ZodPreprocess,$ZodPromise:()=>$ZodPromise,$ZodReadonly:()=>$ZodReadonly,$ZodRealError:()=>$ZodRealError,$ZodRecord:()=>$ZodRecord,$ZodRegistry:()=>$ZodRegistry,$ZodSet:()=>$ZodSet,$ZodString:()=>$ZodString,$ZodStringFormat:()=>$ZodStringFormat,$ZodSuccess:()=>$ZodSuccess,$ZodSymbol:()=>$ZodSymbol,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodTransform:()=>$ZodTransform,$ZodTuple:()=>$ZodTuple,$ZodType:()=>$ZodType,$ZodULID:()=>$ZodULID,$ZodURL:()=>$ZodURL,$ZodUUID:()=>$ZodUUID,$ZodUndefined:()=>$ZodUndefined,$ZodUnion:()=>$ZodUnion,$ZodUnknown:()=>$ZodUnknown,$ZodVoid:()=>$ZodVoid,$ZodXID:()=>$ZodXID,$ZodXor:()=>$ZodXor,$brand:()=>$brand,$constructor:()=>$constructor,$input:()=>$input,$output:()=>$output,Doc:()=>Doc,JSONSchema:()=>json_schema_exports,JSONSchemaGenerator:()=>JSONSchemaGenerator,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,_any:()=>_any,_array:()=>_array,_base64:()=>_base64,_base64url:()=>_base64url,_bigint:()=>_bigint,_boolean:()=>_boolean,_catch:()=>_catch,_check:()=>_check,_cidrv4:()=>_cidrv4,_cidrv6:()=>_cidrv6,_coercedBigint:()=>_coercedBigint,_coercedBoolean:()=>_coercedBoolean,_coercedDate:()=>_coercedDate,_coercedNumber:()=>_coercedNumber,_coercedString:()=>_coercedString,_cuid:()=>_cuid,_cuid2:()=>_cuid2,_custom:()=>_custom,_date:()=>_date,_decode:()=>_decode,_decodeAsync:()=>_decodeAsync,_default:()=>_default,_discriminatedUnion:()=>_discriminatedUnion,_e164:()=>_e164,_email:()=>_email,_emoji:()=>_emoji2,_encode:()=>_encode,_encodeAsync:()=>_encodeAsync,_endsWith:()=>_endsWith,_enum:()=>_enum,_file:()=>_file,_float32:()=>_float32,_float64:()=>_float64,_gt:()=>_gt,_gte:()=>_gte,_guid:()=>_guid,_includes:()=>_includes,_int:()=>_int,_int32:()=>_int32,_int64:()=>_int64,_intersection:()=>_intersection,_ipv4:()=>_ipv4,_ipv6:()=>_ipv6,_isoDate:()=>_isoDate,_isoDateTime:()=>_isoDateTime,_isoDuration:()=>_isoDuration,_isoTime:()=>_isoTime,_jwt:()=>_jwt,_ksuid:()=>_ksuid,_lazy:()=>_lazy,_length:()=>_length,_literal:()=>_literal,_lowercase:()=>_lowercase,_lt:()=>_lt,_lte:()=>_lte,_mac:()=>_mac,_map:()=>_map,_max:()=>_lte,_maxLength:()=>_maxLength,_maxSize:()=>_maxSize,_mime:()=>_mime,_min:()=>_gte,_minLength:()=>_minLength,_minSize:()=>_minSize,_multipleOf:()=>_multipleOf,_nan:()=>_nan,_nanoid:()=>_nanoid,_nativeEnum:()=>_nativeEnum,_negative:()=>_negative,_never:()=>_never,_nonnegative:()=>_nonnegative,_nonoptional:()=>_nonoptional,_nonpositive:()=>_nonpositive,_normalize:()=>_normalize,_null:()=>_null2,_nullable:()=>_nullable,_number:()=>_number,_optional:()=>_optional,_overwrite:()=>_overwrite,_parse:()=>_parse,_parseAsync:()=>_parseAsync,_pipe:()=>_pipe,_positive:()=>_positive,_promise:()=>_promise,_property:()=>_property,_readonly:()=>_readonly,_record:()=>_record,_refine:()=>_refine,_regex:()=>_regex,_safeDecode:()=>_safeDecode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeEncode:()=>_safeEncode,_safeEncodeAsync:()=>_safeEncodeAsync,_safeParse:()=>_safeParse,_safeParseAsync:()=>_safeParseAsync,_set:()=>_set,_size:()=>_size,_slugify:()=>_slugify,_startsWith:()=>_startsWith,_string:()=>_string,_stringFormat:()=>_stringFormat,_stringbool:()=>_stringbool,_success:()=>_success,_superRefine:()=>_superRefine,_symbol:()=>_symbol,_templateLiteral:()=>_templateLiteral,_toLowerCase:()=>_toLowerCase,_toUpperCase:()=>_toUpperCase,_transform:()=>_transform,_trim:()=>_trim,_tuple:()=>_tuple,_uint32:()=>_uint32,_uint64:()=>_uint64,_ulid:()=>_ulid,_undefined:()=>_undefined2,_union:()=>_union,_unknown:()=>_unknown,_uppercase:()=>_uppercase,_url:()=>_url,_uuid:()=>_uuid,_uuidv4:()=>_uuidv4,_uuidv6:()=>_uuidv6,_uuidv7:()=>_uuidv7,_void:()=>_void,_xid:()=>_xid,_xor:()=>_xor,clone:()=>clone,config:()=>config,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe,encode:()=>encode,encodeAsync:()=>encodeAsync,extractDefs:()=>extractDefs,finalize:()=>finalize,flattenError:()=>flattenError,formatError:()=>formatError,globalConfig:()=>globalConfig,globalRegistry:()=>globalRegistry,initializeContext:()=>initializeContext,isValidBase64:()=>isValidBase64,isValidBase64URL:()=>isValidBase64URL,isValidJWT:()=>isValidJWT,locales:()=>locales_exports,meta:()=>meta,parse:()=>parse2,parseAsync:()=>parseAsync,prettifyError:()=>prettifyError,process:()=>process2,regexes:()=>regexes_exports,registry:()=>registry,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,toDotPath:()=>toDotPath,toJSONSchema:()=>toJSONSchema,treeifyError:()=>treeifyError,util:()=>util_exports,version:()=>version2});var init_core2=__esm({"node_modules/zod/v4/core/index.js"(){"use strict";init_core();init_parse();init_errors2();init_schemas();init_checks();init_versions();init_util();init_regexes();init_locales();init_registries();init_doc();init_api();init_to_json_schema();init_json_schema_processors();init_json_schema_generator();init_json_schema()}});var init_parse2=__esm({"node_modules/zod/v4/mini/parse.js"(){"use strict";init_core2()}});function string2(params){return _string(ZodMiniString,params)}function email2(params){return _email(ZodMiniEmail,params)}function guid2(params){return _guid(ZodMiniGUID,params)}function uuid2(params){return _uuid(ZodMiniUUID,params)}function uuidv4(params){return _uuidv4(ZodMiniUUID,params)}function uuidv6(params){return _uuidv6(ZodMiniUUID,params)}function uuidv7(params){return _uuidv7(ZodMiniUUID,params)}function url(params){return _url(ZodMiniURL,params)}function httpUrl(params){return _url(ZodMiniURL,{protocol:regexes_exports.httpProtocol,hostname:regexes_exports.domain,...normalizeParams(params)})}function emoji2(params){return _emoji2(ZodMiniEmoji,params)}function nanoid2(params){return _nanoid(ZodMiniNanoID,params)}function cuid3(params){return _cuid(ZodMiniCUID,params)}function cuid22(params){return _cuid2(ZodMiniCUID2,params)}function ulid2(params){return _ulid(ZodMiniULID,params)}function xid2(params){return _xid(ZodMiniXID,params)}function ksuid2(params){return _ksuid(ZodMiniKSUID,params)}function ipv42(params){return _ipv4(ZodMiniIPv4,params)}function ipv62(params){return _ipv6(ZodMiniIPv6,params)}function cidrv42(params){return _cidrv4(ZodMiniCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodMiniCIDRv6,params)}function mac2(params){return _mac(ZodMiniMAC,params)}function base642(params){return _base64(ZodMiniBase64,params)}function base64url2(params){return _base64url(ZodMiniBase64URL,params)}function e1642(params){return _e164(ZodMiniE164,params)}function jwt(params){return _jwt(ZodMiniJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodMiniCustomStringFormat,format,fnOrRegex,_params)}function hostname3(_params){return _stringFormat(ZodMiniCustomStringFormat,"hostname",regexes_exports.hostname,_params)}function hex2(_params){return _stringFormat(ZodMiniCustomStringFormat,"hex",regexes_exports.hex,_params)}function hash(alg,params){const enc=params?.enc??"hex";const format=`${alg}_${enc}`;const regex=regexes_exports[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodMiniCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodMiniNumber,params)}function int(params){return _int(ZodMiniNumberFormat,params)}function float32(params){return _float32(ZodMiniNumberFormat,params)}function float64(params){return _float64(ZodMiniNumberFormat,params)}function int32(params){return _int32(ZodMiniNumberFormat,params)}function uint32(params){return _uint32(ZodMiniNumberFormat,params)}function boolean2(params){return _boolean(ZodMiniBoolean,params)}function bigint2(params){return _bigint(ZodMiniBigInt,params)}function int64(params){return _int64(ZodMiniBigIntFormat,params)}function uint64(params){return _uint64(ZodMiniBigIntFormat,params)}function symbol(params){return _symbol(ZodMiniSymbol,params)}function _undefined3(params){return _undefined2(ZodMiniUndefined,params)}function _null3(params){return _null2(ZodMiniNull,params)}function any(){return _any(ZodMiniAny)}function unknown(){return _unknown(ZodMiniUnknown)}function never(params){return _never(ZodMiniNever,params)}function _void2(params){return _void(ZodMiniVoid,params)}function date2(params){return _date(ZodMiniDate,params)}function array(element,params){return new ZodMiniArray({type:"array",element,...normalizeParams(params)})}function keyof(schema){const shape2=schema._zod.def.shape;return _enum2(Object.keys(shape2))}function object(shape2,params){const def={type:"object",shape:shape2??{},...normalizeParams(params)};return new ZodMiniObject(def)}function strictObject(shape2,params){return new ZodMiniObject({type:"object",shape:shape2,catchall:never(),...normalizeParams(params)})}function looseObject(shape2,params){return new ZodMiniObject({type:"object",shape:shape2,catchall:unknown(),...normalizeParams(params)})}function extend2(schema,shape2){return extend(schema,shape2)}function safeExtend2(schema,shape2){return safeExtend(schema,shape2)}function merge2(schema,shape2){return extend(schema,shape2)}function pick2(schema,mask){return pick(schema,mask)}function omit2(schema,mask){return omit(schema,mask)}function partial2(schema,mask){return partial(ZodMiniOptional,schema,mask)}function required2(schema,mask){return required(ZodMiniNonOptional,schema,mask)}function catchall(inst,catchall2){return inst.clone({...inst._zod.def,catchall:catchall2})}function union(options,params){return new ZodMiniUnion({type:"union",options,...normalizeParams(params)})}function xor(options,params){return new ZodMiniXor({type:"union",options,inclusive:false,...normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodMiniDiscriminatedUnion({type:"union",options,discriminator,...normalizeParams(params)})}function intersection(left,right){return new ZodMiniIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new ZodMiniTuple({type:"tuple",items,rest,...normalizeParams(params)})}function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodMiniRecord({type:"record",keyType:string2(),valueType:keyType,...normalizeParams(valueType)})}return new ZodMiniRecord({type:"record",keyType,valueType,...normalizeParams(params)})}function partialRecord(keyType,valueType,params){const k2=clone(keyType);k2._zod.values=void 0;return new ZodMiniRecord({type:"record",keyType:k2,valueType,...normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodMiniRecord({type:"record",keyType,valueType,mode:"loose",...normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMiniMap({type:"map",keyType,valueType,...normalizeParams(params)})}function set(valueType,params){return new ZodMiniSet({type:"set",valueType,...normalizeParams(params)})}function _enum2(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodMiniEnum({type:"enum",entries,...normalizeParams(params)})}function nativeEnum(entries,params){return new ZodMiniEnum({type:"enum",entries,...normalizeParams(params)})}function literal(value,params){return new ZodMiniLiteral({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function file(params){return _file(ZodMiniFile,params)}function transform(fn){return new ZodMiniTransform({type:"transform",transform:fn})}function optional(innerType){return new ZodMiniOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodMiniExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodMiniNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodMiniDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodMiniPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodMiniNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}function success(innerType){return new ZodMiniSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodMiniCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan(params){return _nan(ZodMiniNaN,params)}function pipe(in_,out){return new ZodMiniPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodMiniCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){const def=codec2._zod.def;return new ZodMiniCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}function readonly(innerType){return new ZodMiniReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodMiniTemplateLiteral({type:"template_literal",parts,...normalizeParams(params)})}function _lazy2(getter){return new ZodMiniLazy({type:"lazy",getter})}function promise(innerType){return new ZodMiniPromise({type:"promise",innerType})}function check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function custom(fn,_params){return _custom(ZodMiniCustom,fn??(()=>true),_params)}function refine(fn,_params={}){return _refine(ZodMiniCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function _instanceof(cls,params={}){const inst=custom(data=>data instanceof cls,params);inst._zod.bag.Class=cls;inst._zod.check=payload=>{if(!(payload.value instanceof cls)){payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})}};return inst}function json2(){const jsonSchema=_lazy2(()=>{return union([string2(),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function _function(params){return new ZodMiniFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodMiniType,ZodMiniString,ZodMiniStringFormat,ZodMiniEmail,ZodMiniGUID,ZodMiniUUID,ZodMiniURL,ZodMiniEmoji,ZodMiniNanoID,ZodMiniCUID,ZodMiniCUID2,ZodMiniULID,ZodMiniXID,ZodMiniKSUID,ZodMiniIPv4,ZodMiniIPv6,ZodMiniCIDRv4,ZodMiniCIDRv6,ZodMiniMAC,ZodMiniBase64,ZodMiniBase64URL,ZodMiniE164,ZodMiniJWT,ZodMiniCustomStringFormat,ZodMiniNumber,ZodMiniNumberFormat,ZodMiniBoolean,ZodMiniBigInt,ZodMiniBigIntFormat,ZodMiniSymbol,ZodMiniUndefined,ZodMiniNull,ZodMiniAny,ZodMiniUnknown,ZodMiniNever,ZodMiniVoid,ZodMiniDate,ZodMiniArray,ZodMiniObject,ZodMiniUnion,ZodMiniXor,ZodMiniDiscriminatedUnion,ZodMiniIntersection,ZodMiniTuple,ZodMiniRecord,ZodMiniMap,ZodMiniSet,ZodMiniEnum,ZodMiniLiteral,ZodMiniFile,ZodMiniTransform,ZodMiniOptional,ZodMiniExactOptional,ZodMiniNullable,ZodMiniDefault,ZodMiniPrefault,ZodMiniNonOptional,ZodMiniSuccess,ZodMiniCatch,ZodMiniNaN,ZodMiniPipe,ZodMiniCodec,ZodMiniReadonly,ZodMiniTemplateLiteral,ZodMiniLazy,ZodMiniPromise,ZodMiniCustom,describe2,meta2,stringbool,ZodMiniFunction;var init_schemas2=__esm({"node_modules/zod/v4/mini/schemas.js"(){"use strict";init_core2();init_util();init_parse2();ZodMiniType=$constructor("ZodMiniType",(inst,def)=>{if(!inst._zod)throw new Error("Uninitialized schema in ZodMiniType.");$ZodType.init(inst,def);inst.def=def;inst.type=def.type;inst.parse=(data,params)=>parse2(inst,data,params,{callee:inst.parse});inst.safeParse=(data,params)=>safeParse(inst,data,params);inst.parseAsync=async(data,params)=>parseAsync(inst,data,params,{callee:inst.parseAsync});inst.safeParseAsync=async(data,params)=>safeParseAsync(inst,data,params);inst.check=(...checks)=>{return inst.clone({...def,checks:[...def.checks??[],...checks.map(ch=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]},{parent:true})};inst.with=inst.check;inst.clone=(_def,params)=>clone(inst,_def,params);inst.brand=()=>inst;inst.register=((reg,meta4)=>{reg.add(inst,meta4);return inst});inst.apply=fn=>fn(inst)});ZodMiniString=$constructor("ZodMiniString",(inst,def)=>{$ZodString.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniStringFormat=$constructor("ZodMiniStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);ZodMiniString.init(inst,def)});ZodMiniEmail=$constructor("ZodMiniEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniGUID=$constructor("ZodMiniGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniUUID=$constructor("ZodMiniUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniURL=$constructor("ZodMiniURL",(inst,def)=>{$ZodURL.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniEmoji=$constructor("ZodMiniEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniNanoID=$constructor("ZodMiniNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCUID=$constructor("ZodMiniCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCUID2=$constructor("ZodMiniCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniULID=$constructor("ZodMiniULID",(inst,def)=>{$ZodULID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniXID=$constructor("ZodMiniXID",(inst,def)=>{$ZodXID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniKSUID=$constructor("ZodMiniKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniIPv4=$constructor("ZodMiniIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniIPv6=$constructor("ZodMiniIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCIDRv4=$constructor("ZodMiniCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCIDRv6=$constructor("ZodMiniCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniMAC=$constructor("ZodMiniMAC",(inst,def)=>{$ZodMAC.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniBase64=$constructor("ZodMiniBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniBase64URL=$constructor("ZodMiniBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniE164=$constructor("ZodMiniE164",(inst,def)=>{$ZodE164.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniJWT=$constructor("ZodMiniJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCustomStringFormat=$constructor("ZodMiniCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniNumber=$constructor("ZodMiniNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNumberFormat=$constructor("ZodMiniNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodMiniNumber.init(inst,def)});ZodMiniBoolean=$constructor("ZodMiniBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniBigInt=$constructor("ZodMiniBigInt",(inst,def)=>{$ZodBigInt.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniBigIntFormat=$constructor("ZodMiniBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def);ZodMiniBigInt.init(inst,def)});ZodMiniSymbol=$constructor("ZodMiniSymbol",(inst,def)=>{$ZodSymbol.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniUndefined=$constructor("ZodMiniUndefined",(inst,def)=>{$ZodUndefined.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNull=$constructor("ZodMiniNull",(inst,def)=>{$ZodNull.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniAny=$constructor("ZodMiniAny",(inst,def)=>{$ZodAny.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniUnknown=$constructor("ZodMiniUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNever=$constructor("ZodMiniNever",(inst,def)=>{$ZodNever.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniVoid=$constructor("ZodMiniVoid",(inst,def)=>{$ZodVoid.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniDate=$constructor("ZodMiniDate",(inst,def)=>{$ZodDate.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniArray=$constructor("ZodMiniArray",(inst,def)=>{$ZodArray.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniObject=$constructor("ZodMiniObject",(inst,def)=>{$ZodObject.init(inst,def);ZodMiniType.init(inst,def);defineLazy(inst,"shape",()=>def.shape)});ZodMiniUnion=$constructor("ZodMiniUnion",(inst,def)=>{$ZodUnion.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniXor=$constructor("ZodMiniXor",(inst,def)=>{ZodMiniUnion.init(inst,def);$ZodXor.init(inst,def)});ZodMiniDiscriminatedUnion=$constructor("ZodMiniDiscriminatedUnion",(inst,def)=>{$ZodDiscriminatedUnion.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniIntersection=$constructor("ZodMiniIntersection",(inst,def)=>{$ZodIntersection.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniTuple=$constructor("ZodMiniTuple",(inst,def)=>{$ZodTuple.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniRecord=$constructor("ZodMiniRecord",(inst,def)=>{$ZodRecord.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniMap=$constructor("ZodMiniMap",(inst,def)=>{$ZodMap.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniSet=$constructor("ZodMiniSet",(inst,def)=>{$ZodSet.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniEnum=$constructor("ZodMiniEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodMiniType.init(inst,def);inst.options=Object.values(def.entries)});ZodMiniLiteral=$constructor("ZodMiniLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniFile=$constructor("ZodMiniFile",(inst,def)=>{$ZodFile.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniTransform=$constructor("ZodMiniTransform",(inst,def)=>{$ZodTransform.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniOptional=$constructor("ZodMiniOptional",(inst,def)=>{$ZodOptional.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniExactOptional=$constructor("ZodMiniExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNullable=$constructor("ZodMiniNullable",(inst,def)=>{$ZodNullable.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniDefault=$constructor("ZodMiniDefault",(inst,def)=>{$ZodDefault.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniPrefault=$constructor("ZodMiniPrefault",(inst,def)=>{$ZodPrefault.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNonOptional=$constructor("ZodMiniNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniSuccess=$constructor("ZodMiniSuccess",(inst,def)=>{$ZodSuccess.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniCatch=$constructor("ZodMiniCatch",(inst,def)=>{$ZodCatch.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNaN=$constructor("ZodMiniNaN",(inst,def)=>{$ZodNaN.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniPipe=$constructor("ZodMiniPipe",(inst,def)=>{$ZodPipe.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniCodec=$constructor("ZodMiniCodec",(inst,def)=>{ZodMiniPipe.init(inst,def);$ZodCodec.init(inst,def)});ZodMiniReadonly=$constructor("ZodMiniReadonly",(inst,def)=>{$ZodReadonly.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniTemplateLiteral=$constructor("ZodMiniTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniLazy=$constructor("ZodMiniLazy",(inst,def)=>{$ZodLazy.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniPromise=$constructor("ZodMiniPromise",(inst,def)=>{$ZodPromise.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniCustom=$constructor("ZodMiniCustom",(inst,def)=>{$ZodCustom.init(inst,def);ZodMiniType.init(inst,def)});describe2=describe;meta2=meta;stringbool=(...args)=>_stringbool({Codec:ZodMiniCodec,Boolean:ZodMiniBoolean,String:ZodMiniString},...args);ZodMiniFunction=$constructor("ZodMiniFunction",(inst,def)=>{$ZodFunction.init(inst,def);ZodMiniType.init(inst,def)})}});var init_checks2=__esm({"node_modules/zod/v4/mini/checks.js"(){"use strict";init_core2()}});var iso_exports={};__export(iso_exports,{ZodMiniISODate:()=>ZodMiniISODate,ZodMiniISODateTime:()=>ZodMiniISODateTime,ZodMiniISODuration:()=>ZodMiniISODuration,ZodMiniISOTime:()=>ZodMiniISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodMiniISODateTime,params)}function date3(params){return _isoDate(ZodMiniISODate,params)}function time2(params){return _isoTime(ZodMiniISOTime,params)}function duration2(params){return _isoDuration(ZodMiniISODuration,params)}var ZodMiniISODateTime,ZodMiniISODate,ZodMiniISOTime,ZodMiniISODuration;var init_iso=__esm({"node_modules/zod/v4/mini/iso.js"(){"use strict";init_core2();init_schemas2();ZodMiniISODateTime=$constructor("ZodMiniISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniISODate=$constructor("ZodMiniISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniISOTime=$constructor("ZodMiniISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniISODuration=$constructor("ZodMiniISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodMiniStringFormat.init(inst,def)})}});var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodMiniString,params)}function number3(params){return _coercedNumber(ZodMiniNumber,params)}function boolean3(params){return _coercedBoolean(ZodMiniBoolean,params)}function bigint3(params){return _coercedBigint(ZodMiniBigInt,params)}function date4(params){return _coercedDate(ZodMiniDate,params)}var init_coerce=__esm({"node_modules/zod/v4/mini/coerce.js"(){"use strict";init_core2();init_schemas2()}});var external_exports={};__export(external_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodMiniAny:()=>ZodMiniAny,ZodMiniArray:()=>ZodMiniArray,ZodMiniBase64:()=>ZodMiniBase64,ZodMiniBase64URL:()=>ZodMiniBase64URL,ZodMiniBigInt:()=>ZodMiniBigInt,ZodMiniBigIntFormat:()=>ZodMiniBigIntFormat,ZodMiniBoolean:()=>ZodMiniBoolean,ZodMiniCIDRv4:()=>ZodMiniCIDRv4,ZodMiniCIDRv6:()=>ZodMiniCIDRv6,ZodMiniCUID:()=>ZodMiniCUID,ZodMiniCUID2:()=>ZodMiniCUID2,ZodMiniCatch:()=>ZodMiniCatch,ZodMiniCodec:()=>ZodMiniCodec,ZodMiniCustom:()=>ZodMiniCustom,ZodMiniCustomStringFormat:()=>ZodMiniCustomStringFormat,ZodMiniDate:()=>ZodMiniDate,ZodMiniDefault:()=>ZodMiniDefault,ZodMiniDiscriminatedUnion:()=>ZodMiniDiscriminatedUnion,ZodMiniE164:()=>ZodMiniE164,ZodMiniEmail:()=>ZodMiniEmail,ZodMiniEmoji:()=>ZodMiniEmoji,ZodMiniEnum:()=>ZodMiniEnum,ZodMiniExactOptional:()=>ZodMiniExactOptional,ZodMiniFile:()=>ZodMiniFile,ZodMiniFunction:()=>ZodMiniFunction,ZodMiniGUID:()=>ZodMiniGUID,ZodMiniIPv4:()=>ZodMiniIPv4,ZodMiniIPv6:()=>ZodMiniIPv6,ZodMiniISODate:()=>ZodMiniISODate,ZodMiniISODateTime:()=>ZodMiniISODateTime,ZodMiniISODuration:()=>ZodMiniISODuration,ZodMiniISOTime:()=>ZodMiniISOTime,ZodMiniIntersection:()=>ZodMiniIntersection,ZodMiniJWT:()=>ZodMiniJWT,ZodMiniKSUID:()=>ZodMiniKSUID,ZodMiniLazy:()=>ZodMiniLazy,ZodMiniLiteral:()=>ZodMiniLiteral,ZodMiniMAC:()=>ZodMiniMAC,ZodMiniMap:()=>ZodMiniMap,ZodMiniNaN:()=>ZodMiniNaN,ZodMiniNanoID:()=>ZodMiniNanoID,ZodMiniNever:()=>ZodMiniNever,ZodMiniNonOptional:()=>ZodMiniNonOptional,ZodMiniNull:()=>ZodMiniNull,ZodMiniNullable:()=>ZodMiniNullable,ZodMiniNumber:()=>ZodMiniNumber,ZodMiniNumberFormat:()=>ZodMiniNumberFormat,ZodMiniObject:()=>ZodMiniObject,ZodMiniOptional:()=>ZodMiniOptional,ZodMiniPipe:()=>ZodMiniPipe,ZodMiniPrefault:()=>ZodMiniPrefault,ZodMiniPromise:()=>ZodMiniPromise,ZodMiniReadonly:()=>ZodMiniReadonly,ZodMiniRecord:()=>ZodMiniRecord,ZodMiniSet:()=>ZodMiniSet,ZodMiniString:()=>ZodMiniString,ZodMiniStringFormat:()=>ZodMiniStringFormat,ZodMiniSuccess:()=>ZodMiniSuccess,ZodMiniSymbol:()=>ZodMiniSymbol,ZodMiniTemplateLiteral:()=>ZodMiniTemplateLiteral,ZodMiniTransform:()=>ZodMiniTransform,ZodMiniTuple:()=>ZodMiniTuple,ZodMiniType:()=>ZodMiniType,ZodMiniULID:()=>ZodMiniULID,ZodMiniURL:()=>ZodMiniURL,ZodMiniUUID:()=>ZodMiniUUID,ZodMiniUndefined:()=>ZodMiniUndefined,ZodMiniUnion:()=>ZodMiniUnion,ZodMiniUnknown:()=>ZodMiniUnknown,ZodMiniVoid:()=>ZodMiniVoid,ZodMiniXID:()=>ZodMiniXID,ZodMiniXor:()=>ZodMiniXor,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,catchall:()=>catchall,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>coerce_exports,config:()=>config,core:()=>core_exports2,cuid:()=>cuid3,cuid2:()=>cuid22,custom:()=>custom,date:()=>date2,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode,encodeAsync:()=>encodeAsync,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,extend:()=>extend2,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,function:()=>_function,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname3,httpUrl:()=>httpUrl,includes:()=>_includes,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>iso_exports,json:()=>json2,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>_lazy2,length:()=>_length,literal:()=>literal,locales:()=>locales_exports,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,maximum:()=>_lte,merge:()=>merge2,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,minimum:()=>_gte,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,omit:()=>omit2,optional:()=>optional,overwrite:()=>_overwrite,parse:()=>parse2,parseAsync:()=>parseAsync,partial:()=>partial2,partialRecord:()=>partialRecord,pick:()=>pick2,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,prettifyError:()=>prettifyError,promise:()=>promise,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>regexes_exports,registry:()=>registry,required:()=>required2,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeExtend:()=>safeExtend2,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,set:()=>set,size:()=>_size,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>util_exports,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var init_external=__esm({"node_modules/zod/v4/mini/external.js"(){"use strict";init_core2();init_parse2();init_schemas2();init_checks2();init_core2();init_json_schema_processors();init_locales();init_iso();init_iso();init_coerce()}});var init_mini=__esm({"node_modules/zod/mini/index.js"(){"use strict";init_external();init_external()}});var zod_exports={};__export(zod_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodMiniAny:()=>ZodMiniAny,ZodMiniArray:()=>ZodMiniArray,ZodMiniBase64:()=>ZodMiniBase64,ZodMiniBase64URL:()=>ZodMiniBase64URL,ZodMiniBigInt:()=>ZodMiniBigInt,ZodMiniBigIntFormat:()=>ZodMiniBigIntFormat,ZodMiniBoolean:()=>ZodMiniBoolean,ZodMiniCIDRv4:()=>ZodMiniCIDRv4,ZodMiniCIDRv6:()=>ZodMiniCIDRv6,ZodMiniCUID:()=>ZodMiniCUID,ZodMiniCUID2:()=>ZodMiniCUID2,ZodMiniCatch:()=>ZodMiniCatch,ZodMiniCodec:()=>ZodMiniCodec,ZodMiniCustom:()=>ZodMiniCustom,ZodMiniCustomStringFormat:()=>ZodMiniCustomStringFormat,ZodMiniDate:()=>ZodMiniDate,ZodMiniDefault:()=>ZodMiniDefault,ZodMiniDiscriminatedUnion:()=>ZodMiniDiscriminatedUnion,ZodMiniE164:()=>ZodMiniE164,ZodMiniEmail:()=>ZodMiniEmail,ZodMiniEmoji:()=>ZodMiniEmoji,ZodMiniEnum:()=>ZodMiniEnum,ZodMiniExactOptional:()=>ZodMiniExactOptional,ZodMiniFile:()=>ZodMiniFile,ZodMiniFunction:()=>ZodMiniFunction,ZodMiniGUID:()=>ZodMiniGUID,ZodMiniIPv4:()=>ZodMiniIPv4,ZodMiniIPv6:()=>ZodMiniIPv6,ZodMiniISODate:()=>ZodMiniISODate,ZodMiniISODateTime:()=>ZodMiniISODateTime,ZodMiniISODuration:()=>ZodMiniISODuration,ZodMiniISOTime:()=>ZodMiniISOTime,ZodMiniIntersection:()=>ZodMiniIntersection,ZodMiniJWT:()=>ZodMiniJWT,ZodMiniKSUID:()=>ZodMiniKSUID,ZodMiniLazy:()=>ZodMiniLazy,ZodMiniLiteral:()=>ZodMiniLiteral,ZodMiniMAC:()=>ZodMiniMAC,ZodMiniMap:()=>ZodMiniMap,ZodMiniNaN:()=>ZodMiniNaN,ZodMiniNanoID:()=>ZodMiniNanoID,ZodMiniNever:()=>ZodMiniNever,ZodMiniNonOptional:()=>ZodMiniNonOptional,ZodMiniNull:()=>ZodMiniNull,ZodMiniNullable:()=>ZodMiniNullable,ZodMiniNumber:()=>ZodMiniNumber,ZodMiniNumberFormat:()=>ZodMiniNumberFormat,ZodMiniObject:()=>ZodMiniObject,ZodMiniOptional:()=>ZodMiniOptional,ZodMiniPipe:()=>ZodMiniPipe,ZodMiniPrefault:()=>ZodMiniPrefault,ZodMiniPromise:()=>ZodMiniPromise,ZodMiniReadonly:()=>ZodMiniReadonly,ZodMiniRecord:()=>ZodMiniRecord,ZodMiniSet:()=>ZodMiniSet,ZodMiniString:()=>ZodMiniString,ZodMiniStringFormat:()=>ZodMiniStringFormat,ZodMiniSuccess:()=>ZodMiniSuccess,ZodMiniSymbol:()=>ZodMiniSymbol,ZodMiniTemplateLiteral:()=>ZodMiniTemplateLiteral,ZodMiniTransform:()=>ZodMiniTransform,ZodMiniTuple:()=>ZodMiniTuple,ZodMiniType:()=>ZodMiniType,ZodMiniULID:()=>ZodMiniULID,ZodMiniURL:()=>ZodMiniURL,ZodMiniUUID:()=>ZodMiniUUID,ZodMiniUndefined:()=>ZodMiniUndefined,ZodMiniUnion:()=>ZodMiniUnion,ZodMiniUnknown:()=>ZodMiniUnknown,ZodMiniVoid:()=>ZodMiniVoid,ZodMiniXID:()=>ZodMiniXID,ZodMiniXor:()=>ZodMiniXor,_default:()=>_default2,_function:()=>_function,address:()=>address,amount:()=>amount,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,catchall:()=>catchall,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>coerce_exports,config:()=>config,core:()=>core_exports2,cuid:()=>cuid3,cuid2:()=>cuid22,custom:()=>custom,date:()=>date2,datetime:()=>datetime3,datetimeInput:()=>datetimeInput,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode,encodeAsync:()=>encodeAsync,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,extend:()=>extend2,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,function:()=>_function,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash2,hex:()=>hex2,hostname:()=>hostname3,httpUrl:()=>httpUrl,includes:()=>_includes,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>iso_exports,json:()=>json2,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>_lazy2,length:()=>_length,literal:()=>literal,locales:()=>locales_exports,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,maximum:()=>_lte,merge:()=>merge2,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,minimum:()=>_gte,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,omit:()=>omit2,optional:()=>optional,overwrite:()=>_overwrite,parse:()=>parse2,parseAsync:()=>parseAsync,partial:()=>partial2,partialRecord:()=>partialRecord,period:()=>period,pick:()=>pick2,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,prettifyError:()=>prettifyError,promise:()=>promise,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>regexes_exports,registry:()=>registry,required:()=>required2,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeExtend:()=>safeExtend2,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,set:()=>set,signature:()=>signature,size:()=>_size,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toDate:()=>toDate,toDatetimeString:()=>toDatetimeString,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,unwrapOptional:()=>unwrapOptional,uppercase:()=>_uppercase,url:()=>url,util:()=>util_exports,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor,z:()=>external_exports});function amount(){return external_exports.string().check(external_exports.regex(/^\d+(\.\d+)?$/,"Invalid amount"))}function datetime3(){return external_exports.string().check(external_exports.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,"Invalid ISO 8601 datetime"))}function datetimeInput(message2="Invalid ISO 8601 datetime"){return external_exports.pipe(external_exports.union([datetime3(),external_exports.custom(value=>value instanceof Date)]),external_exports.transform(toDate)).check(external_exports.refine(value=>Number.isFinite(value.getTime()),message2))}function toDate(value){return value instanceof Date?value:new Date(value)}function toDatetimeString(value){if(!(value instanceof Date))return value;if(!Number.isFinite(value.getTime()))return"Invalid Date";return value.toISOString()}function address(){return external_exports.string().check(external_exports.regex(/^0x[0-9a-fA-F]{40}$/,"Invalid address"))}function hash2(){return external_exports.string().check(external_exports.regex(/^0x[0-9a-fA-F]{64}$/,"Invalid hash"))}function period(){return external_exports.string().check(external_exports.regex(/^(day|week|month|year|\d+)$/,"Invalid period"))}function signature(){return external_exports.string().check(external_exports.regex(/^0x[0-9a-fA-F]+$/,"Invalid signature"))}function unwrapOptional(schema){if(schema._zod.def.type==="optional")return schema._zod.def.innerType;return schema}var init_zod=__esm({"node_modules/mppx/dist/zod.js"(){"use strict";init_mini();init_mini()}});var Challenge_exports={};__export(Challenge_exports,{Schema:()=>Schema,deserialize:()=>deserialize2,deserializeList:()=>deserializeList,from:()=>from4,fromHeaders:()=>fromHeaders,fromHeadersList:()=>fromHeadersList,fromMethod:()=>fromMethod2,fromResponse:()=>fromResponse,fromResponseList:()=>fromResponseList,meta:()=>meta3,serialize:()=>serialize2,verify:()=>verify2});function from4(parameters,options){void options;const{description,digest,meta:meta4,method:methodName,intent,realm,request,secretKey}=parameters;const expires=parameters.expires?toDatetimeString(parameters.expires):void 0;const opaque=parameters.opaque??(meta4!==void 0?serialize(meta4):void 0);const id=secretKey?computeId({...parameters,expires,...meta4!==void 0&&{meta:meta4},opaque},{secretKey}):parameters.id;return Schema.parse({id,realm,method:methodName,intent,request,...description&&{description},...digest&&{digest},...expires&&{expires},...meta4!==void 0&&{meta:meta4},...opaque!==void 0&&{opaque}})}function fromMethod2(method,parameters){const{name:methodName,intent}=method;const{description,digest,expires,id,meta:meta4,realm,secretKey}=parameters;const request=fromMethod(method,parameters.request);return from4({...id!==void 0?{id}:{secretKey},realm,method:methodName,intent,request,description,digest,expires,meta:meta4})}function serialize2(challenge){const parts=[authParam("id",challenge.id),authParam("realm",challenge.realm),authParam("method",challenge.method),authParam("intent",challenge.intent),authParam("request",serialize(challenge.request))];if(challenge.description!==void 0)parts.push(authParam("description",challenge.description));if(challenge.digest!==void 0)parts.push(authParam("digest",challenge.digest));if(challenge.expires!==void 0)parts.push(authParam("expires",challenge.expires));if(challenge.opaque!==void 0)parts.push(authParam("opaque",challenge.opaque));else if(challenge.meta!==void 0)parts.push(authParam("opaque",serialize(challenge.meta)));return`${Schemes.payment} ${parts.join(", ")}`}function authParam(name,value){if(/[\r\n]/.test(value))throw new Error("Invalid quoted-string value.");return`${name}="${value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function deserialize2(value,options){const params=extractPaymentAuthParams(value);if(!params)throw new Error("Missing Payment scheme.");const result=parseAuthParams(params);const{request,opaque,...rest}=result;if(!request)throw new Error("Missing request parameter.");if(request.length>maxRequestParameterLength)throw new Error("Request parameter too large.");if(rest.method&&!/^[a-z][a-z0-9:_-]*$/.test(rest.method))throw new Error(`Invalid method: "${rest.method}". Must be lowercase per spec.`);return from4({...rest,request:deserialize(request),...opaque&&{opaque}},options)}function extractPaymentAuthParams(header){const token=Schemes.payment;let inQuotes=false;let escaped=false;for(let i=0;i<header.length;i++){const char=header[i];if(inQuotes){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char==='"')inQuotes=false;continue}if(char==='"'){inQuotes=true;continue}if(!startsWithSchemeToken(header,i,token))continue;const prefix=header.slice(0,i);if(prefix.trim()&&!prefix.trimEnd().endsWith(","))continue;let paramsStart=i+token.length;while(paramsStart<header.length&&/\s/.test(header[paramsStart]??""))paramsStart++;return header.slice(paramsStart)}return null}function parseAuthParams(input){const result={};let i=0;while(i<input.length){while(i<input.length&&/[\s,]/.test(input[i]??""))i++;if(i>=input.length)break;const keyStart=i;while(i<input.length&&/[A-Za-z0-9_-]/.test(input[i]??""))i++;const key=input.slice(keyStart,i);if(!key)throw new Error("Malformed auth-param.");while(i<input.length&&/\s/.test(input[i]??""))i++;if(input[i]!=="=")break;i++;while(i<input.length&&/\s/.test(input[i]??""))i++;const[value,nextIndex]=readAuthParamValue(input,i);i=nextIndex;if(key in result)throw new Error(`Duplicate parameter: ${key}`);result[key]=value}return result}function readAuthParamValue(input,start){if(input[start]==='"')return readQuotedAuthParamValue(input,start+1);let i=start;while(i<input.length&&input[i]!==",")i++;return[input.slice(start,i).trim(),i]}function readQuotedAuthParamValue(input,start){let i=start;let escaped=false;let segmentStart=start;let parts;while(i<input.length){const char=input[i];i++;if(escaped){parts??=[];parts.push(char);segmentStart=i;escaped=false;continue}if(char==="\\"){parts??=[];parts.push(input.slice(segmentStart,i-1));segmentStart=i;escaped=true;continue}if(char==='"'){const value=parts?[...parts,input.slice(segmentStart,i-1)].join(""):input.slice(start,i-1);return[value,i]}}throw new Error("Unterminated quoted-string.")}function startsWithSchemeToken(value,index,token){if(!value.slice(index).toLowerCase().startsWith(token.toLowerCase()))return false;const next=value[index+token.length];return Boolean(next&&/\s/.test(next))}function fromHeaders(headers,options){const header=headers.get(Headers2.wwwAuthenticate);if(!header)throw new Error(`Missing ${Headers2.wwwAuthenticate} header.`);return deserialize2(header,options)}function fromResponse(response,options){if(response.status!==402)throw new Error("Response status is not 402.");return fromHeaders(response.headers,options)}function fromResponseList(response,options){if(response.status!==402)throw new Error("Response status is not 402.");return fromHeadersList(response.headers,options)}function fromHeadersList(headers,options){const header=headers.get(Headers2.wwwAuthenticate);if(!header)throw new Error(`Missing ${Headers2.wwwAuthenticate} header.`);return deserializeList(header,options)}function deserializeList(value,options){const starts=[];const schemePattern=new RegExp(`${Schemes.payment}\\s+`,"gi");for(const match of value.matchAll(schemePattern)){starts.push(match.index)}if(starts.length===0)throw new Error("No Payment schemes found.");return starts.map((start,i)=>{const end=i+1<starts.length?starts[i+1]:value.length;const chunk=value.slice(start,end).replace(/,\s*$/,"");return deserialize2(chunk,options)})}function verify2(challenge,options){const expectedId=computeId(challenge,options);return constantTimeEqual(challenge.id,expectedId)}function meta3(challenge){return challenge.meta}function idBindingInput(challenge){return[challenge.realm,challenge.method,challenge.intent,serialize(challenge.request),challenge.expires??"",challenge.digest??"",challenge.opaque??(challenge.meta?serialize(challenge.meta):"")].join("|")}function computeId(challenge,options){const input=idBindingInput(challenge);const key=Bytes_exports.fromString(options.secretKey);const data=Bytes_exports.fromString(input);const mac3=Hash_exports.hmac256(key,data,{as:"Bytes"});return Base64_exports.fromBytes(mac3,{url:true,pad:false})}var maxRequestParameterLength,Schema;var init_Challenge=__esm({"node_modules/mppx/dist/Challenge.js"(){"use strict";init_esm2();init_Constants();init_constantTimeEqual();init_PaymentRequest();init_zod();maxRequestParameterLength=16*1024;Schema=object({description:optional(string2()),digest:optional(string2().check(_regex(/^sha-256=/,"Invalid digest format"))),expires:optional(datetime3()),id:string2().check(_minLength(1)),intent:string2(),method:string2(),meta:optional(record(string2(),string2())),opaque:optional(string2()),realm:string2(),request:record(string2(),unknown())})}});var Credential_exports={};__export(Credential_exports,{InvalidCredentialEncodingError:()=>InvalidCredentialEncodingError,MissingAuthorizationHeaderError:()=>MissingAuthorizationHeaderError,MissingPaymentSchemeError:()=>MissingPaymentSchemeError,deserialize:()=>deserialize3,extractPaymentScheme:()=>extractPaymentScheme,from:()=>from5,fromRequest:()=>fromRequest,serialize:()=>serialize3});function deserialize3(value){const prefixMatch=value.match(new RegExp(`^${Schemes.payment}\\s+(.+)$`,"i"));if(!prefixMatch?.[1])throw new MissingPaymentSchemeError;try{const json3=Base64_exports.toString(prefixMatch[1]);const parsed=JSON.parse(json3);const{opaque:challengeOpaque,request,meta:_meta,...challengeFields}=parsed.challenge;const{meta:meta4,opaque}=normalizeCredentialOpaque(challengeOpaque);const challenge=Schema.parse({...challengeFields,...meta4!==void 0&&{meta:meta4},...opaque!==void 0&&{opaque},request:deserialize(request)});return{challenge,payload:parsed.payload,...parsed.source&&{source:parsed.source}}}catch{throw new InvalidCredentialEncodingError}}function normalizeCredentialOpaque(value){if(value===void 0)return{};if(typeof value==="string")return{opaque:value};if(!isStringRecord(value))throw new Error("Invalid opaque.");return{meta:value,opaque:serialize(value)}}function isStringRecord(value){if(typeof value!=="object"||value===null||Array.isArray(value))return false;return Object.values(value).every(entry=>typeof entry==="string")}function from5(parameters){const{challenge,payload,source}=parameters;return{challenge,payload,...source&&{source}}}function fromRequest(request){const header=request.headers.get(Headers2.authorization);if(!header)throw new MissingAuthorizationHeaderError;const payment=extractPaymentScheme(header);if(!payment)throw new MissingPaymentSchemeError;return deserialize3(payment)}function serialize3(credential){const{meta:meta4,opaque,request,...challenge}=credential.challenge;const wireOpaque=opaque??(meta4!==void 0?serialize(meta4):void 0);const wire={challenge:{...challenge,...wireOpaque!==void 0&&{opaque:wireOpaque},request:serialize(request)},payload:credential.payload,...credential.source&&{source:credential.source}};const json3=JSON.stringify(wire);const encoded=Base64_exports.fromString(json3,{pad:false,url:true});return`${Schemes.payment} ${encoded}`}function extractPaymentScheme(header){const schemes2=header.split(",").map(s=>s.trim());return schemes2.find(s=>new RegExp(`^${Schemes.payment}\\s+`,"i").test(s))??null}var MissingAuthorizationHeaderError,MissingPaymentSchemeError,InvalidCredentialEncodingError;var init_Credential=__esm({"node_modules/mppx/dist/Credential.js"(){"use strict";init_esm2();init_Challenge();init_Constants();init_PaymentRequest();MissingAuthorizationHeaderError=class extends Error{name="MissingAuthorizationHeaderError";constructor(){super("Missing Authorization header.")}};MissingPaymentSchemeError=class extends Error{name="MissingPaymentSchemeError";constructor(){super("Missing Payment scheme.")}};InvalidCredentialEncodingError=class extends Error{name="InvalidCredentialEncodingError";constructor(){super("Invalid base64url or JSON.")}}}});var Errors_exports2={};__export(Errors_exports2,{AmountExceedsDepositError:()=>AmountExceedsDepositError,BadRequestError:()=>BadRequestError,ChannelClosedError:()=>ChannelClosedError,ChannelNotFoundError:()=>ChannelNotFoundError,DeltaTooSmallError:()=>DeltaTooSmallError,Hints:()=>Hints,InsufficientBalanceError:()=>InsufficientBalanceError,InvalidChallengeError:()=>InvalidChallengeError,InvalidPayloadError:()=>InvalidPayloadError,InvalidSignatureError:()=>InvalidSignatureError,MalformedCredentialError:()=>MalformedCredentialError,PaymentActionRequiredError:()=>PaymentActionRequiredError,PaymentError:()=>PaymentError,PaymentExpiredError:()=>PaymentExpiredError,PaymentInsufficientError:()=>PaymentInsufficientError,PaymentMethodUnsupportedError:()=>PaymentMethodUnsupportedError,PaymentRequiredError:()=>PaymentRequiredError,SignerMismatchError:()=>SignerMismatchError,VerificationFailedError:()=>VerificationFailedError});var Hints,PaymentError,MalformedCredentialError,InvalidChallengeError,VerificationFailedError,PaymentActionRequiredError,PaymentExpiredError,PaymentRequiredError,InvalidPayloadError,BadRequestError,PaymentInsufficientError,PaymentMethodUnsupportedError,InsufficientBalanceError,InvalidSignatureError,SignerMismatchError,AmountExceedsDepositError,DeltaTooSmallError,ChannelNotFoundError,ChannelClosedError;var init_Errors2=__esm({"node_modules/mppx/dist/Errors.js"(){"use strict";Hints={paymentRequired:"Use a supported wallet to pay for this resource using one of the supported payment methods returned in the WWW-Authenticate header. See https://mpp.dev/tools/wallet.md",malformedCredential:"Use a supported wallet to construct valid credentials for one of the supported payment methods returned in the WWW-Authenticate header. See https://mpp.dev/tools/wallet.md",methodUnsupported:"Use a supported wallet to pay for this resource using one of the supported payment methods returned in the WWW-Authenticate header. See https://mpp.dev/tools/wallet.md"};PaymentError=class extends Error{details;status=402;hint;constructor(message2,options={}){super(message2);this.details=options.details}toProblemDetails(challengeId){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...challengeId&&{challengeId}}}};MalformedCredentialError=class extends PaymentError{name="MalformedCredentialError";title="Malformed Credential";status=402;type="https://paymentauth.org/problems/malformed-credential";hint=Hints.malformedCredential;constructor(options={}){const{reason}=options;super(reason?`Credential is malformed: ${reason}.`:"Credential is malformed.")}};InvalidChallengeError=class extends PaymentError{name="InvalidChallengeError";title="Invalid Challenge";status=402;type="https://paymentauth.org/problems/invalid-challenge";constructor(options={}){const{id,reason}=options;const idPart=id?` "${id}"`:"";const reasonPart=reason?`: ${reason}`:"";super(`Challenge${idPart} is invalid${reasonPart}.`)}};VerificationFailedError=class extends PaymentError{name="VerificationFailedError";title="Verification Failed";type="https://paymentauth.org/problems/verification-failed";constructor(options={}){const{details,reason}=options;super(reason?`Payment verification failed: ${reason}.`:"Payment verification failed.",{details})}};PaymentActionRequiredError=class extends PaymentError{name="PaymentActionRequiredError";title="Payment Action Required";type="https://paymentauth.org/problems/payment-action-required";constructor(options={}){const{reason}=options;super(reason?`Payment requires action: ${reason}.`:"Payment requires action.")}};PaymentExpiredError=class extends PaymentError{name="PaymentExpiredError";title="Payment Expired";type="https://paymentauth.org/problems/payment-expired";constructor(options={}){const{expires}=options;super(expires?`Payment expired at ${expires}.`:"Payment has expired.")}};PaymentRequiredError=class extends PaymentError{name="PaymentRequiredError";title="Payment Required";type="https://paymentauth.org/problems/payment-required";hint=Hints.paymentRequired;constructor(options={}){const{description}=options;const parts=["Payment is required"];if(description)parts.push(`(${description})`);super(`${parts.join(" ")}.`)}};InvalidPayloadError=class extends PaymentError{name="InvalidPayloadError";title="Invalid Payload";type="https://paymentauth.org/problems/invalid-payload";constructor(options={}){const{reason}=options;super(reason?`Credential payload is invalid: ${reason}.`:"Credential payload is invalid.")}};BadRequestError=class extends PaymentError{name="BadRequestError";title="Bad Request";status=400;type="https://paymentauth.org/problems/bad-request";constructor(options={}){const{reason}=options;super(reason?`Bad request: ${reason}.`:"Bad request.")}};PaymentInsufficientError=class extends PaymentError{name="PaymentInsufficientError";title="Payment Insufficient";type="https://paymentauth.org/problems/payment-insufficient";constructor(options={}){const{reason}=options;super(reason?`Payment insufficient: ${reason}.`:"Payment amount is insufficient.")}};PaymentMethodUnsupportedError=class extends PaymentError{name="PaymentMethodUnsupportedError";title="Method Unsupported";status=400;type="https://paymentauth.org/problems/method-unsupported";hint=Hints.methodUnsupported;constructor(options={}){const{method}=options;super(method?`Payment method "${method}" is not supported.`:"Payment method is not supported.")}};InsufficientBalanceError=class extends PaymentError{name="InsufficientBalanceError";title="Insufficient Balance";status=402;type="https://paymentauth.org/problems/session/insufficient-balance";constructor(options={}){const{reason}=options;super(reason?`Insufficient balance: ${reason}.`:"Insufficient balance.")}};InvalidSignatureError=class extends PaymentError{name="InvalidSignatureError";title="Invalid Signature";status=402;type="https://paymentauth.org/problems/session/invalid-signature";constructor(options={}){const{reason}=options;super(reason?`Invalid signature: ${reason}.`:"Invalid signature.")}};SignerMismatchError=class extends PaymentError{name="SignerMismatchError";title="Signer Mismatch";status=402;type="https://paymentauth.org/problems/session/signer-mismatch";constructor(options={}){const{reason}=options;super(reason?`Signer mismatch: ${reason}.`:"Signer is not authorized for this channel.")}};AmountExceedsDepositError=class extends PaymentError{name="AmountExceedsDepositError";title="Amount Exceeds Deposit";status=402;type="https://paymentauth.org/problems/session/amount-exceeds-deposit";constructor(options={}){const{reason}=options;super(reason?`Amount exceeds deposit: ${reason}.`:"Voucher amount exceeds channel deposit.")}};DeltaTooSmallError=class extends PaymentError{name="DeltaTooSmallError";title="Delta Too Small";status=402;type="https://paymentauth.org/problems/session/delta-too-small";constructor(options={}){const{reason}=options;super(reason?`Delta too small: ${reason}.`:"Amount increase below minimum voucher delta.")}};ChannelNotFoundError=class extends PaymentError{name="ChannelNotFoundError";title="Channel Not Found";status=410;type="https://paymentauth.org/problems/session/channel-not-found";constructor(options={}){const{reason}=options;super(reason?`Channel not found: ${reason}.`:"No channel with this ID exists.")}};ChannelClosedError=class extends PaymentError{name="ChannelClosedError";title="Channel Closed";status=410;type="https://paymentauth.org/problems/session/channel-finalized";constructor(options={}){const{reason}=options;super(reason?`Channel closed: ${reason}.`:"Channel is closed.")}}}});var Expires_exports={};__export(Expires_exports,{assert:()=>assert5,days:()=>days,hours:()=>hours,minutes:()=>minutes,months:()=>months,seconds:()=>seconds,weeks:()=>weeks,years:()=>years});function assert5(expires,challengeId){if(!expires)throw new InvalidChallengeError({...challengeId&&{id:challengeId},reason:"missing required expires field"});if(Number.isNaN(new Date(expires).getTime()))throw new InvalidChallengeError({...challengeId&&{id:challengeId},reason:"malformed expires timestamp"});if(new Date(expires)<new Date)throw new PaymentExpiredError({expires})}function days(n){return new Date(Date.now()+n*24*60*60*1e3).toISOString()}function hours(n){return new Date(Date.now()+n*60*60*1e3).toISOString()}function minutes(n){return new Date(Date.now()+n*60*1e3).toISOString()}function months(n){return new Date(Date.now()+n*30*24*60*60*1e3).toISOString()}function seconds(n){return new Date(Date.now()+n*1e3).toISOString()}function weeks(n){return new Date(Date.now()+n*7*24*60*60*1e3).toISOString()}function years(n){return new Date(Date.now()+n*365*24*60*60*1e3).toISOString()}var init_Expires=__esm({"node_modules/mppx/dist/Expires.js"(){"use strict";init_Errors2()}});function isHex(value,{strict=true}={}){if(!value)return false;if(typeof value!=="string")return false;return strict?/^0x[0-9a-fA-F]*$/.test(value):value.startsWith("0x")}var init_isHex=__esm({"node_modules/viem/_esm/utils/data/isHex.js"(){"use strict"}});function size3(value){if(isHex(value,{strict:false}))return Math.ceil((value.length-2)/2);return value.length}var init_size=__esm({"node_modules/viem/_esm/utils/data/size.js"(){"use strict";init_isHex()}});var version3;var init_version2=__esm({"node_modules/viem/_esm/errors/version.js"(){"use strict";version3="2.55.11"}});function walk2(err,fn){if(fn?.(err))return err;if(err&&typeof err==="object"&&"cause"in err&&err.cause!==void 0)return walk2(err.cause,fn);return fn?null:err}var errorConfig,BaseError3;var init_base2=__esm({"node_modules/viem/_esm/errors/base.js"(){"use strict";init_version2();errorConfig={getDocsUrl:({docsBaseUrl,docsPath="",docsSlug})=>docsPath?`${docsBaseUrl??"https://viem.sh"}${docsPath}${docsSlug?`#${docsSlug}`:""}`:void 0,version:`viem@${version3}`};BaseError3=class _BaseError extends Error{constructor(shortMessage,args={}){const details=(()=>{if(args.cause instanceof _BaseError)return args.cause.details;if(args.cause?.message)return args.cause.message;return args.details})();const docsPath=(()=>{if(args.cause instanceof _BaseError)return args.cause.docsPath||args.docsPath;return args.docsPath})();const docsUrl=errorConfig.getDocsUrl?.({...args,docsPath});const message2=[shortMessage||"An error occurred.","",...args.metaMessages?[...args.metaMessages,""]:[],...docsUrl?[`Docs: ${docsUrl}`]:[],...details?[`Details: ${details}`]:[],...errorConfig.version?[`Version: ${errorConfig.version}`]:[]].join("\n");super(message2,args.cause?{cause:args.cause}:void 0);Object.defineProperty(this,"details",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"docsPath",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"metaMessages",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"shortMessage",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"version",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"name",{enumerable:true,configurable:true,writable:true,value:"BaseError"});this.details=details;this.docsPath=docsPath;this.metaMessages=args.metaMessages;this.name=args.name??this.name;this.shortMessage=shortMessage;this.version=version3}walk(fn){return walk2(this,fn)}}}});var SizeExceedsPaddingSizeError3;var init_data=__esm({"node_modules/viem/_esm/errors/data.js"(){"use strict";init_base2();SizeExceedsPaddingSizeError3=class extends BaseError3{constructor({size:size4,targetSize,type}){super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size4}) exceeds padding size (${targetSize}).`,{name:"SizeExceedsPaddingSizeError"})}}}});function pad3(hexOrBytes,{dir,size:size4=32}={}){if(typeof hexOrBytes==="string")return padHex(hexOrBytes,{dir,size:size4});return padBytes(hexOrBytes,{dir,size:size4})}function padHex(hex_,{dir,size:size4=32}={}){if(size4===null)return hex_;const hex3=hex_.replace("0x","");if(hex3.length>size4*2)throw new SizeExceedsPaddingSizeError3({size:Math.ceil(hex3.length/2),targetSize:size4,type:"hex"});return`0x${hex3[dir==="right"?"padEnd":"padStart"](size4*2,"0")}`}function padBytes(bytes,{dir,size:size4=32}={}){if(size4===null)return bytes;if(bytes.length>size4)throw new SizeExceedsPaddingSizeError3({size:bytes.length,targetSize:size4,type:"bytes"});const paddedBytes=new Uint8Array(size4);for(let i=0;i<size4;i++){const padEnd=dir==="right";paddedBytes[padEnd?i:size4-i-1]=bytes[padEnd?i:bytes.length-i-1]}return paddedBytes}var init_pad=__esm({"node_modules/viem/_esm/utils/data/pad.js"(){"use strict";init_data()}});var IntegerOutOfRangeError2,SizeOverflowError3;var init_encoding=__esm({"node_modules/viem/_esm/errors/encoding.js"(){"use strict";init_base2();IntegerOutOfRangeError2=class extends BaseError3{constructor({max,min,signed,size:size4,value}){super(`Number "${value}" is not in safe ${size4?`${size4*8}-bit ${signed?"signed":"unsigned"} `:""}integer range ${max?`(${min} to ${max})`:`(above ${min})`}`,{name:"IntegerOutOfRangeError"})}};SizeOverflowError3=class extends BaseError3{constructor({givenSize,maxSize}){super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,{name:"SizeOverflowError"})}}}});function assertSize3(hexOrBytes,{size:size4}){if(size3(hexOrBytes)>size4)throw new SizeOverflowError3({givenSize:size3(hexOrBytes),maxSize:size4})}var init_fromHex=__esm({"node_modules/viem/_esm/utils/encoding/fromHex.js"(){"use strict";init_encoding();init_size()}});function toHex3(value,opts={}){if(typeof value==="number"||typeof value==="bigint")return numberToHex(value,opts);if(typeof value==="string"){return stringToHex(value,opts)}if(typeof value==="boolean")return boolToHex(value,opts);return bytesToHex(value,opts)}function boolToHex(value,opts={}){const hex3=`0x${Number(value)}`;if(typeof opts.size==="number"){assertSize3(hex3,{size:opts.size});return pad3(hex3,{size:opts.size})}return hex3}function bytesToHex(value,opts={}){let string4="";for(let i=0;i<value.length;i++){string4+=hexes2[value[i]]}const hex3=`0x${string4}`;if(typeof opts.size==="number"){assertSize3(hex3,{size:opts.size});return pad3(hex3,{dir:"right",size:opts.size})}return hex3}function numberToHex(value_,opts={}){const{signed,size:size4}=opts;const value=BigInt(value_);let maxValue;if(size4){if(signed)maxValue=(1n<<BigInt(size4)*8n-1n)-1n;else maxValue=2n**(BigInt(size4)*8n)-1n}else if(typeof value_==="number"){maxValue=BigInt(Number.MAX_SAFE_INTEGER)}const minValue=typeof maxValue==="bigint"&&signed?-maxValue-1n:0;if(maxValue&&value>maxValue||value<minValue){const suffix=typeof value_==="bigint"?"n":"";throw new IntegerOutOfRangeError2({max:maxValue?`${maxValue}${suffix}`:void 0,min:`${minValue}${suffix}`,signed,size:size4,value:`${value_}${suffix}`})}const hex3=`0x${(signed&&value<0?(1n<<BigInt(size4*8))+BigInt(value):value).toString(16)}`;if(size4)return pad3(hex3,{size:size4});return hex3}function stringToHex(value_,opts={}){const value=encoder4.encode(value_);return bytesToHex(value,opts)}var hexes2,encoder4;var init_toHex=__esm({"node_modules/viem/_esm/utils/encoding/toHex.js"(){"use strict";init_encoding();init_pad();init_fromHex();hexes2=Array.from({length:256},(_v,i)=>i.toString(16).padStart(2,"0"));encoder4=new TextEncoder}});function toBytes4(value,opts={}){if(typeof value==="number"||typeof value==="bigint")return numberToBytes(value,opts);if(typeof value==="boolean")return boolToBytes(value,opts);if(isHex(value))return hexToBytes(value,opts);return stringToBytes(value,opts)}function boolToBytes(value,opts={}){const bytes=new Uint8Array(1);bytes[0]=Number(value);if(typeof opts.size==="number"){assertSize3(bytes,{size:opts.size});return pad3(bytes,{size:opts.size})}return bytes}function charCodeToBase162(char){if(char>=charCodeMap2.zero&&char<=charCodeMap2.nine)return char-charCodeMap2.zero;if(char>=charCodeMap2.A&&char<=charCodeMap2.F)return char-(charCodeMap2.A-10);if(char>=charCodeMap2.a&&char<=charCodeMap2.f)return char-(charCodeMap2.a-10);return void 0}function hexToBytes(hex_,opts={}){let hex3=hex_;if(opts.size){assertSize3(hex3,{size:opts.size});hex3=pad3(hex3,{dir:"right",size:opts.size})}let hexString=hex3.slice(2);if(hexString.length%2)hexString=`0${hexString}`;const length=hexString.length/2;const bytes=new Uint8Array(length);for(let index=0,j2=0;index<length;index++){const nibbleLeft=charCodeToBase162(hexString.charCodeAt(j2++));const nibbleRight=charCodeToBase162(hexString.charCodeAt(j2++));if(nibbleLeft===void 0||nibbleRight===void 0){throw new BaseError3(`Invalid byte sequence ("${hexString[j2-2]}${hexString[j2-1]}" in "${hexString}").`)}bytes[index]=nibbleLeft*16+nibbleRight}return bytes}function numberToBytes(value,opts){const hex3=numberToHex(value,opts);return hexToBytes(hex3)}function stringToBytes(value,opts={}){const bytes=encoder5.encode(value);if(typeof opts.size==="number"){assertSize3(bytes,{size:opts.size});return pad3(bytes,{dir:"right",size:opts.size})}return bytes}var encoder5,charCodeMap2;var init_toBytes=__esm({"node_modules/viem/_esm/utils/encoding/toBytes.js"(){"use strict";init_base2();init_isHex();init_pad();init_fromHex();init_toHex();encoder5=new TextEncoder;charCodeMap2={zero:48,nine:57,A:65,F:70,a:97,f:102}}});function fromBig2(n,le=false){if(le)return{h:Number(n&U32_MASK642),l:Number(n>>_32n2&U32_MASK642)};return{h:Number(n>>_32n2&U32_MASK642)|0,l:Number(n&U32_MASK642)|0}}function split2(lst,le=false){const len=lst.length;let Ah=new Uint32Array(len);let Al=new Uint32Array(len);for(let i=0;i<len;i++){const{h,l}=fromBig2(lst[i],le);[Ah[i],Al[i]]=[h,l]}return[Ah,Al]}var U32_MASK642,_32n2,rotlSH2,rotlSL2,rotlBH2,rotlBL2;var init_u642=__esm({"node_modules/viem/node_modules/@noble/hashes/esm/_u64.js"(){"use strict";U32_MASK642=BigInt(2**32-1);_32n2=BigInt(32);rotlSH2=(h,l,s)=>h<<s|l>>>32-s;rotlSL2=(h,l,s)=>l<<s|h>>>32-s;rotlBH2=(h,l,s)=>l<<s-32|h>>>64-s;rotlBL2=(h,l,s)=>h<<s-32|l>>>64-s}});function isBytes4(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function anumber4(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function abytes3(b2,...lengths){if(!isBytes4(b2))throw new Error("Uint8Array expected");if(lengths.length>0&&!lengths.includes(b2.length))throw new Error("Uint8Array expected of length "+lengths+", got length="+b2.length)}function aexists3(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function aoutput3(out,instance){abytes3(out);const min=instance.outputLen;if(out.length<min){throw new Error("digestInto() expects output buffer of length at least "+min)}}function u322(arr){return new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4))}function clean3(...arrays){for(let i=0;i<arrays.length;i++){arrays[i].fill(0)}}function byteSwap2(word){return word<<24&4278190080|word<<8&16711680|word>>>8&65280|word>>>24&255}function byteSwap322(arr){for(let i=0;i<arr.length;i++){arr[i]=byteSwap2(arr[i])}return arr}function utf8ToBytes2(str2){if(typeof str2!=="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(str2))}function toBytes5(data){if(typeof data==="string")data=utf8ToBytes2(data);abytes3(data);return data}function createHasher3(hashCons){const hashC=msg=>hashCons().update(toBytes5(msg)).digest();const tmp=hashCons();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashCons();return hashC}var isLE2,swap32IfBE2,Hash2;var init_utils4=__esm({"node_modules/viem/node_modules/@noble/hashes/esm/utils.js"(){"use strict";isLE2=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();swap32IfBE2=isLE2?u=>u:byteSwap322;Hash2=class{}}});function keccakP2(s,rounds=24){const B2=new Uint32Array(5*2);for(let round=24-rounds;round<24;round++){for(let x2=0;x2<10;x2++)B2[x2]=s[x2]^s[x2+10]^s[x2+20]^s[x2+30]^s[x2+40];for(let x2=0;x2<10;x2+=2){const idx1=(x2+8)%10;const idx0=(x2+2)%10;const B0=B2[idx0];const B1=B2[idx0+1];const Th=rotlH2(B0,B1,1)^B2[idx1];const Tl=rotlL2(B0,B1,1)^B2[idx1+1];for(let y=0;y<50;y+=10){s[x2+y]^=Th;s[x2+y+1]^=Tl}}let curH=s[2];let curL=s[3];for(let t2=0;t2<24;t2++){const shift=SHA3_ROTL2[t2];const Th=rotlH2(curH,curL,shift);const Tl=rotlL2(curH,curL,shift);const PI=SHA3_PI2[t2];curH=s[PI];curL=s[PI+1];s[PI]=Th;s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x2=0;x2<10;x2++)B2[x2]=s[y+x2];for(let x2=0;x2<10;x2++)s[y+x2]^=~B2[(x2+2)%10]&B2[(x2+4)%10]}s[0]^=SHA3_IOTA_H2[round];s[1]^=SHA3_IOTA_L2[round]}clean3(B2)}var _0n2,_1n2,_2n2,_7n2,_256n2,_0x71n2,SHA3_PI2,SHA3_ROTL2,_SHA3_IOTA2,IOTAS2,SHA3_IOTA_H2,SHA3_IOTA_L2,rotlH2,rotlL2,Keccak2,gen2,keccak_2562;var init_sha32=__esm({"node_modules/viem/node_modules/@noble/hashes/esm/sha3.js"(){"use strict";init_u642();init_utils4();_0n2=BigInt(0);_1n2=BigInt(1);_2n2=BigInt(2);_7n2=BigInt(7);_256n2=BigInt(256);_0x71n2=BigInt(113);SHA3_PI2=[];SHA3_ROTL2=[];_SHA3_IOTA2=[];for(let round=0,R=_1n2,x2=1,y=0;round<24;round++){[x2,y]=[y,(2*x2+3*y)%5];SHA3_PI2.push(2*(5*y+x2));SHA3_ROTL2.push((round+1)*(round+2)/2%64);let t2=_0n2;for(let j2=0;j2<7;j2++){R=(R<<_1n2^(R>>_7n2)*_0x71n2)%_256n2;if(R&_2n2)t2^=_1n2<<(_1n2<<BigInt(j2))-_1n2}_SHA3_IOTA2.push(t2)}IOTAS2=split2(_SHA3_IOTA2,true);SHA3_IOTA_H2=IOTAS2[0];SHA3_IOTA_L2=IOTAS2[1];rotlH2=(h,l,s)=>s>32?rotlBH2(h,l,s):rotlSH2(h,l,s);rotlL2=(h,l,s)=>s>32?rotlBL2(h,l,s):rotlSL2(h,l,s);Keccak2=class _Keccak extends Hash2{constructor(blockLen,suffix,outputLen,enableXOF=false,rounds=24){super();this.pos=0;this.posOut=0;this.finished=false;this.destroyed=false;this.enableXOF=false;this.blockLen=blockLen;this.suffix=suffix;this.outputLen=outputLen;this.enableXOF=enableXOF;this.rounds=rounds;anumber4(outputLen);if(!(0<blockLen&&blockLen<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200);this.state32=u322(this.state)}clone(){return this._cloneInto()}keccak(){swap32IfBE2(this.state32);keccakP2(this.state32,this.rounds);swap32IfBE2(this.state32);this.posOut=0;this.pos=0}update(data){aexists3(this);data=toBytes5(data);abytes3(data);const{blockLen,state}=this;const len=data.length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);for(let i=0;i<take;i++)state[this.pos++]^=data[pos++];if(this.pos===blockLen)this.keccak()}return this}finish(){if(this.finished)return;this.finished=true;const{state,suffix,pos,blockLen}=this;state[pos]^=suffix;if((suffix&128)!==0&&pos===blockLen-1)this.keccak();state[blockLen-1]^=128;this.keccak()}writeInto(out){aexists3(this,false);abytes3(out);this.finish();const bufferOut=this.state;const{blockLen}=this;for(let pos=0,len=out.length;pos<len;){if(this.posOut>=blockLen)this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos);this.posOut+=take;pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){anumber4(bytes);return this.xofInto(new Uint8Array(bytes))}digestInto(out){aoutput3(out,this);if(this.finished)throw new Error("digest() was already called");this.writeInto(out);this.destroy();return out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true;clean3(this.state)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;to||(to=new _Keccak(blockLen,suffix,outputLen,enableXOF,rounds));to.state32.set(this.state32);to.pos=this.pos;to.posOut=this.posOut;to.finished=this.finished;to.rounds=rounds;to.suffix=suffix;to.outputLen=outputLen;to.enableXOF=enableXOF;to.destroyed=this.destroyed;return to}};gen2=(suffix,blockLen,outputLen)=>createHasher3(()=>new Keccak2(blockLen,suffix,outputLen));keccak_2562=(()=>gen2(1,136,256/8))()}});function keccak2562(value,to_){const to=to_||"hex";const bytes=keccak_2562(isHex(value,{strict:false})?toBytes4(value):value);if(to==="bytes")return bytes;return toHex3(bytes)}var init_keccak256=__esm({"node_modules/viem/_esm/utils/hash/keccak256.js"(){"use strict";init_sha32();init_isHex();init_toBytes();init_toHex()}});var InvalidAddressError2;var init_address=__esm({"node_modules/viem/_esm/errors/address.js"(){"use strict";init_base2();InvalidAddressError2=class extends BaseError3{constructor({address:address3}){super(`Address "${address3}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}}});var LruMap2;var init_lru2=__esm({"node_modules/viem/_esm/utils/lru.js"(){"use strict";LruMap2=class extends Map{constructor(size4){super();Object.defineProperty(this,"maxSize",{enumerable:true,configurable:true,writable:true,value:void 0});this.maxSize=size4}get(key){const value=super.get(key);if(super.has(key)){super.delete(key);super.set(key,value)}return value}set(key,value){if(super.has(key))super.delete(key);super.set(key,value);if(this.maxSize&&this.size>this.maxSize){const firstKey=super.keys().next().value;if(firstKey!==void 0)super.delete(firstKey)}return this}}}});function checksumAddress(address_,chainId){if(checksumAddressCache.has(`${address_}.${chainId}`))return checksumAddressCache.get(`${address_}.${chainId}`);const hexAddress=chainId?`${chainId}${address_.toLowerCase()}`:address_.substring(2).toLowerCase();const hash3=keccak2562(stringToBytes(hexAddress),"bytes");const address3=(chainId?hexAddress.substring(`${chainId}0x`.length):hexAddress).split("");for(let i=0;i<40;i+=2){if(hash3[i>>1]>>4>=8&&address3[i]){address3[i]=address3[i].toUpperCase()}if((hash3[i>>1]&15)>=8&&address3[i+1]){address3[i+1]=address3[i+1].toUpperCase()}}const result=`0x${address3.join("")}`;checksumAddressCache.set(`${address_}.${chainId}`,result);return result}function getAddress(address3,chainId){if(!isAddress(address3,{strict:false}))throw new InvalidAddressError2({address:address3});return checksumAddress(address3,chainId)}var checksumAddressCache;var init_getAddress=__esm({"node_modules/viem/_esm/utils/address/getAddress.js"(){"use strict";init_address();init_toBytes();init_keccak256();init_lru2();init_isAddress();checksumAddressCache=new LruMap2(8192)}});function isAddress(address3,options){const{strict=true}=options??{};const cacheKey=`${address3}.${strict}`;if(isAddressCache.has(cacheKey))return isAddressCache.get(cacheKey);const result=(()=>{if(!addressRegex2.test(address3))return false;if(address3.toLowerCase()===address3)return true;if(strict)return checksumAddress(address3)===address3;return true})();isAddressCache.set(cacheKey,result);return result}var addressRegex2,isAddressCache;var init_isAddress=__esm({"node_modules/viem/_esm/utils/address/isAddress.js"(){"use strict";init_lru2();init_getAddress();addressRegex2=/^0x[a-fA-F0-9]{40}$/;isAddressCache=new LruMap2(8192)}});function from6(value,decimals=0){if(!Number.isInteger(decimals)||decimals<0)throw new InvalidDecimalsError({decimals});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(value))throw new InvalidDecimalNumberError({value});let[integer2="",fraction="0"]=value.split(".");const negative=integer2.startsWith("-");if(negative)integer2=integer2.slice(1);if(integer2==="")integer2="0";fraction=fraction.replace(/(0+)$/,"");if(decimals===0){if(fraction.length>0&&Number.parseInt(fraction[0],10)>=5)integer2=`${BigInt(integer2)+1n}`;fraction=""}else if(fraction.length>decimals){const left=fraction.slice(0,decimals);const roundDigit=Number.parseInt(fraction.slice(decimals,decimals+1),10);if(roundDigit>=5){const carried=carry(left);if(carried.length>decimals){fraction=carried.slice(1);integer2=`${BigInt(integer2)+1n}`}else{fraction=carried}}else{fraction=left}}else{fraction=fraction.padEnd(decimals,"0")}return BigInt(`${negative?"-":""}${integer2}${fraction}`)}function carry(digits){const out=digits.split("");let i=out.length-1;while(i>=0){const d=Number.parseInt(out[i],10)+1;if(d<10){out[i]=String(d);return out.join("")}out[i]="0";i--}return`1${out.join("")}`}var InvalidDecimalNumberError,InvalidDecimalsError;var init_Value2=__esm({"node_modules/viem/_esm/utils/unit/Value.js"(){"use strict";InvalidDecimalNumberError=class extends Error{constructor({value}){super(`Value \`${value}\` is not a valid decimal number.`);Object.defineProperty(this,"name",{enumerable:true,configurable:true,writable:true,value:"Value.InvalidDecimalNumberError"})}};InvalidDecimalsError=class extends Error{constructor({decimals}){super(`\`decimals\` must be a non-negative integer. Got \`${decimals}\`.`);Object.defineProperty(this,"name",{enumerable:true,configurable:true,writable:true,value:"Value.InvalidDecimalsError"})}}}});function parseUnits(value,decimals){return from6(value,decimals)}var init_parseUnits=__esm({"node_modules/viem/_esm/utils/unit/parseUnits.js"(){"use strict";init_Value2()}});var init_esm3=__esm({"node_modules/viem/_esm/index.js"(){"use strict";init_getAddress();init_parseUnits()}});var Assets_exports={};__export(Assets_exports,{base:()=>base,baseSepolia:()=>baseSepolia,celo:()=>celo,celoSepolia:()=>celoSepolia,define:()=>define,fromToken:()=>fromToken,isAsset:()=>isAsset,isRawAddress:()=>isRawAddress,isToken:()=>isToken,matches:()=>matches,resolve:()=>resolve,toChainId:()=>toChainId,toNetwork:()=>toNetwork});function define(parameters){return{[knownAsset]:true,address:parameters.address,decimals:parameters.decimals,network:parameters.network,transfer:parameters.transfer}}function fromToken(token,parameters){const resolved=token(parameters.chainId);return define({address:resolved.address,decimals:resolved.decimals,network:toNetwork(parameters.chainId),transfer:withTokenDefaults(parameters.transfer,resolved)})}function isAsset(value){if(typeof value!=="object"||value===null)return false;return value[knownAsset]===true}function isToken(value){return typeof value==="function"&&typeof value.addresses==="object"&&typeof value.decimals==="number"}function isRawAddress(currency){return typeof currency==="string"}function resolve(currency,network){if(isAsset(currency)){if(currency.network!==network)return void 0;return{address:currency.address,decimals:currency.decimals,transfer:currency.transfer}}if(isToken(currency)){const address3=currency.addresses[toChainId(network)];if(!address3)return void 0;return{address:address3,decimals:currency.decimals,name:currency.name}}return{address:currency}}function matches(currency,acceptedCurrency,network){const resolved=resolve(currency,network);if(!resolved)return false;return getAddress(resolved.address)===getAddress(acceptedCurrency)}function toNetwork(chainId){return`eip155:${chainId}`}function toChainId(network){return Number(network.slice("eip155:".length))}function withTokenDefaults(transfer2,token){if(transfer2.type!=="eip3009")return transfer2;if(transfer2.name)return{...transfer2,name:transfer2.name};if(!token.name)throw new Error("EIP-3009 token assets require a token name.");return{...transfer2,name:token.name}}var knownAsset,base,baseSepolia,celo,celoSepolia;var init_Assets=__esm({"node_modules/mppx/dist/x402/Assets.js"(){"use strict";init_esm3();knownAsset=Symbol("mppx.x402.asset");base={USDC:define({address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,network:"eip155:8453",transfer:{name:"USD Coin",type:"eip3009",version:"2"}})};baseSepolia={USDC:define({address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",decimals:6,network:"eip155:84532",transfer:{name:"USDC",type:"eip3009",version:"2"}})};celo={USDC:define({address:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,network:"eip155:42220",transfer:{name:"USDC",type:"eip3009",version:"2"}}),USDT:define({address:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,network:"eip155:42220",transfer:{name:"Tether USD",type:"eip3009",version:"1"}})};celoSepolia={USDC:define({address:"0x01C5C0122039549AD1493B8220cABEdD739BC44E",decimals:6,network:"eip155:11142220",transfer:{name:"USDC",type:"eip3009",version:"2"}})}}});var Assets_exports2={};__export(Assets_exports2,{base:()=>base,baseSepolia:()=>baseSepolia,celo:()=>celo,celoSepolia:()=>celoSepolia,define:()=>define,fromToken:()=>fromToken,isAsset:()=>isAsset,isRawAddress:()=>isRawAddress,isToken:()=>isToken,matches:()=>matches,resolve:()=>resolve,toChainId:()=>toChainId,toNetwork:()=>toNetwork});var init_Assets2=__esm({"node_modules/mppx/dist/evm/Assets.js"(){"use strict";init_Assets()}});var Chains_exports={};__export(Chains_exports,{base:()=>base2,baseSepolia:()=>baseSepolia2,celo:()=>celo2,celoSepolia:()=>celoSepolia2});var base2,baseSepolia2,celo2,celoSepolia2;var init_Chains=__esm({"node_modules/mppx/dist/evm/Chains.js"(){"use strict";base2=8453;baseSepolia2=84532;celo2=42220;celoSepolia2=11142220}});var Method_exports={};__export(Method_exports,{broadcastCredential:()=>broadcastCredential,from:()=>from7,selectServerMethod:()=>selectServerMethod,toClient:()=>toClient,toServer:()=>toServer,validateCredential:()=>validateCredential});function from7(method){return method}async function validateCredential(methods,input){const prepared=prepareCredential(methods,input);if(!prepared.method.validate)throw new VerificationFailedError({details:{intent:prepared.method.intent,method:prepared.method.name},reason:`${prepared.method.name}/${prepared.method.intent} does not support non-mutating credential validation`});return prepared.method.validate({credential:prepared.credential,request:prepared.request})}async function broadcastCredential(methods,input){const prepared=prepareCredential(methods,input);const{method}=prepared;if(method.broadcast&&method.validate)await method.validate({credential:prepared.credential,request:prepared.request});const broadcast=method.broadcast??method.verify;return broadcast({credential:prepared.credential,request:prepared.request})}function prepareCredential(methods,input){const credential=typeof input==="string"?deserialize3(input):input;const candidates=methods.filter(method2=>method2.name===credential.challenge.method&&method2.intent===credential.challenge.intent);const method=selectServerMethod(candidates,credential.challenge);if(!method)throw new InvalidChallengeError({id:credential.challenge.id,reason:`no registered method for ${credential.challenge.method}/${credential.challenge.intent}`});assert5(credential.challenge.expires,credential.challenge.id);let payload;try{payload=method.schema.credential.payload.parse(credential.payload)}catch(error51){throw new InvalidPayloadError(error51 instanceof Error?{reason:error51.message}:{})}return{credential:{...credential,payload},method,request:credential.challenge.request}}function selectServerMethod(methods,challenge){if(methods.length<=1)return methods[0];if(challenge.method!==Methods.tempo||challenge.intent!==Intents.session)return methods[0];const sessionProtocol=getMethodDetail(challenge.request.methodDetails,MethodDetailKeys.sessionProtocol);if(sessionProtocol===void 0||sessionProtocol===SessionProtocols.v1)return methods.find(method=>method.alias==="sessionLegacy")??methods[0];if(sessionProtocol===SessionProtocols.v2)return methods.find(method=>method.alias===void 0)??methods[0];return void 0}function toClient(method,options){const{canHandleChallenge,context,createCredential}=options;return{...method,canHandleChallenge,context,createCredential}}function toServer(method,options){const{alias,authorize,defaults,extensions,html,preflight,request,respond,broadcast,stableBinding,transport,validate:validate5,verify:verify3}=options;const effectiveVerify=verify3??(async parameters=>{if(validate5)await validate5(parameters);if(!broadcast)throw new VerificationFailedError({reason:`${method.name}/${method.intent} does not support credential broadcast`});return broadcast(parameters)});return{...method,alias,authorize,defaults,extensions,html,preflight,request,respond,broadcast,stableBinding,transport,validate:validate5,verify:effectiveVerify}}var init_Method=__esm({"node_modules/mppx/dist/Method.js"(){"use strict";init_Constants();init_Credential();init_Errors2();init_Expires()}});var Types_exports={};__export(Types_exports,{AuthorizationConfigSchema:()=>AuthorizationConfigSchema,AuthorizationPayloadSchema:()=>AuthorizationPayloadSchema,ChargePayloadSchema:()=>ChargePayloadSchema,ChargeRequestInputSchema:()=>ChargeRequestInputSchema,ChargeRequestSchema:()=>ChargeRequestSchema,MethodDetailsSchema:()=>MethodDetailsSchema,authorizationDomain:()=>authorizationDomain,authorizationTypes:()=>authorizationTypes,challengeHash:()=>challengeHash,chargeIntent:()=>chargeIntent,credentialTypes:()=>credentialTypes,eip3009:()=>eip3009,evmNetworkPrefix:()=>evmNetworkPrefix,networkOf:()=>networkOf,paymentMethod:()=>paymentMethod,toSource:()=>toSource});function authorizationDomain(parameters){return{chainId:parameters.chainId,name:parameters.authorization.name,verifyingContract:parameters.currency,version:parameters.authorization.version}}function challengeHash(challenge){return Hash_exports.keccak256(Bytes_exports.fromString(`${challenge.id}${challenge.realm}`),{as:"Hex"})}function networkOf(chainId){return`${evmNetworkPrefix}${chainId}`}function toSource(parameters){return`did:pkh:eip155:${parameters.chainId}:${parameters.address}`}var paymentMethod,chargeIntent,evmNetworkPrefix,eip3009,credentialTypes,atomicAmount,AuthorizationConfigSchema,MethodDetailsSchema,ChargeRequestSchema,ChargeRequestInputSchema,AuthorizationPayloadSchema,ChargePayloadSchema,authorizationTypes;var init_Types=__esm({"node_modules/mppx/dist/evm/Types.js"(){"use strict";init_esm2();init_zod();paymentMethod="evm";chargeIntent="charge";evmNetworkPrefix="eip155:";eip3009="eip3009";credentialTypes=["authorization"];atomicAmount=string2().check(_regex(/^\d+$/,"Invalid atomic amount"));AuthorizationConfigSchema=object({name:string2().check(_minLength(1)),version:string2().check(_minLength(1))});MethodDetailsSchema=object({chainId:number2(),credentialTypes:optional(array(_enum2(credentialTypes)).check(_minLength(1))),decimals:optional(number2()),permit2Address:optional(address()),splits:optional(array(object({amount:atomicAmount,recipient:address()})))});ChargeRequestSchema=object({amount:atomicAmount,currency:address(),description:optional(string2()),externalId:optional(string2()),methodDetails:MethodDetailsSchema,recipient:address()});ChargeRequestInputSchema=object({amount:amount(),chainId:number2(),currency:address(),credentialTypes:optional(array(_enum2(credentialTypes)).check(_minLength(1))),decimals:number2(),description:optional(string2()),externalId:optional(string2()),permit2Address:optional(address()),recipient:address(),splits:optional(array(object({amount:atomicAmount,recipient:address()})))});AuthorizationPayloadSchema=object({from:address(),nonce:hash2(),signature:signature(),to:address(),type:literal("authorization"),validAfter:atomicAmount,validBefore:atomicAmount,value:atomicAmount});ChargePayloadSchema=AuthorizationPayloadSchema;authorizationTypes={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]}}});var Methods_exports={};__export(Methods_exports,{charge:()=>charge});var charge;var init_Methods=__esm({"node_modules/mppx/dist/evm/Methods.js"(){"use strict";init_esm3();init_Method();init_zod();init_Types();charge=from7({name:paymentMethod,intent:chargeIntent,schema:{credential:{payload:ChargePayloadSchema},request:pipe(ChargeRequestInputSchema,transform(({amount:amount2,chainId,credentialTypes:credentialTypes2=["authorization"],currency,decimals,permit2Address,recipient,splits,...request})=>({...request,amount:parseUnits(amount2,decimals).toString(),currency:getAddress(currency),methodDetails:{chainId,credentialTypes:credentialTypes2,decimals,...permit2Address?{permit2Address:getAddress(permit2Address)}:{},...splits?{splits}:{}},recipient:getAddress(recipient)})))}})}});var evm_exports={};__export(evm_exports,{Assets:()=>Assets_exports2,AuthorizationConfigSchema:()=>AuthorizationConfigSchema,AuthorizationPayloadSchema:()=>AuthorizationPayloadSchema,Chains:()=>Chains_exports,ChargePayloadSchema:()=>ChargePayloadSchema,ChargeRequestInputSchema:()=>ChargeRequestInputSchema,ChargeRequestSchema:()=>ChargeRequestSchema,MethodDetailsSchema:()=>MethodDetailsSchema,Methods:()=>Methods_exports,Types:()=>Types_exports,assets:()=>Assets_exports2,authorizationDomain:()=>authorizationDomain,authorizationTypes:()=>authorizationTypes,chains:()=>Chains_exports,challengeHash:()=>challengeHash,charge:()=>charge,chargeIntent:()=>chargeIntent,credentialTypes:()=>credentialTypes,eip3009:()=>eip3009,evmNetworkPrefix:()=>evmNetworkPrefix,networkOf:()=>networkOf,paymentMethod:()=>paymentMethod,toSource:()=>toSource});var init_evm=__esm({"node_modules/mppx/dist/evm/index.js"(){"use strict";init_Assets2();init_Chains();init_Methods();init_Types();init_Assets2();init_Chains();init_Methods();init_Types()}});var Mcp_exports={};__export(Mcp_exports,{credentialMetaKey:()=>credentialMetaKey,paymentRequiredCode:()=>paymentRequiredCode,paymentRequiredMetaKey:()=>paymentRequiredMetaKey,paymentVerificationFailedCode:()=>paymentVerificationFailedCode,receiptMetaKey:()=>receiptMetaKey});var paymentRequiredCode,paymentVerificationFailedCode,credentialMetaKey,paymentRequiredMetaKey,receiptMetaKey;var init_Mcp=__esm({"node_modules/mppx/dist/Mcp.js"(){"use strict";paymentRequiredCode=-32042;paymentVerificationFailedCode=-32043;credentialMetaKey="org.paymentauth/credential";paymentRequiredMetaKey="org.paymentauth/payment-required";receiptMetaKey="org.paymentauth/receipt"}});var Receipt_exports={};__export(Receipt_exports,{Schema:()=>Schema2,deserialize:()=>deserialize4,from:()=>from8,fromResponse:()=>fromResponse2,serialize:()=>serialize4});function deserialize4(encoded){const json3=Base64_exports.toString(encoded);return from8(JSON.parse(json3))}function from8(parameters){return Schema2.parse(parameters)}function serialize4(receipt){const json3=JSON.stringify(receipt);return Base64_exports.fromString(json3,{pad:false,url:true})}function fromResponse2(response){const header=response.headers.get(Headers2.paymentReceipt);if(!header)throw new Error(`Missing ${Headers2.paymentReceipt} header.`);return deserialize4(header)}var shape,BaseSchema,Schema2;var init_Receipt=__esm({"node_modules/mppx/dist/Receipt.js"(){"use strict";init_esm2();init_Constants();init_zod();shape={method:string2(),reference:string2(),externalId:optional(string2()),subscriptionId:optional(string2()),status:literal("success"),timestamp:datetime3()};BaseSchema=object(shape);Schema2=looseObject(shape)}});var Store_exports={};__export(Store_exports,{cloudflare:()=>cloudflare,from:()=>from9,memory:()=>memory,redis:()=>redis,upstash:()=>upstash});function from9(store,options){return withKeyPrefix(store,options?.keyPrefix)}function withKeyPrefix(store,keyPrefix=""){if(!keyPrefix)return store;const cached2=keyPrefixCache.get(store)?.get(keyPrefix);if(cached2)return cached2;const backing=store;const prefixedKey=key=>`${keyPrefix}${key}`;const prefixed=from9({async get(key){return backing.get(prefixedKey(key))},async put(key,value){await backing.put(prefixedKey(key),value)},async delete(key){await backing.delete(prefixedKey(key))},..."update"in store?{async update(key,fn){return store.update(prefixedKey(key),fn)}}:{}});const cachedByPrefix=keyPrefixCache.get(store)??new Map;cachedByPrefix.set(keyPrefix,prefixed);keyPrefixCache.set(store,cachedByPrefix);return prefixed}function wrapJsonUpdate(update){if(!update)return{};return{async update(key,fn){return update(key,current=>{const parsed=current==null?null:Json_exports.parse(current);const change=fn(parsed);if(change.op!=="set")return change;return{...change,value:Json_exports.stringify(change.value)}})}}}function cloudflare(kv,options){return from9({async get(key){const raw2=await kv.get(key);if(raw2==null)return null;return Json_exports.parse(raw2)},async put(key,value){await kv.put(key,Json_exports.stringify(value))},async delete(key){await kv.delete(key)},...wrapJsonUpdate(kv.update)},options)}function memory(options){const store=new Map;return from9({async get(key){const raw2=store.get(key);if(raw2===void 0)return null;return Json_exports.parse(raw2)},async put(key,value){store.set(key,Json_exports.stringify(value))},async delete(key){store.delete(key)},async update(key,fn){const current=store.has(key)?Json_exports.parse(store.get(key)):null;const change=fn(current);if(change.op==="set")store.set(key,Json_exports.stringify(change.value));if(change.op==="delete")store.delete(key);return change.result}},options)}function redis(client,options){return from9({async get(key){const raw2=await client.get(key);if(raw2==null)return null;return Json_exports.parse(raw2)},async put(key,value){await client.set(key,Json_exports.stringify(value))},async delete(key){await client.del(key)},...wrapJsonUpdate(client.update)},options)}function upstash(redis2,options){return from9({async get(key){return await redis2.get(key)},async put(key,value){await redis2.set(key,value)},async delete(key){await redis2.del(key)},...redis2.update?{update:redis2.update}:{}},options)}var keyPrefixCache;var init_Store=__esm({"node_modules/mppx/dist/Store.js"(){"use strict";init_esm2();keyPrefixCache=new WeakMap}});function createJson(schema){return{encode(value){return Base64_exports.fromString(JSON.stringify(schema.parse(value)))},decode(value){try{return schema.parse(JSON.parse(Base64_exports.toString(value)))}catch{throw new InvalidJsonHeaderError}}}}var InvalidJsonHeaderError;var init_HeaderCodec=__esm({"node_modules/mppx/dist/internal/HeaderCodec.js"(){"use strict";init_esm2();InvalidJsonHeaderError=class extends Error{name="InvalidJsonHeaderError";constructor(){super("Invalid base64 JSON header.")}}}});var Types_exports2={};__export(Types_exports2,{ExactEip3009PayloadSchema:()=>ExactEip3009PayloadSchema,ExactPayloadSchema:()=>ExactPayloadSchema,ExactPermit2PayloadSchema:()=>ExactPermit2PayloadSchema,ExactTransferSchema:()=>ExactTransferSchema,ExtensionSchema:()=>ExtensionSchema,ExtensionsSchema:()=>ExtensionsSchema,PaymentPayloadSchema:()=>PaymentPayloadSchema,PaymentRequiredSchema:()=>PaymentRequiredSchema,PaymentRequirementsSchema:()=>PaymentRequirementsSchema,ResourceInfoSchema:()=>ResourceInfoSchema,SettleResponseSchema:()=>SettleResponseSchema,VerifyResponseSchema:()=>VerifyResponseSchema,assetTransferMethods:()=>assetTransferMethods,evmNetworkPrefix:()=>evmNetworkPrefix2,exactIntent:()=>exactIntent,paymentMethod:()=>paymentMethod2,paymentRequiredHeader:()=>paymentRequiredHeader,paymentResponseHeader:()=>paymentResponseHeader,paymentSignatureHeader:()=>paymentSignatureHeader,schemes:()=>schemes,syntheticChallengeIdPrefix:()=>syntheticChallengeIdPrefix,toPaymentRequirements:()=>toPaymentRequirements,versions:()=>versions});function toPaymentRequirements(request){const{extensions:_extensions,resource:_resource,...paymentRequirements}=request;return PaymentRequirementsSchema.parse(paymentRequirements)}var versions,paymentMethod2,exactIntent,schemes,assetTransferMethods,evmNetworkPrefix2,syntheticChallengeIdPrefix,paymentRequiredHeader,paymentSignatureHeader,paymentResponseHeader,nonEmptyString,positiveNumber,atomicAmount2,address2,evmNetwork,ResourceInfoSchema,ExactTransferSchema,PaymentRequirementsSchema,ExtensionSchema,ExtensionsSchema,PaymentRequiredSchema,ExactEip3009PayloadSchema,ExactPermit2PayloadSchema,ExactPayloadSchema,PaymentPayloadSchema,VerifyResponseSchema,SettleResponseSchema;var init_Types2=__esm({"node_modules/mppx/dist/x402/Types.js"(){"use strict";init_zod();versions=[2];paymentMethod2="evm";exactIntent="charge";schemes=["exact"];assetTransferMethods=["eip3009","permit2"];evmNetworkPrefix2="eip155:";syntheticChallengeIdPrefix="x402:";paymentRequiredHeader="PAYMENT-REQUIRED";paymentSignatureHeader="PAYMENT-SIGNATURE";paymentResponseHeader="PAYMENT-RESPONSE";nonEmptyString=string2().check(_minLength(1));positiveNumber=number2().check(refine(value=>value>0,"Must be positive"));atomicAmount2=string2().check(_regex(/^\d+$/,"Invalid atomic amount"));address2=address();evmNetwork=string2().check(_regex(new RegExp(`^${evmNetworkPrefix2}\\d+$`),"Invalid EVM CAIP-2 network"));ResourceInfoSchema=object({description:optional(string2()),iconUrl:optional(string2()),mimeType:optional(string2()),serviceName:optional(string2()),tags:optional(array(string2())),url:nonEmptyString});ExactTransferSchema=discriminatedUnion("type",[object({name:nonEmptyString,type:literal("eip3009"),version:nonEmptyString}),object({name:optional(string2()),type:literal("permit2"),version:optional(string2())})]);PaymentRequirementsSchema=object({amount:atomicAmount2,asset:nonEmptyString,extra:optional(record(string2(),unknown())),maxTimeoutSeconds:positiveNumber,network:evmNetwork,payTo:nonEmptyString,scheme:_enum2(schemes)});ExtensionSchema=object({info:record(string2(),unknown()),schema:record(string2(),unknown())});ExtensionsSchema=record(string2(),ExtensionSchema);PaymentRequiredSchema=object({accepts:array(PaymentRequirementsSchema).check(_minLength(1)),error:optional(string2()),extensions:optional(ExtensionsSchema),resource:ResourceInfoSchema,x402Version:literal(2)});ExactEip3009PayloadSchema=object({authorization:object({from:address2,nonce:hash2(),to:address2,validAfter:atomicAmount2,validBefore:atomicAmount2,value:atomicAmount2}),signature:signature()});ExactPermit2PayloadSchema=object({permit2Authorization:object({deadline:atomicAmount2,from:address2,nonce:atomicAmount2,permitted:object({amount:atomicAmount2,token:address2}),spender:address2,witness:object({to:address2,validAfter:atomicAmount2})}),signature:signature()});ExactPayloadSchema=union([ExactEip3009PayloadSchema,ExactPermit2PayloadSchema]);PaymentPayloadSchema=object({accepted:PaymentRequirementsSchema,extensions:optional(ExtensionsSchema),payload:ExactPayloadSchema,resource:optional(ResourceInfoSchema),x402Version:literal(2)});VerifyResponseSchema=object({extensions:optional(ExtensionsSchema),extra:optional(record(string2(),unknown())),invalidMessage:optional(string2()),invalidReason:optional(string2()),isValid:boolean2(),payer:optional(string2())});SettleResponseSchema=object({amount:optional(atomicAmount2),errorMessage:optional(string2()),errorReason:optional(string2()),extensions:optional(ExtensionsSchema),extra:optional(record(string2(),unknown())),network:nonEmptyString,payer:optional(string2()),success:boolean2(),transaction:string2()})}});var Header_exports={};__export(Header_exports,{decodePaymentRequired:()=>decodePaymentRequired,decodePaymentRequiredEnvelope:()=>decodePaymentRequiredEnvelope,decodePaymentResponse:()=>decodePaymentResponse,decodePaymentSignature:()=>decodePaymentSignature,encodePaymentRequired:()=>encodePaymentRequired,encodePaymentResponse:()=>encodePaymentResponse,encodePaymentSignature:()=>encodePaymentSignature});function decodePaymentRequiredEnvelope(value){try{const parsed=JSON.parse(Base64_exports.toString(value));return parsePaymentRequiredEnvelope(parsed)}catch{throw new InvalidJsonHeaderError}}var paymentRequired,paymentSignature,paymentResponse,encodePaymentRequired,decodePaymentRequired,encodePaymentSignature,decodePaymentSignature,encodePaymentResponse,decodePaymentResponse,parsePaymentRequiredEnvelope;var init_Header=__esm({"node_modules/mppx/dist/x402/Header.js"(){"use strict";init_esm2();init_HeaderCodec();init_Types2();paymentRequired=createJson(PaymentRequiredSchema);paymentSignature=createJson(PaymentPayloadSchema);paymentResponse=createJson(SettleResponseSchema);encodePaymentRequired=paymentRequired.encode;decodePaymentRequired=paymentRequired.decode;encodePaymentSignature=paymentSignature.encode;decodePaymentSignature=paymentSignature.decode;encodePaymentResponse=paymentResponse.encode;decodePaymentResponse=paymentResponse.decode;parsePaymentRequiredEnvelope=value=>{if(!value||typeof value!=="object"||Array.isArray(value))throw new InvalidJsonHeaderError;const record2=value;if(record2.x402Version!==2||!Array.isArray(record2.accepts))throw new InvalidJsonHeaderError;const resource=ResourceInfoSchema.parse(record2.resource);const extensions=record2.extensions!==void 0?ExtensionsSchema.safeParse(record2.extensions).data:void 0;return{accepts:record2.accepts,...extensions?{extensions}:{},resource,x402Version:2}}}});var x402_exports={};__export(x402_exports,{Assets:()=>Assets_exports,ExactEip3009PayloadSchema:()=>ExactEip3009PayloadSchema,ExactPayloadSchema:()=>ExactPayloadSchema,ExactPermit2PayloadSchema:()=>ExactPermit2PayloadSchema,ExactTransferSchema:()=>ExactTransferSchema,ExtensionSchema:()=>ExtensionSchema,ExtensionsSchema:()=>ExtensionsSchema,Header:()=>Header_exports,PaymentPayloadSchema:()=>PaymentPayloadSchema,PaymentRequiredSchema:()=>PaymentRequiredSchema,PaymentRequirementsSchema:()=>PaymentRequirementsSchema,ResourceInfoSchema:()=>ResourceInfoSchema,SettleResponseSchema:()=>SettleResponseSchema,Types:()=>Types_exports2,VerifyResponseSchema:()=>VerifyResponseSchema,assetTransferMethods:()=>assetTransferMethods,assets:()=>Assets_exports,evmNetworkPrefix:()=>evmNetworkPrefix2,exactIntent:()=>exactIntent,paymentMethod:()=>paymentMethod2,paymentRequiredHeader:()=>paymentRequiredHeader,paymentResponseHeader:()=>paymentResponseHeader,paymentSignatureHeader:()=>paymentSignatureHeader,schemes:()=>schemes,syntheticChallengeIdPrefix:()=>syntheticChallengeIdPrefix,toPaymentRequirements:()=>toPaymentRequirements,versions:()=>versions});var init_x402=__esm({"node_modules/mppx/dist/x402/index.js"(){"use strict";init_Assets();init_Header();init_Types2();init_Assets();init_Types2()}});var dist_exports={};__export(dist_exports,{BodyDigest:()=>BodyDigest_exports,Challenge:()=>Challenge_exports,Constants:()=>Constants_exports,Credential:()=>Credential_exports,Errors:()=>Errors_exports2,Expires:()=>Expires_exports,Mcp:()=>Mcp_exports,Method:()=>Method_exports,PaymentRequest:()=>PaymentRequest_exports,Receipt:()=>Receipt_exports,Store:()=>Store_exports,evm:()=>evm_exports,x402:()=>x402_exports,z:()=>zod_exports});var init_dist2=__esm({"node_modules/mppx/dist/index.js"(){"use strict";init_BodyDigest();init_Challenge();init_Constants();init_Credential();init_Errors2();init_Expires();init_evm();init_Mcp();init_Method();init_PaymentRequest();init_Receipt();init_Store();init_x402();init_zod()}});import{decodePaymentRequiredHeader,DvmError as DvmError6,fetchBtcUsdRate,isAbortError as isAbortError2,isFundingReceipt,isSignedJobReceipt,parseCreditMenu,parseCreditTerms,providerProseSources as providerProseSources2,ROUTER_FEEDBACK_CLAIM_HEADER,SUPPORTED_PROTOCOL_VERSION,usdToMsats,X402_V1_VERSION,X402_VERSION}from"@dvmkit/sdk/internal";function jobTokenHeader(jobToken){return jobToken?{"X-Job-Token":jobToken}:{}}function captureTraceId(res){const tp=res.headers.get("traceparent");if(tp){const parsed=parseTraceparent(tp);if(parsed)setOutputTraceId(parsed.traceId)}}async function tempoTransactionHashFromResponse(res){const encoded=res.headers.get("Payment-Receipt");if(!encoded)return void 0;try{const{Receipt}=await Promise.resolve().then(()=>(init_dist2(),dist_exports));const receipt=Receipt.deserialize(encoded);if(receipt.method!=="tempo")return void 0;const extension2=receipt;const candidate=extension2.intent==="session"?typeof extension2.txHash==="string"?extension2.txHash:void 0:receipt.reference;return candidate&&/^0x[a-f0-9]{64}$/i.test(candidate)?candidate.toLowerCase():void 0}catch{return void 0}}function parseSignedReceipt(value){if(value===void 0)return{};return isSignedJobReceipt(value)?{receipt:value}:{receiptParseError:"shape_invalid"}}function parseFundingReceipt(value){if(value===void 0)return{};return isFundingReceipt(value)?{fundingReceipt:value}:{fundingReceiptParseError:"shape_invalid"}}function parseFundingResponse(data){return{...parseFundingReceipt(data.funding_receipt),...typeof data.funded_micro==="number"?{fundedMicro:data.funded_micro}:{},...data.credit&&typeof data.credit==="object"&&!Array.isArray(data.credit)?{credit:data.credit}:{}}}function parseRequestResultResponse(value,requestId,httpStatus){if(!value||typeof value!=="object"||Array.isArray(value)){throw malformedRequestResult(requestId,"response_not_object")}const data=value;if(data.request_id!==requestId){throw malformedRequestResult(requestId,"request_id_mismatch")}if(typeof data.job_id!=="string"||data.job_id.trim().length===0||data.job_id.length>512||hasAsciiControl(data.job_id)){throw malformedRequestResult(requestId,"job_id_invalid")}const allowedStatuses=new Set(["processing","awaiting-input","completed","failed","cancelled"]);if(!allowedStatuses.has(data.status)){throw malformedRequestResult(requestId,"status_invalid")}const status2=data.status;const terminal=status2==="completed"||status2==="failed"||status2==="cancelled";if(httpStatus===202&&terminal||httpStatus===200&&!terminal){throw malformedRequestResult(requestId,"http_status_mismatch")}if(data.job_token!==void 0&&!isOpaqueJobToken(data.job_token)){throw malformedRequestResult(requestId,"job_token_invalid")}if(data.transaction_hash!==void 0&&(typeof data.transaction_hash!=="string"||!/^0x[0-9a-fA-F]{64}$/.test(data.transaction_hash))){throw malformedRequestResult(requestId,"transaction_hash_invalid")}if(data.summary!==void 0&&typeof data.summary!=="string"){throw malformedRequestResult(requestId,"summary_invalid")}if(data.has_artifacts!==void 0&&typeof data.has_artifacts!=="boolean"){throw malformedRequestResult(requestId,"has_artifacts_invalid")}if(data.artifact_count!==void 0&&(!Number.isSafeInteger(data.artifact_count)||data.artifact_count<0)){throw malformedRequestResult(requestId,"artifact_count_invalid")}if(data.payload_in!==void 0&&data.payload_in!=="summary"&&data.payload_in!=="messages"){throw malformedRequestResult(requestId,"payload_in_invalid")}let receipt;if(data.receipt!==void 0){if(!isSignedJobReceipt(data.receipt)||data.receipt.job_id!==data.job_id||!/^[0-9a-fA-F]{64}$/.test(data.receipt.receipt_pubkey)||!/^[0-9a-fA-F]{128}$/.test(data.receipt.signature)||terminal&&data.receipt.outcome!==status2){throw malformedRequestResult(requestId,"receipt_invalid")}receipt=data.receipt}return{jobId:data.job_id,status:status2,...typeof data.transaction_hash==="string"?{transactionHash:data.transaction_hash}:{},...typeof data.summary==="string"?{summary:data.summary}:{},...typeof data.has_artifacts==="boolean"?{hasArtifacts:data.has_artifacts}:{},...typeof data.artifact_count==="number"?{artifactCount:data.artifact_count}:{},...data.payload_in==="summary"||data.payload_in==="messages"?{payloadIn:data.payload_in}:{},...typeof data.job_token==="string"?{jobToken:data.job_token}:{},...receipt?{receipt}:{},...parseFundingResponse(data)}}function isOpaqueJobToken(value){return typeof value==="string"&&value.length>0&&value.length<=4096&&value.trim()===value&&!hasAsciiControl(value)}function hasAsciiControl(value){for(const character of value){const code=character.charCodeAt(0);if(code<=31||code===127)return true}return false}function malformedRequestResult(requestId,reason){return new DvmError6("request_outcome_unknown","The provider returned a malformed request recovery response.","Do not submit or pay for a replacement. Retry the read-only lookup after the provider is fixed.",{request_id:requestId,status:"unknown",reason})}function parseTrustAnchor(value){if(!value||typeof value!=="object"||Array.isArray(value))return void 0;const b2=value;const attestation=b2.attestation;const wellFormed=typeof b2.pubkey==="string"&&typeof b2.signature==="string"&&!!attestation&&typeof attestation==="object"&&!Array.isArray(attestation);return wellFormed?value:void 0}function parseX402PaymentRequired(headers,body){const v2=headers.get("PAYMENT-REQUIRED");if(v2){try{return decodePaymentRequiredHeader(v2)}catch{}}if(body.x402Version!==X402_V1_VERSION||!Array.isArray(body.accepts))return void 0;return{x402Version:X402_V1_VERSION,...typeof body.message==="string"?{error:body.message}:{},accepts:body.accepts}}function x402RequiredUsdcMicro(required3){if(!required3)return void 0;if(required3.x402Version===X402_VERSION){return required3.accepts.at(0)?.amount}return required3.accepts.at(0)?.maxAmountRequired}async function parseSSEStream(res,options){const messages=[];if(!res.body){return{messages,reason:"error"}}const reader=res.body.getReader();const decoder3=new TextDecoder;let buffer="";let lastReason="yield";try{for(;;){const{done,value}=await reader.read();if(done)break;buffer+=decoder3.decode(value,{stream:true});let hitYield=false;let boundary;while((boundary=buffer.indexOf("\n\n"))!==-1){const block=buffer.slice(0,boundary);buffer=buffer.slice(boundary+2);const dataLine=block.split("\n").find(line=>line.startsWith("data:"));if(!dataLine)continue;const json3=dataLine.slice("data:".length).trim();try{const msg=JSON.parse(json3);messages.push(msg);options?.onMessage?.(msg);if(YIELD_TYPES.has(msg.type)){if(msg.type==="complete")lastReason="complete";else if(msg.type==="cancel")lastReason="cancel";else lastReason="yield";hitYield=true}}catch{}}if(hitYield){reader.cancel().catch(()=>void 0);return{messages,reason:lastReason}}}}catch{lastReason="error"}finally{reader.releaseLock()}return{messages,reason:lastReason}}function parseStructuredError(body){const parsed=parseJsonObject(body);if(!parsed)return null;const err=parsed.error;if(err&&typeof err==="object"&&!Array.isArray(err)){const e17=err;if(typeof e17.code!=="string")return null;return buildStructuredError(e17.code,e17)}if(typeof err!=="string")return null;if(err==="invalid_input"||err==="invalid_quote_data"){const fields={...parsed,...typeof parsed.message!=="string"&&typeof parsed.details==="string"?{message:parsed.details}:{}};return buildStructuredError("invalid_input",fields)}return buildStructuredError(err,parsed)}function jobCredentialError(status2,body){if(status2!==401)return null;return parseStructuredError(body)}function buildStructuredError(code,fields){const display=typeof fields.display==="string"?fields.display:void 0;const providerMessage=typeof fields.message==="string"?fields.message:void 0;const message2=providerMessage??display??"The provider returned an error without explanatory prose.";const hint=typeof fields.hint==="string"?fields.hint:void 0;const data={};if(display!==void 0)data.display=display;if(typeof fields.retryable==="boolean")data.retryable=fields.retryable;if(fields.status==="unknown")data.status=fields.status;if(typeof fields.request_id==="string")data.request_id=fields.request_id;if(fields.server_acceptance==="absent")data.server_acceptance=fields.server_acceptance;if(fields.payment_state==="unknown")data.payment_state=fields.payment_state;const detectedSources=providerProseSources2(fields,data);const proseSources=display!==void 0&&providerMessage===void 0?{...detectedSources,message:"provider"}:detectedSources;return new DvmError6(code,message2,hint,Object.keys(data).length>0?data:void 0,void 0,proseSources)}function providerResponseError(code,message2){return new DvmError6(code,message2,void 0,void 0,void 0,{message:"provider"})}function parseJsonObject(body){try{const parsed=JSON.parse(body);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return null;return parsed}catch{return null}}function isReceipt402(code){return code===void 0||code==="payment_required"||code==="payment_insufficient"}function buildPaymentError(errorBody){const code=typeof errorBody.error==="string"?errorBody.error:"payment_insufficient";return buildStructuredError(code,errorBody)}async function paymentHeaders(payment){const headers={};if(payment?.cashuToken){headers["X-Cashu"]=payment.cashuToken}if(payment?.cashuRequestId){headers["X-Cashu-Request-Id"]=payment.cashuRequestId}if(payment?.x402Payment){headers[payment.x402Version===X402_VERSION?"PAYMENT-SIGNATURE":"X-PAYMENT"]=payment.x402Payment}if(payment?.mppCredentialRaw){headers.Authorization=payment.mppCredentialRaw}else if(payment?.mppCredential){const{Credential}=await Promise.resolve().then(()=>(init_dist2(),dist_exports));headers.Authorization=Credential.serialize(payment.mppCredential)}return headers}function withCreditErrorContext(err,body){const extra={};for(const key of CREDIT_CONTEXT_FIELDS){if(typeof body[key]==="number")extra[key]=body[key]}const menu=parseCreditMenu(body.credit);if(menu)extra.credit=menu;const lightning=parseLightningOffer(body.lightning);if(lightning)extra.lightning=lightning;for(const key of["credit_id","fund_id","drain_id","credit_rail","credit_instrument","credit_channel_id","bound_credit_id","rail","settlement_drain_id"]){if(typeof body[key]==="string")extra[key]=body[key]}for(const key of["drain_registered","drain_id_retired","credential_refresh_required"]){if(typeof body[key]==="boolean")extra[key]=body[key]}for(const key of["funding","alternatives"]){const rails=body[key];if(Array.isArray(rails)&&rails.every(r=>typeof r==="string")){extra[key]=rails}}if(Object.keys(extra).length===0)return err;return new DvmError6(err.code,err.message,err.hint,{...err.data,...extra},err.display,err.proseSources)}function parseLightningOffer(raw2){if(!raw2||typeof raw2!=="object"||Array.isArray(raw2))return void 0;const block=raw2;if(typeof block.invoice!=="string"||block.invoice.length===0)return void 0;if(typeof block.amount_msats!=="number"||block.amount_msats<=0)return void 0;return block}function parseUpfront(data){const raw2=data.upfront;if(raw2&&typeof raw2==="object"){const u=raw2;if(typeof u.amount==="number"&&typeof u.currency==="string"){const amountMicro=exactMicro(u.amount_micro);return{amount:u.amount,currency:u.currency,...amountMicro&&{amount_micro:amountMicro}}}}return{amount:0,currency:"usd"}}function exactMicro(raw2){return typeof raw2==="number"&&Number.isSafeInteger(raw2)&&raw2>0?raw2:void 0}async function deriveAdvisorySats(upfront,data){if(typeof data.price_msats==="number")return data.price_msats;if(upfront.currency!=="usd"||upfront.amount<=0)return void 0;try{const rate=await fetchBtcUsdRate();return usdToMsats(upfront.amount,rate)}catch{return void 0}}var HttpsTransport,YIELD_TYPES,CREDIT_CONTEXT_FIELDS;var init_https=__esm({"src/lib/transport/https.ts"(){"use strict";init_output();init_traceparent();init_http();init_job_envelope();HttpsTransport=class{async describe(provider,options){const url2=`${provider.endpoint}/v1/info`;const signal=options?.timeoutMs&&options.timeoutMs>0?AbortSignal.timeout(options.timeoutMs):void 0;let res;try{res=await dvmFetch(url2,{signal})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","Provider metadata read timed out.","The provider may be starting up. Retry in a few seconds.")}throw err}if(!res.ok){throw providerResponseError("provider_error",`Provider returned ${res.status}: ${await res.text()}`)}const data=await res.json();const providerVersion=data.protocol_version;if(providerVersion!==void 0&&providerVersion>SUPPORTED_PROTOCOL_VERSION){throw new DvmError6("unsupported_version",`Provider requires protocol version ${providerVersion}, but this client only supports up to ${SUPPORTED_PROTOCOL_VERSION}.`,"Upgrade dvmkit to interact with this provider.")}const builder=parseTrustAnchor(data.builder);return{name:data.name,about:data.description,tags:data.tags,auth:data.auth,authAudience:data.auth_audience,pricing:data.pricing,mints:data.mints,quote:data.quote,inputSchema:data.input_schema,protocolVersion:providerVersion,paymentMethods:data.payment?.methods,credit:parseCreditTerms(data.credit),x402:data.x402,tempo:data.tempo,cashu:data.cashu,sdkSha:data.sdk_sha,capabilities:data.capabilities,...data.receipts===true?{receipts:true}:{},...data.request_recovery===true?{requestRecovery:true}:{},...builder?{builder}:{}}}async quote(provider,job){const url2=`${provider.endpoint}/v1/quote`;const body=JSON.stringify(envelopeToPayload(job));const res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json"},body});captureTraceId(res);if(!res.ok){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`Quote failed (${res.status}): ${text}`)}const data=await res.json();const upfront=parseUpfront(data);const description=typeof data.description==="string"?data.description:"";const advisorySats=await deriveAdvisorySats(upfront,data);const quote={upfront,description,priceMsats:advisorySats??0,mints:data.mints,expiresAt:data.expires_at};if(typeof data.hint==="string")quote.hint=data.hint;if(data.shape==="fixed"||data.shape==="rate")quote.shape=data.shape;if(data.rate&&typeof data.rate==="object"){quote.rate=data.rate}const payment=data.payment;if(payment&&Array.isArray(payment.methods)&&payment.refundable&&typeof payment.refundable==="object"){quote.payment={methods:payment.methods,refundable:payment.refundable}}const creditMenu=parseCreditMenu(data.credit);if(creditMenu)quote.credit=creditMenu;return[quote]}async submit(provider,job,payment,options){const url2=`${provider.endpoint}/v1/job`;const body=JSON.stringify(envelopeToPayload(job));const headers={"Content-Type":"application/json",...await paymentHeaders(payment)};const signal=options?.timeoutMs&&options.timeoutMs>0?AbortSignal.timeout(options.timeoutMs):void 0;let res;try{res=await dvmFetch(url2,{method:"POST",headers,body,signal})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","Job submission timed out.","The provider may be starting up. Retry in a few seconds or use a longer --timeout.")}throw new DvmError6("provider_unreachable",`Could not reach ${url2}: ${err instanceof Error?err.message:String(err)}`,"The provider may be down or unreachable from this network. Retry once it is back.")}captureTraceId(res);const tempoTransactionHash=await tempoTransactionHashFromResponse(res);if(res.status===402){let errorBody;try{errorBody=await res.json()}catch{throw new DvmError6("payment_insufficient","Payment required (unparseable response).")}const requiredMsats=errorBody.required_msats;const receivedMsats=errorBody.received_msats;if(requiredMsats!==void 0&&isReceipt402(errorBody.error)){const creditMenu=parseCreditMenu(errorBody.credit);const priceMicro=exactMicro(errorBody.price_micro);const rate=priceMicro===void 0?await fetchBtcUsdRate().catch(()=>null):null;const usd=rate?requiredMsats/1e11*rate:0;const upfront=priceMicro===void 0?{amount:Math.round(usd*1e4)/1e4,currency:"usd"}:{amount:priceMicro/1e6,currency:typeof errorBody.price_currency==="string"?errorBody.price_currency:creditMenu?.currency??"usd",amount_micro:priceMicro};const x402PaymentRequired=parseX402PaymentRequired(res.headers,errorBody);const requiredUsdcMicro=x402RequiredUsdcMicro(x402PaymentRequired);return{jobId:"",status:"payment-required",quotes:[{upfront,description:receivedMsats?`Received ${String(receivedMsats)} msats, need ${String(requiredMsats)} msats`:"Upfront payment required",priceMsats:requiredMsats,...requiredUsdcMicro!==void 0&&{requiredUsdcMicro},...x402PaymentRequired&&{x402PaymentRequired},...creditMenu?{credit:creditMenu}:{},mints:errorBody.mints}]}}throw withCreditErrorContext(buildPaymentError(errorBody),errorBody)}if(!res.ok&&res.status!==202){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`Job submission failed (${res.status}): ${text}`)}const data=await res.json();const feedbackClaim=res.headers.get(ROUTER_FEEDBACK_CLAIM_HEADER)??void 0;const jobToken=data.job_token;if(res.status===202){return{jobId:data.job_id,status:data.status==="awaiting-input"?"awaiting-input":"processing",estimatedSeconds:data.estimated_seconds,jobToken,...tempoTransactionHash?{transactionHash:tempoTransactionHash}:{},...feedbackClaim?{feedbackClaim}:{},...parseFundingResponse(data)}}return{jobId:data.job_id,status:"completed",summary:data.summary,hasArtifacts:data.has_artifacts,artifactCount:data.artifact_count,payloadIn:data.payload_in,cashuChange:res.headers.get("X-Cashu-Change")??void 0,jobToken,...tempoTransactionHash?{transactionHash:tempoTransactionHash}:{},...feedbackClaim?{feedbackClaim}:{},...parseSignedReceipt(data.receipt),...parseFundingResponse(data)}}async requestResult(provider,requestId,signedJob){const url2=`${provider.endpoint}/v1/request-result/${encodeURIComponent(requestId)}`;const res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(envelopeToPayload(signedJob))});captureTraceId(res);if(!res.ok&&res.status!==202){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`Request lookup failed (${res.status}): ${text}`)}let data;try{data=await res.json()}catch{throw malformedRequestResult(requestId,"response_not_json")}return parseRequestResultResponse(data,requestId,res.status)}async requestResume(provider,requestId,signedJob,options){const url2=`${provider.endpoint}/v1/request-resume/${encodeURIComponent(requestId)}`;const signal=options?.timeoutMs&&options.timeoutMs>0?AbortSignal.timeout(options.timeoutMs):void 0;let res;try{res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(envelopeToPayload(signedJob)),signal})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","Request recovery timed out.","Run request-result before retrying recovery.")}throw new DvmError6("provider_unreachable",`Could not reach ${url2}: ${err instanceof Error?err.message:String(err)}`,"Run request-result before retrying recovery.")}captureTraceId(res);if(!res.ok&&res.status!==202){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`Request recovery failed (${res.status}): ${text}`)}}async credit(provider,signedBody,payment,options){const url2=`${provider.endpoint}/v1/credit`;const headers={"Content-Type":"application/json",...await paymentHeaders(payment)};const signal=options?.timeoutMs&&options.timeoutMs>0?AbortSignal.timeout(options.timeoutMs):void 0;let res;try{res=await dvmFetch(url2,{method:"POST",headers,body:JSON.stringify(signedBody),signal})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","Credit operation timed out.","The provider may be starting up. Retry in a few seconds.")}throw new DvmError6("provider_unreachable",`Could not reach ${url2}: ${err instanceof Error?err.message:String(err)}`,"The provider may be down or unreachable from this network. Retry once it is back.")}captureTraceId(res);const tempoTransactionHash=await tempoTransactionHashFromResponse(res);if(!res.ok){const mppChallenges=res.status===402&&res.headers.get("WWW-Authenticate")?(await Promise.resolve().then(()=>(init_dist2(),dist_exports))).Challenge.fromHeadersList(res.headers):[];const text=await res.text();const parsed=parseJsonObject(text);const structured=parseStructuredError(text);if(structured){const contextual=withCreditErrorContext(structured,parsed??{});const x402PaymentRequired=parseX402PaymentRequired(res.headers,parsed??{});if(x402PaymentRequired){contextual.data={...contextual.data,x402_payment_required:x402PaymentRequired}}if(tempoTransactionHash){contextual.data={...contextual.data,transaction_hash:tempoTransactionHash}}throw mppChallenges.length>0?new DvmError6(contextual.code,contextual.message,contextual.hint,{...contextual.data,tempo_challenges:mppChallenges},contextual.display,contextual.proseSources):contextual}throw providerResponseError("provider_error",`Credit operation failed (${res.status}): ${text}`)}const result=await res.json();const{menu:rawMenu,funding_receipt:rawFundingReceipt,...creditResult}=result;const menu=parseCreditMenu(rawMenu);const x402PaymentResponse=res.headers.get("PAYMENT-RESPONSE")??res.headers.get("X-PAYMENT-RESPONSE")??void 0;const enriched={...creditResult,...parseFundingReceipt(rawFundingReceipt),...x402PaymentResponse?{x402PaymentResponse}:{},...tempoTransactionHash?{transactionHash:tempoTransactionHash}:{}};return menu?{...enriched,menu}:enriched}async status(jobId,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS status check requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}`;const res=await dvmFetch(url2,{headers:jobTokenHeader(options?.jobToken)});captureTraceId(res);if(res.status===404){throw new DvmError6("job_not_found",`Job ${jobId} not found.`)}if(!res.ok){const credentialErr=jobCredentialError(res.status,await res.text());if(credentialErr)throw credentialErr;throw new DvmError6("provider_error",`Status check failed (${res.status})`)}const data=await res.json();return{jobId,status:data.status,summary:data.summary,hasArtifacts:data.has_artifacts,artifactCount:data.artifact_count,payloadIn:data.payload_in,message:data.message,cashuChange:res.headers.get("X-Cashu-Change")??void 0,...parseSignedReceipt(data.receipt),...parseFundingResponse(data)}}async getMessages(jobId,after,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS getMessages requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}/messages?after=${after}`;const res=await dvmFetch(url2,{headers:jobTokenHeader(options?.jobToken)});if(!res.ok){const text=await res.text();const credentialErr=jobCredentialError(res.status,text);if(credentialErr)throw credentialErr;throw providerResponseError("provider_error",`getMessages failed (${res.status}): ${text}`)}const data=await res.json();return data.messages}async sendMessage(jobId,message2,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS sendMessage requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}/messages`;const body=JSON.stringify({type:message2.type,content:message2.content});let res;try{res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json",...jobTokenHeader(options?.jobToken)},body})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","sendMessage timed out.")}throw err}if(res.status===402){let errorBody;try{errorBody=await res.json()}catch{throw new DvmError6("payment_insufficient","Payment required (unparseable response).")}throw buildPaymentError(errorBody)}if(res.status===409){const body2=parseJsonObject(await res.text());if(body2?.error==="replay_rejected")throw buildPaymentError(body2);throw new DvmError6("job_terminal","Job is no longer active.",`The job has already completed or been cancelled, so it can't accept more messages. Fetch the final result with 'dvm messages ${jobId}'.`)}if(!res.ok){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`sendMessage failed (${res.status}): ${text}`)}}async stream(jobId,afterSeq,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS stream requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}/messages?after=${afterSeq}`;const res=await dvmFetch(url2,{headers:{Accept:"text/event-stream",...jobTokenHeader(options?.jobToken)},signal:options?.signal});if(!res.ok){const text=await res.text();const credentialErr=jobCredentialError(res.status,text);if(credentialErr)throw credentialErr;throw providerResponseError("provider_error",`stream failed (${res.status}): ${text}`)}const contentType=res.headers.get("content-type")??"";if(contentType.includes("application/json")){const body=await res.json();const messages=body.messages??[];const last=messages.at(-1);const reason=last?.type==="complete"?"complete":last?.type==="cancel"?"cancel":"yield";for(const msg of messages)options?.onMessage?.(msg);return{messages,reason}}return parseSSEStream(res,options)}async cancel(jobId,reason,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS cancel requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}`;const body=reason?JSON.stringify({reason}):void 0;const tokenHeader=jobTokenHeader(options?.jobToken);const headers=body?{"Content-Type":"application/json",...tokenHeader}:tokenHeader;const res=await dvmFetch(url2,{method:"DELETE",headers,body});if(!res.ok){const text=await res.text();const credentialErr=jobCredentialError(res.status,text);if(credentialErr)throw credentialErr;throw providerResponseError("provider_error",`Cancel failed (${res.status}): ${text}`)}}async probeMppChallenges(provider,job){const url2=`${provider.endpoint}/v1/job`;const body=JSON.stringify(envelopeToPayload(job));const res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json"},body});if(res.status!==402){await res.text().catch(()=>void 0);if(res.ok||res.status===202)return[];throw new DvmError6("provider_error",`MPP probe expected 402 but got ${res.status}.`,"Check the DVM's `/v1/info` for advertised payment methods.")}const{Challenge}=await Promise.resolve().then(()=>(init_dist2(),dist_exports));return Challenge.fromHeadersList(res.headers)}close(){}};YIELD_TYPES=new Set(["prompt","payment-request","working","complete","cancel"]);CREDIT_CONTEXT_FIELDS=["remaining_micro","shortfall_micro","balance_micro","expiry_ms","fundable_micro","expected_micro","min_micro"]}});function createDvmTransport(){return new HttpsTransport}var init_factory=__esm({"src/lib/transport/factory.ts"(){"use strict";init_https()}});import{SUPPORTED_PROTOCOL_VERSION as SUPPORTED_PROTOCOL_VERSION2}from"@dvmkit/sdk/internal";var init_transport=__esm({"src/lib/transport/index.ts"(){"use strict";init_factory();init_https()}});import{deriveBuilderLockKeypair,DvmError as DvmError7,toLockPubkey}from"@dvmkit/sdk/internal";function resolveBuilderLockIdentity(handle2){const{mnemonic,canonicalDvmId,rotationIndex}=readBuilderContextByHandle(handle2);return{handle:handle2,canonicalDvmId,rotationIndex,lockPubkey:deriveBuilderLockKeypair(mnemonic,canonicalDvmId,rotationIndex).pubkey}}function resolveBuilderLockKeyring(dvmId){return buildKeyring(readBuilderContext(dvmId))}async function resolveBuilderLockKeyringByHandle(handle2,endpoint){const mnemonic=requireBuilderMnemonic();const resolved=await resolveBuilderEntryByHandle(handle2,mnemonic,endpoint);return buildKeyring({handle:resolved.entry.handle,mnemonic,canonicalDvmId:resolved.entry.canonical_dvm_id,rotationIndex:resolved.entry.current_rotation_index},resolved.signingRotationIndex)}function buildKeyring({handle:handle2,mnemonic,canonicalDvmId,rotationIndex},signingRotationIndex=rotationIndex){const keypairsByPubkey=new Map;let currentKeypair;for(let i=0;i<=rotationIndex;i++){const kp=deriveBuilderLockKeypair(mnemonic,canonicalDvmId,i);keypairsByPubkey.set(toLockPubkey(kp.pubkey),kp);if(i===signingRotationIndex)currentKeypair=kp}if(!currentKeypair){throw new Error("unreachable: signing rotation index walk produced no keypair")}return{handle:handle2,canonicalDvmId,rotationIndex,currentKeypair,keypairsByPubkey}}function readBuilderContext(dvmId){const mnemonic=requireBuilderMnemonic();const entry=requireSelectedBuilderDvm(dvmId);return{handle:entry.handle,mnemonic,canonicalDvmId:entry.canonical_dvm_id,rotationIndex:entry.current_rotation_index}}function readBuilderContextByHandle(handle2){const mnemonic=requireBuilderMnemonic();const entry=requireBuilderDvmByHandle(handle2);return{handle:entry.handle,mnemonic,canonicalDvmId:entry.canonical_dvm_id,rotationIndex:entry.current_rotation_index}}function requireBuilderMnemonic(){const mnemonic=readBuilderMnemonic();if(!mnemonic){throw new DvmError7("no_builder_mnemonic","No builder mnemonic found.","Run `dvmctl lock create` first to generate or import a mnemonic.")}return mnemonic}async function resolveBuilderEntryByHandle(handle2,mnemonic,endpoint){let ambiguity;try{const entry=requireBuilderDvmByHandle(handle2);return{entry,signingRotationIndex:entry.current_rotation_index}}catch(err){if(!(err instanceof DvmError7)||err.code!=="ambiguous_dvm_handle"||!endpoint){throw err}ambiguity=err}const advertised=await readAdvertisedCurrentLockPubkey(endpoint);if(!advertised)throw ambiguity;const candidates=findBuilderDvmsByHandle(handle2);const matching=candidates.flatMap(entry=>{const signingRotationIndex=matchingRotationIndex(entry,mnemonic,advertised);return signingRotationIndex===void 0?[]:[{entry,signingRotationIndex}]});if(matching.length===1)return matching[0];const candidateIds=candidates.map(entry=>entry.canonical_dvm_id);const matchingIds=matching.map(({entry})=>entry.canonical_dvm_id);const diagnostic=matching.length===0?`None of your entries derive the key this DVM advertises (${advertised}) across their recorded rotation indexes.`:`${matching.length} of your entries derive the key this DVM advertises (${advertised}), so the endpoint cannot settle which record is right.`;throw new DvmError7("ambiguous_dvm_handle",ambiguity.message,`${diagnostic} Candidates: ${candidateIds.join(", ")}.${matchingIds.length>0?` Matching candidates: ${matchingIds.join(", ")}.`:""} Restore the correct entry or rotation index in ${BUILDER_FILE}; nothing uses a guessed identity because the wrong keys would strand proofs.`,{advertised_lock_pubkey:advertised,candidates:candidateIds,matching_candidates:matchingIds})}async function readAdvertisedCurrentLockPubkey(endpoint){try{const provider=await createDvmTransport().describe({endpoint:endpoint.replace(/\/+$/,"")},{timeoutMs:DVM_INFO_PROBE_TIMEOUT_MS});const current=provider.cashu?.lock_pubkeys[0];return typeof current==="string"&&COMPRESSED_PUBKEY_PATTERN.test(current.trim())?toLockPubkey(current):void 0}catch{return void 0}}function matchingRotationIndex(entry,mnemonic,advertised){for(let i=0;i<=entry.current_rotation_index;i++){const derived=deriveBuilderLockKeypair(mnemonic,entry.canonical_dvm_id,i);if(toLockPubkey(derived.pubkey)===advertised)return i}return void 0}var DVM_INFO_PROBE_TIMEOUT_MS,COMPRESSED_PUBKEY_PATTERN;var init_builder_lock_identity=__esm({"src/lib/cashu/builder-lock-identity.ts"(){"use strict";init_builder_store();init_defaults();init_builder_mnemonic();init_transport();DVM_INFO_PROBE_TIMEOUT_MS=5e3;COMPRESSED_PUBKEY_PATTERN=/^0[23][0-9a-f]{64}$/i}});function blockUntilShutdown(getServer){let shuttingDown=false;const shutdown=()=>{if(shuttingDown)return;shuttingDown=true;void Promise.resolve(getServer().close()).finally(()=>process.exit(0))};process.once("SIGINT",shutdown);process.once("SIGTERM",shutdown);return new Promise(()=>{})}var init_keep_alive=__esm({"src/lib/keep-alive.ts"(){"use strict"}});import{existsSync as existsSync5,readFileSync as readFileSync5}from"fs";import{basename as basename2,resolve as resolve3}from"path";import{buildAttestation,deriveReceiptKeypair,DvmError as DvmError16,loadIdentitySecret,signAttestation}from"@dvmkit/sdk/internal";function signDeployAttestation(args){const receipt=args.withReceiptKey?deriveReceiptKeypair(args.builderSecret,args.dvmId):void 0;const payload=buildAttestation({dvmId:args.dvmId,slug:args.slug,capabilities:args.capabilities,builderPubkey:args.builderPubkey,receiptPubkey:receipt?.pubkey});return{identityPubkey:args.builderPubkey,payload,signature:signAttestation(payload,args.builderSecret),capabilities:args.capabilities,receiptSecret:receipt?.secret}}function buildDeployAttestation(cwd,slug,dvmId,opts={}){const pubkey=loadIdentityPubkey();const secret=loadIdentitySecret();if(!pubkey||!secret){throw new DvmError16("identity_required","Builder identity is missing or partial (pubkey \u2260 secret on disk).","Run `dvmctl identity create --force` to regenerate.")}return signDeployAttestation({builderSecret:secret,builderPubkey:pubkey,dvmId,slug,capabilities:readCapabilitiesForAttestation(cwd),withReceiptKey:opts.withReceiptKey})}function attestationEnv(attestation){const env2={DVMKIT_BUILDER_PUBKEY:attestation.identityPubkey,DVMKIT_BUILDER_ATTESTATION:JSON.stringify(attestation.payload),DVMKIT_BUILDER_SIGNATURE:attestation.signature,DVMKIT_DVM_ID:attestation.payload.dvm_id,DVMKIT_CANONICAL_DVM_ID:attestation.payload.dvm_id};if(attestation.receiptSecret)env2.DVMKIT_RECEIPT_KEY=attestation.receiptSecret;return env2}function requireBuilderIdentity(){if(loadIdentitySecret()===null){throw new DvmError16("identity_required","No builder identity found.","Run `dvmctl identity create` once on this workstation, then re-run `dvmctl deploy`.")}}function readCapabilitiesForAttestation(cwd){const pkg=readPackageJson(cwd);const dvmkit=pkg?.dvmkit;if(dvmkit==null||typeof dvmkit!=="object")return{};const raw2=dvmkit.capabilities;if(raw2===void 0)return{};if(raw2===null||typeof raw2!=="object"){throw new DvmError16("invalid_capabilities","`package.json#dvmkit.capabilities` must be an object or an array of capability names (or omitted).","Remove the field, declare an array of capability names, or replace it with an object literal.")}return raw2}function deriveSlug(cwd){const raw2=readPackageJson(cwd)?.name??basename2(cwd);return slugify2(raw2)}function slugify2(input){const slug=input.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return slug.slice(0,40).replace(/-$/,"")}function readPackageJson(cwd){const pkgPath=resolve3(cwd,"package.json");if(!existsSync5(pkgPath))return null;try{return JSON.parse(readFileSync5(pkgPath,"utf-8"))}catch{return null}}var ATTESTATION_ENV_KEYS;var init_deploy_attestation=__esm({"src/lib/deploy-attestation.ts"(){"use strict";init_builder_store();ATTESTATION_ENV_KEYS=["DVMKIT_BUILDER_PUBKEY","DVMKIT_BUILDER_ATTESTATION","DVMKIT_BUILDER_SIGNATURE","DVMKIT_RECEIPT_KEY","DVMKIT_DVM_ID","DVMKIT_CANONICAL_DVM_ID"]}});import{pathToFileURL}from"url";import{configureDVM,isConfiguredDVMDescriptor}from"@dvmkit/sdk";function isDescriptor(value){return isConfiguredDVMDescriptor(value)}async function loadDescriptor(modulePath){await registerTsxIfNeeded(modulePath);const url2=modulePath.startsWith("file://")?modulePath:pathToFileURL(modulePath).href;const mod2=await import(url2);const preferred=[mod2.default,mod2.dvm];for(const value of preferred){const descriptor=descriptorFromExport(value,modulePath);if(descriptor)return descriptor}for(const value of Object.values(mod2)){const descriptor=descriptorFromExport(value,modulePath);if(descriptor)return descriptor}throw new Error(`No DVMDescriptor found in ${modulePath}. Export a configureDVM() result as default, "dvm", or any named export.`)}function descriptorFromExport(value,modulePath){if(isDescriptor(value))return value;if(!isDescriptorSketch(value))return void 0;const{config:config2,capabilities:_resolvedCapabilities,inputSchema,...topLevel}=value;const normalizedConfig={...topLevel,...inputSchema!==void 0?{input:inputSchema}:{},...config2};if(typeof normalizedConfig.name!=="string"){throw new Error(`Invalid DVM descriptor export in ${modulePath}: missing required "name" field.`)}try{return configureDVM(normalizedConfig)}catch(err){const message2=err instanceof Error?err.message:String(err);throw new Error(`Invalid DVM descriptor export in ${modulePath}: ${message2}`,{cause:err})}}function isDescriptorSketch(value){if(!isRecord(value)||!isRecord(value.config))return false;return"onJob"in value.config||"capabilities"in value.config}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}async function registerTsxIfNeeded(path){if(tsxRegistered||!path.endsWith(".ts"))return;try{const tsx=await import("tsx/esm/api");tsx.register();tsxRegistered=true}catch{}}var tsxRegistered;var init_load_handler=__esm({"src/lib/load-handler.ts"(){"use strict";tsxRegistered=false}});import{readFileSync as readFileSync8}from"fs";import{resolve as resolve6}from"path";function parseDotenv(content){const env2={};for(const line of content.split("\n")){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;const eqIdx=trimmed.indexOf("=");if(eqIdx===-1)continue;const key=trimmed.slice(0,eqIdx).trim();let value=trimmed.slice(eqIdx+1).trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'")){value=value.slice(1,-1)}env2[key]=value}return env2}function loadDevEnvironment(cwd=process.cwd(),parent=process.env){const inherited={};for(const[key,value]of Object.entries(parent)){if(value!==void 0)inherited[key]=value}let project={};try{project=parseDotenv(readFileSync8(resolve6(cwd,".env"),"utf8"))}catch{}return{...inherited,...project}}var init_dev_environment=__esm({"src/lib/dev-environment.ts"(){"use strict"}});var dev_exports={};__export(dev_exports,{DevPaymentTracker:()=>DevPaymentTracker,dev:()=>dev,parseDotenv:()=>parseDotenv,printStartup:()=>printStartup});import{watch}from"fs";import{resolve as resolve8}from"path";import{pathToFileURL as pathToFileURL2}from"url";import{serve}from"@dvmkit/sdk/server";async function dev(handlerPath,opts){const absPath=resolve8(process.cwd(),handlerPath);const env2=loadDevEnvironment();const configuredPort=Object.hasOwn(env2,"PORT")?env2.PORT:void 0;const port=Number(opts.port??configuredPort??"3000");let descriptor=await loadDescriptor(absPath);const payments=new DevPaymentTracker;let server=await startServer(descriptor,port,env2,payments);printStartup(descriptor,port,server.paymentModes);let stopWatching=()=>Promise.resolve();if(opts.reload!==false){let debounce=null;let reload=Promise.resolve();const lifecycle={stopping:false};const isStopping=()=>lifecycle.stopping;const watcher=watch(absPath,()=>{if(isStopping())return;if(debounce)clearTimeout(debounce);debounce=setTimeout(()=>{if(isStopping())return;console.log("\nFile changed, reloading...");const reloadUrl=`${pathToFileURL2(absPath).href}?t=${Date.now()}`;reload=reload.then(async()=>{try{const fresh=await loadDescriptor(reloadUrl);if(isStopping())return;await server.close();if(isStopping())return;descriptor=fresh;server=await startServer(descriptor,port,env2,payments);printStartup(descriptor,port,server.paymentModes)}catch(err){console.error("Reload failed:",err instanceof Error?err.message:String(err));console.log("Watching for changes...")}})},300)});stopWatching=async()=>{lifecycle.stopping=true;if(debounce)clearTimeout(debounce);watcher.close();await reload}}payments.installExitSummary();await blockUntilShutdown(()=>({close:async()=>{await stopWatching();await server.close()}}))}async function startServer(descriptor,port,env2,payments){const mintsRaw="DVMKIT_CASHU_MINTS"in env2?env2.DVMKIT_CASHU_MINTS:void 0;const mints=mintsRaw?mintsRaw.split(",").map(m=>m.trim()):void 0;return serve(descriptor,{port,env:env2,devMode:true,mints,onPaidJobCompleted:event=>{payments.observe(event)}})}function printStartup(descriptor,port,paymentModes){console.log("");console.log(` Dev server running at http://localhost:${port}`);console.log(` Name: ${descriptor.name}`);console.log(` Tags: ${descriptor.tags.join(", ")}`);if(descriptor.price!==void 0)console.log(` Price: ${JSON.stringify(descriptor.price)}`);printPaymentMode(paymentModes);console.log("");console.log(` Test page: http://localhost:${port}/_dev`);console.log("");console.log(` First call:`);console.log(firstCall(descriptor,port,paymentModes));console.log("")}function printPaymentMode(paymentModes){const rails=["cashu","x402","tempo"];const configured=new Set;let verificationRequired=false;let verifierAvailable=false;for(const mode of paymentModes){if(mode.verification==="required")verificationRequired=true;for(const[rail,state]of Object.entries(mode.rails)){if(state.status!=="absent")configured.add(rail);if(mode.verification==="required"&&state.status==="verifying"){verifierAvailable=true}}}for(const rail of rails){const states=paymentModes.map(mode=>mode.rails[rail]);const state=states.find(candidate=>candidate.status!=="absent")??states[0];if(state.status==="absent"){console.log(` ${rail}: absent (not configured)`)}else{const funds=state.testFunds===true?"test funds":state.testFunds===false?"live funds":"fund type unknown";console.log(` ${rail}: ${state.status} (${funds})`)}}if(configured.size===0){console.log(" Payments: skipped; no payment rail is configured");console.log(" Enable Cashu with DVMKIT_CASHU_MINTS, x402 with DVMKIT_X402_PAY_TO, or Tempo with DVMKIT_TEMPO_RECIPIENT.");console.log(" dev_auto: /_dev may approve synthetic payments; CLI calls are free in this mode.");return}if(verificationRequired&&!verifierAvailable){console.log(" Payments: required but unavailable; paid CLI calls fail closed")}else{console.log(` Payments: ${verificationRequired?"real verification":"skipped"}`)}console.log(" dev_auto: applies only to /_dev; caller CLI payments use the configured verifier.")}function firstCall(descriptor,port,paymentModes){const capabilities=Object.entries(descriptor.capabilities);if(capabilities.length!==1){const names=capabilities.map(([name])=>name).join(", ");const first=capabilities[0]?.[0]??"<capability>";return` Local endpoint calls cannot select among ${names||"multiple capabilities"}. Use /_dev, or after deployment run dvm request -d <handle>--<slug>/${first} --data <json>.`}const capability=capabilities[0][1];const data=capability.example??"hello";const rail=effectiveRail(paymentModes);if(paymentModes.some(mode=>mode.verification==="required")&&!rail){return" No paid caller command is available until a configured payment verifier recovers."}const cap=typeof capability.price==="string"?capability.price:void 0;const payment=rail&&cap?` --rail ${rail} --budget ${shellQuote2(cap)} --auto-pay-below ${shellQuote2(cap)} --max-increment ${shellQuote2(cap)} --max-payments 1`:"";return` dvm request --endpoint http://localhost:${port} --data ${shellQuote2(JSON.stringify(data))}${payment} </dev/null`}function effectiveRail(paymentModes){for(const rail of["cashu","tempo","x402"]){if(paymentModes.some(mode=>mode.rails[rail].status==="verifying"))return rail}return void 0}function shellQuote2(value){return`'${value.replaceAll("'",`'\\''`)}'`}function formatMoney(amountMicro,currency){const amount2=(amountMicro/1e6).toFixed(6).replace(/\.?0+$/,"");return currency.toLowerCase()==="usd"?`$${amount2} USD`:`${amount2} ${currency.toUpperCase()}`}var DevPaymentTracker;var init_dev=__esm({"src/commands/dev.ts"(){"use strict";init_dev_environment();init_keep_alive();init_load_handler();init_dev_environment();DevPaymentTracker=class{jobs=new Set;totals=new Map;observe(event){if(this.jobs.has(event.jobId))return;this.jobs.add(event.jobId);const classification=event.testFunds===true?"test":event.testFunds===false?"live":"unknown";const key=`${event.currency}:${classification}`;const prior=this.totals.get(key);this.totals.set(key,{amountMicro:(prior?.amountMicro??0)+event.amountMicro,currency:event.currency,testFunds:event.testFunds});const funds=event.testFunds===true?" test funds":event.testFunds===false?" live funds":" funds not classified";console.log(` Paid job ${event.jobId}: ${formatMoney(event.amountMicro,event.currency)} via ${event.rail}${funds}`);console.log(` Session total (${this.jobs.size} job${this.jobs.size===1?"":"s"}): ${this.totalDisplay()}`)}printSummary(){if(this.jobs.size===0){console.log(" Session total: no paid jobs.");return}console.log(` Session total (${this.jobs.size} paid job${this.jobs.size===1?"":"s"}): ${this.totalDisplay()}`)}installExitSummary(){const print=()=>{this.printSummary()};process.once("SIGINT",print);process.once("SIGTERM",print)}totalDisplay(){return[...this.totals.values()].map(({amountMicro,currency,testFunds})=>{const classification=testFunds===true?"test funds":testFunds===false?"live funds":"funds not classified";return`${formatMoney(amountMicro,currency)} ${classification}`}).join(" + ")}}}});var serve_exports={};__export(serve_exports,{assertProductionDatabase:()=>assertProductionDatabase,attestationEnvOccupied:()=>attestationEnvOccupied,buildServeOpts:()=>buildServeOpts,builderServe:()=>builderServe});import{resolve as resolve9}from"path";import{DvmError as DvmError37,loadIdentitySecret as loadIdentitySecret3}from"@dvmkit/sdk/internal";import{serve as sdkServe}from"@dvmkit/sdk/server";async function builderServe(handlerPath,opts){const absPath=resolve9(process.cwd(),handlerPath);const descriptor=await loadDescriptor(absPath);const identity=opts.dvm?resolveBuilderLockIdentity(opts.dvm):void 0;const attestation=opts.dvm?resolveServeAttestation(process.cwd(),opts.dvm,identity?.canonicalDvmId,process.env):void 0;const serveOpts=buildServeOpts(process.env,opts,identity,attestation);assertProductionDatabase(serveOpts);const{url:url2,close}=await sdkServe(descriptor,serveOpts);console.log(`Serving ${descriptor.name} at ${url2}`);if(identity){console.log(` lock identity: ${identity.handle} (rotation ${identity.rotationIndex})`);console.log(` lock pubkey: ${identity.lockPubkey}`)}if(attestation){console.log(` attested dvm id: ${attestation.payload.dvm_id}`);console.log(` attested slug: ${attestation.payload.slug}`);console.log(` receipt key: ${attestation.payload.receipt_pubkey??"(none)"}`)}else if(opts.dvm){console.log(" receipts: unattested (see the note above)")}await blockUntilShutdown(()=>({close}))}function assertProductionDatabase(opts){if(opts.database)return;throw new DvmError37("production_database_required","Production serving requires a Postgres database.","Set DATABASE_URL to a Postgres connection string, or use `dvmctl dev` for local development.")}function buildServeOpts(env2,opts,identity,attestation){const result={};const port=opts?.port??env2.PORT;if(port)result.port=Number(port);if(env2.DATABASE_URL)result.database=env2.DATABASE_URL;const mintsRaw=env2.DVMKIT_CASHU_MINTS;if(mintsRaw){result.mints=mintsRaw.split(",").map(m=>m.trim())}let serveEnv=env2;if(identity)serveEnv=withLockIdentity(serveEnv,identity);if(attestation)serveEnv={...serveEnv,...attestationEnv(attestation)};result.env=serveEnv;return result}function attestationEnvOccupied(env2){return ATTESTATION_ENV_KEYS.filter(key=>env2[key])}function resolveServeAttestation(cwd,handle2,dvmId,env2){const occupied=attestationEnvOccupied(env2);if(occupied.length>0){console.log(` note: ${occupied.join(", ")} already set \u2014 serving the environment's attestation, not deriving one for --dvm ${handle2}.`);return void 0}const secret=loadIdentitySecret3();const pubkey=loadIdentityPubkey();if(!secret||!pubkey){console.log(` note: no builder identity on disk, so this DVM's receipts will be unattested. Run 'dvmctl identity create' to have --dvm ${handle2} derive and attest a receipt key.`);return void 0}if(!dvmId){throw new DvmError37("durable_dvm_identity_required",`No durable DVM ID is recorded for "${handle2}".`,"Run `dvmctl init <handle> --self-hosted` before serving receipts, then retry.")}return signDeployAttestation({builderSecret:secret,builderPubkey:pubkey,dvmId,slug:handle2,capabilities:readCapabilitiesForAttestation(cwd),withReceiptKey:true})}function withLockIdentity(env2,identity){assertNoConflict(env2,"DVMKIT_CASHU_LOCK_PUBKEY",identity.lockPubkey,identity);assertNoConflict(env2,"DVMKIT_DVM_ID",identity.canonicalDvmId,identity);assertNoConflict(env2,"DVMKIT_CANONICAL_DVM_ID",identity.canonicalDvmId,identity);return{...env2,DVMKIT_CASHU_LOCK_PUBKEY:identity.lockPubkey,DVMKIT_DVM_ID:identity.canonicalDvmId,DVMKIT_CANONICAL_DVM_ID:identity.canonicalDvmId}}function assertNoConflict(env2,key,derived,identity){const existing=env2[key];if(!existing||existing.toLowerCase()===derived.toLowerCase())return;throw new DvmError37("lock_identity_conflict",`${key} is set to "${existing}", but --dvm ${identity.handle} derives "${derived}".`,`Unset ${key} to serve under the builder-store identity, or drop --dvm to serve under the environment's.`)}var init_serve=__esm({"src/commands/builder/serve.ts"(){"use strict";init_builder_lock_identity();init_deploy_attestation();init_keep_alive();init_load_handler();init_builder_store()}});import{realpathSync as realpathSync2}from"fs";import{fileURLToPath as fileURLToPath2}from"url";import{randomTraceId}from"@dvmkit/sdk/internal";var import_index=__toESM(require_commander(),1);var{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{homedir}from"os";import{join}from"path";import{DvmError}from"@dvmkit/sdk/internal";function requireAuth(){const creds=resolveAuth();if(!creds){throw new DvmError("auth_required","Not authenticated.","Set DVMKIT_API_KEY or run `dvmctl auth`.")}return{token:creds.token,platformUrl:process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev"}}function resolveAuth(){const envKey=process.env.DVMKIT_API_KEY;if(envKey){return{token:envKey,account:"api-key"}}return loadAuthToken()}function saveAuthToken(creds){const dir=dvmctlConfigDir();mkdirSync(dir,{recursive:true,mode:448});const configPath=join(dir,"config.json");let config2={};if(existsSync(configPath)){try{config2=JSON.parse(readFileSync(configPath,"utf-8"))}catch{}}config2.auth=creds;writeFileSync(configPath,JSON.stringify(config2,null,2)+"\n",{encoding:"utf-8",mode:384})}function loadAuthToken(){const configPath=join(dvmctlConfigDir(),"config.json");if(!existsSync(configPath))return null;try{const config2=JSON.parse(readFileSync(configPath,"utf-8"));const auth2=config2.auth;if(auth2?.token&&auth2.account)return auth2}catch{}return null}function clearAuthToken(){const configPath=join(dvmctlConfigDir(),"config.json");if(!existsSync(configPath))return;try{const config2=JSON.parse(readFileSync(configPath,"utf-8"));delete config2.auth;writeFileSync(configPath,JSON.stringify(config2,null,2)+"\n","utf-8")}catch{}}function resolveOrgScope(opts={}){return opts.org??loadActiveOrg()??void 0}function loadActiveOrg(){const configPath=join(dvmctlConfigDir(),"config.json");if(!existsSync(configPath))return null;try{const config2=JSON.parse(readFileSync(configPath,"utf-8"));const context=config2.context;return context?.activeOrg??null}catch{return null}}function saveActiveOrg(handle2){const dir=dvmctlConfigDir();mkdirSync(dir,{recursive:true,mode:448});const configPath=join(dir,"config.json");let config2={};if(existsSync(configPath)){try{config2=JSON.parse(readFileSync(configPath,"utf-8"))}catch{}}const existingContext=typeof config2.context==="object"&&config2.context!=null?config2.context:{};config2.context={...existingContext,activeOrg:handle2};writeFileSync(configPath,JSON.stringify(config2,null,2)+"\n",{encoding:"utf-8",mode:384})}function clearActiveOrg(){const configPath=join(dvmctlConfigDir(),"config.json");if(!existsSync(configPath))return;try{const config2=JSON.parse(readFileSync(configPath,"utf-8"));if(typeof config2.context==="object"&&config2.context!=null){const context=config2.context;delete context.activeOrg;if(Object.keys(context).length===0)delete config2.context}writeFileSync(configPath,JSON.stringify(config2,null,2)+"\n","utf-8")}catch{}}function dvmctlConfigDir(){return process.env.DVMCTL_CONFIG_DIR??join(homedir(),".dvmctl")}init_output();init_traceparent();init_http();import{DvmError as DvmError2,isAbortError,providerProseSources,transportErrorCode}from"@dvmkit/sdk/internal";async function platformFetch(input,init2){const method=(init2?.method??(input instanceof Request?input.method:"GET")).toUpperCase();const attempts=method==="GET"||method==="HEAD"?3:1;let lastError;for(let attempt=1;attempt<=attempts;attempt++){try{const res=await dvmFetch(input,init2);const tp=res.headers.get("traceparent");if(tp){const parsed=parseTraceparent(tp);if(parsed)setOutputTraceId(parsed.traceId)}return res}catch(err){if(isAbortError(err)||err instanceof DvmError2)throw err;lastError=err;if(attempt<attempts)await new Promise(resolve10=>setTimeout(resolve10,100*attempt))}}const cause=transportErrorCode(lastError);throw new DvmError2("platform_unreachable",`Could not reach the dvmkit platform after ${attempts} attempt${attempts===1?"":"s"}${cause?` (${cause})`:""}.`,"Check the network connection and retry. No server response was received.",{attempts,method,...cause?{transport_code:cause}:{}})}async function orgScopedError(res,fallbackCode,what,org){const body=await res.json().catch(()=>({}));const scope=org?`org "${org}"`:"your personal context";let hint=body.error?.hint;if(!hint&&org&&res.status===404&&body.error?.code==="not_found"){hint=`No org "${org}" you can see. Check the handle, or ask an admin to invite you.`}if(!hint&&res.status===403){hint=`Your role in ${scope} is too low for this data. Ask an org admin.`}return platformResponseError(body.error?.code??fallbackCode,body.error,`${what} for ${scope}: ${res.status}`,{hint})}function platformResponseError(code,remote,fallbackMessage,local={}){const data=remote?.data||local.data?{...remote?.data??{},...local.data??{}}:void 0;return new DvmError2(code,remote?.message??fallbackMessage,remote?.hint??local.hint,data,remote?.display??local.display,providerProseSources(remote,remote?.data))}async function setHandle(platformUrl,token,handle2){const res=await platformFetch(`${platformUrl}/api/v1/builder/handle`,{method:"PUT",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({handle:handle2})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"handle_failed",body.error,`Failed to set handle: ${res.status}`)}}async function checkHandle(platformUrl,handle2){const res=await platformFetch(`${platformUrl}/api/v1/handle/check/${encodeURIComponent(handle2)}`);return await res.json()}async function addDomain(platformUrl,token,dvmId,domain2){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/domains`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({domain:domain2})});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"domain_failed",body2.error,`Failed to add domain: ${res.status}`)}const body=await res.json().catch(()=>({}));return{hint:body.hint}}async function removeDomain(platformUrl,token,dvmId,domain2){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/domains/${encodeURIComponent(domain2)}`,{method:"DELETE",headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"domain_failed",body.error,`Failed to remove domain: ${res.status}`)}}async function verifyDomain(platformUrl,token,dvmId,domain2){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/domains/${encodeURIComponent(domain2)}/verify`,{method:"POST",headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"verify_failed",body.error,`Failed to verify domain: ${res.status}`)}}async function listDomains(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/domains`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw new DvmError2("domain_failed",`Failed to list domains: ${res.status}`)}const body=await res.json();return body.domains}function scopeLabel(org){return org.personal?"personal":org.handle??org.id}async function listDvms(platformUrl,token,opts={}){const url2=new URL(`${platformUrl}/api/v1/builder/dvms`);if(opts.org)url2.searchParams.set("org",opts.org);const res=await platformFetch(url2,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"list_failed","Failed to list DVMs",opts.org)}return await res.json()}async function getDvm(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"info_failed",body.error,`Failed to get DVM: ${res.status}`)}return await res.json()}async function destroyDvm(platformUrl,token,dvmId,opts){const url2=new URL(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}`);if(opts?.keepDb)url2.searchParams.set("keep_db","true");const res=await platformFetch(url2,{method:"DELETE",headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"destroy_failed",body.error,`Failed to destroy DVM: ${res.status}`)}}async function listBuilderFeedback(platformUrl,token,opts={}){const url2=new URL(`${platformUrl}/api/v1/builder/feedback`);if(opts.dvmId)url2.searchParams.set("dvm_id",opts.dvmId);if(opts.sinceMs!==void 0)url2.searchParams.set("since",String(opts.sinceMs));if(opts.cursor)url2.searchParams.set("cursor",opts.cursor);if(opts.limit!==void 0)url2.searchParams.set("limit",String(opts.limit));if(opts.org)url2.searchParams.set("org",opts.org);const res=await platformFetch(url2,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"feedback_list_failed","Failed to list feedback",opts.org)}return await res.json()}async function updateDvmSettings(platformUrl,token,dvmId,settings){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/settings`,{method:"PATCH",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(settings)});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"settings_update_failed",body.error,`Failed to update DVM settings: ${res.status}`)}return await res.json()}async function getAuthenticatedBuilderProfile(platformUrl,token){const res=await platformFetch(`${platformUrl}/api/v1/builder/me`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"builder_profile_failed",body.error,`Failed to read builder profile: ${res.status}`)}const data=await res.json();return data.builder}async function listBuilderOrgs(platformUrl,token){const res=await platformFetch(`${platformUrl}/api/v1/builder/orgs`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"org_list_failed",body.error,`Failed to list org memberships: ${res.status}`)}const data=await res.json();return data.orgs}async function getOrgMembership(platformUrl,token,handle2){const res=await platformFetch(`${platformUrl}/api/v1/builder/orgs/${encodeURIComponent(handle2)}`,{headers:{Authorization:`Bearer ${token}`}});if(res.status===404){throw new DvmError2("org_not_found",`Org "${handle2}" not found, or you are not a member.`,"Check the handle, or ask an admin to invite you.")}if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"org_lookup_failed",body.error,`Failed to look up org: ${res.status}`)}const data=await res.json();return{handle:data.org.handle,displayName:data.org.displayName,role:data.role}}async function setDvmLockPubkey(platformUrl,token,dvmId,pubkey){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/lock-pubkey`,{method:"PUT",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({pubkey})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError("platform_error",body.error,"Failed to register per-DVM lock pubkey.",{hint:"Ensure the pubkey is a valid 33-byte compressed secp256k1 key (66 hex chars)."})}}async function rotateDvmLockPubkey(platformUrl,token,dvmId,newPubkey){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/rotate-lock-pubkey`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({new_pubkey:newPubkey})});if(!res.ok){const body=await res.json().catch(()=>({}));const code=body.error?.code??"platform_error";throw platformResponseError(code,body.error,`Failed to rotate per-DVM lock pubkey (HTTP ${res.status}).`,{hint:code==="no_op_rotation"?void 0:"Ensure the pubkey is a valid compressed secp256k1 key and the DVM is isolate-tier."})}return await res.json()}async function validateAuth(platformUrl,token){const res=await platformFetch(`${platformUrl}/api/v1/builder/auth/me`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw new DvmError2("auth_failed","Invalid API key.","Check your DVMKIT_API_KEY or run `dvmctl auth`.")}}async function startDeploy(platformUrl,token,opts){const form=new FormData;if(opts.tarball){form.append("tarball",new Blob([new Uint8Array(opts.tarball)]),"project.tar.gz")}form.append("metadata",JSON.stringify({slug:opts.slug,name:opts.name,env:opts.env,runtime:opts.runtime,commit:opts.commit,vmConfig:opts.vmConfig,inheritSecrets:opts.inheritSecrets,features:opts.features,endpointUrl:opts.endpointUrl,dockerfilePath:opts.dockerfilePath,orgHandle:opts.orgHandle,lockPubkey:opts.lockPubkey,expectLockPubkey:opts.expectLockPubkey,expectIdentityFinalization:opts.expectIdentityFinalization,identityPubkey:opts.identityPubkey,attestationPayload:opts.attestationPayload,attestationSignature:opts.attestationSignature,capabilities:opts.capabilities}));const res=await platformFetch(`${platformUrl}/api/v1/builder/deploy`,{method:"POST",headers:{Authorization:`Bearer ${token}`},body:form});if(!res.ok){const body2=await res.json().catch(()=>({}));const code=body2.error?.code??"deploy_failed";throw platformResponseError(code,body2.error,`Deploy failed with status ${res.status}`)}const body=await res.json();if(typeof body.deployId!=="string"||typeof body.dvmId!=="string"||typeof body.slug!=="string"){throw new DvmError2("platform_response_invalid","Platform deploy response is missing required fields (deployId, dvmId, or slug).","Your platform may be outdated. Update it with: fly deploy --config fly.platform.toml")}return body}async function finalizeDvmDeployIdentity(platformUrl,token,dvmId,opts){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/deploy-identity`,{method:"PUT",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(opts)});if(res.ok)return;const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"deploy_identity_finalize_failed",body.error,`Identity finalization failed with status ${res.status}`)}async function deployLocal(platformUrl,token,opts){const res=await platformFetch(`${platformUrl}/api/v1/builder/deploy/local`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({slug:opts.slug,name:opts.name,url:opts.url,runtime:opts.runtime,identityPubkey:opts.identityPubkey,attestationPayload:opts.attestationPayload,attestationSignature:opts.attestationSignature,capabilities:opts.capabilities,orgHandle:opts.orgHandle})});if(!res.ok){const body=await res.json().catch(()=>({}));const code=body.error?.code??"local_deploy_failed";throw platformResponseError(code,body.error,`Local deploy failed with status ${res.status}`,{hint:code==="local_deploy_disabled"?"Start the local stack with `npm run dev:stack` (it sets DVMKIT_ALLOW_LOCAL_DEPLOY=true).":void 0})}return await res.json()}var DEPLOY_POLL_INTERVAL_MS=15e3;async function getDeployStatus(platformUrl,token,deployId){const res=await platformFetch(`${platformUrl}/api/v1/builder/deploys/${encodeURIComponent(deployId)}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"deploy_status_failed",body.error,`Failed to get deploy status: ${res.status}`)}return await res.json()}async function streamDeployLogs(platformUrl,token,deployId,opts){const pollIntervalMs=opts.pollIntervalMs??DEPLOY_POLL_INTERVAL_MS;const recoveryTimeoutMs=opts.recoveryTimeoutMs??75e3;const startTime=Date.now();const abortController=new AbortController;let acceptedRelease;let lastTransportError;let recoveryTimer;let streamLost=false;const state={settled:false};const isSettled=()=>state.settled;let resolveOuter;let rejectOuter;const outerPromise=new Promise((res,rej)=>{resolveOuter=res;rejectOuter=rej});const resolve10=result=>{if(isSettled())return;state.settled=true;abortController.abort();resolveOuter(result)};const reject=err=>{if(isSettled())return;state.settled=true;abortController.abort();rejectOuter(err)};const pollerInterval=setInterval(()=>{if(isSettled())return;void getDeployStatus(platformUrl,token,deployId).then(({deploy:deploy2,dvm,recovery})=>{if(isSettled())return;opts.onPhase?.({status:deploy2.status,elapsedMs:Date.now()-startTime});if(deploy2.status==="deployed"){resolve10({url:dvm.url??"",status:acceptedRelease&&streamLost?"deployed_unverified":"deployed",dvmkitUrl:dvm.dvmkitUrl??null})}else if(deploy2.status==="failed"||deploy2.status==="superseded"){const providerMessage=deploy2.error??void 0;const healthFailure=deploy2.releaseAcceptedAt!=null;reject(new DvmError2(deploy2.status==="superseded"?"deploy_superseded":healthFailure?"deploy_health_verification_failed":"deploy_failed",providerMessage??(deploy2.status==="superseded"?"Deploy was superseded by a recovery rollout.":"Deploy failed"),void 0,healthFailure?{release_accepted:true,rollback:recovery?{attempted:true,status:recovery.status,deploy_id:recovery.deployId,target_deploy_id:recovery.targetDeployId,error:recovery.error}:{attempted:false,status:"not_available"}}:void 0,void 0,providerMessage?{message:"provider"}:void 0))}},err=>{lastTransportError=err})},pollIntervalMs);void(async()=>{try{const streamOnce=async()=>{try{return await streamDeployLogsOnce(platformUrl,token,deployId,opts.onLog,release=>{acceptedRelease=release;opts.onAccepted?.(release)},abortController.signal)}catch(err){if(isAbortError(err))throw err;if(!isDeployStreamTransportError(err))throw err;lastTransportError=err;streamLost=true;return{kind:"dropped"}}};const first=await streamOnce();if(isSettled())return;if(first.kind==="result"){resolve10(first.result);return}if(first.kind==="error"){reject(acceptedRelease?deployAcceptedReleaseError(deployId,acceptedRelease,first.error):first.error);return}streamLost=true;await new Promise(r=>setTimeout(r,opts.streamRetryDelayMs??1500));if(isSettled())return;const second=await streamOnce();if(isSettled())return;if(second.kind==="result"){resolve10(second.result);return}if(second.kind==="error"){reject(acceptedRelease?deployAcceptedReleaseError(deployId,acceptedRelease,second.error):second.error);return}recoveryTimer=setTimeout(()=>{reject(deployRecoveryError(deployId,acceptedRelease,lastTransportError))},recoveryTimeoutMs);recoveryTimer.unref()}catch(err){if(err?.name==="AbortError")return;reject(err)}})();try{return await outerPromise}finally{clearInterval(pollerInterval);if(recoveryTimer)clearTimeout(recoveryTimer);abortController.abort()}}async function streamDeployLogsOnce(platformUrl,token,deployId,onLog,onAccepted,signal){const url2=`${platformUrl}/api/v1/builder/deploys/${deployId}/logs`;const res=await platformFetch(url2,{headers:{Authorization:`Bearer ${token}`,Accept:"text/event-stream"},signal});if(!res.ok){return{kind:"error",error:new DvmError2("deploy_stream_failed",`Failed to stream deploy logs: ${res.status}`)}}const reader=res.body?.getReader();if(!reader){return{kind:"error",error:new DvmError2("deploy_stream_failed","No response body")}}const decoder3=new TextDecoder;let buffer="";let chunk=await reader.read();while(!chunk.done){const{value}=chunk;buffer+=decoder3.decode(value,{stream:true});const lines=buffer.split("\n");buffer=lines.pop()??"";let currentEvent="";const dataLines=[];for(const line of lines){if(line.startsWith("event: ")){currentEvent=line.slice(7)}else if(line.startsWith("data: ")){dataLines.push(line.slice(6))}else if(line===""&¤tEvent){const currentData=dataLines.join("\n");dataLines.length=0;if(currentEvent==="log"){onLog(currentData)}else if(currentEvent==="accepted"){try{const release=JSON.parse(currentData);if(typeof release.deployId!=="string"||typeof release.url!=="string"||release.commitSha!==null&&typeof release.commitSha!=="string"){throw new Error("invalid accepted-release payload")}onAccepted(release)}catch{return{kind:"error",error:new DvmError2("deploy_stream_failed","Platform returned a malformed accepted-release event.")}}}else if(currentEvent==="complete"){try{return{kind:"result",result:JSON.parse(currentData)}}catch{return{kind:"error",error:new DvmError2("deploy_failed",`Malformed deploy result: ${currentData}`,void 0,void 0,void 0,{message:"provider"})}}}else if(currentEvent==="error"){try{const err=JSON.parse(currentData);return{kind:"error",error:new DvmError2(err.code??"deploy_failed",err.message,void 0,err.releaseAccepted?{release_accepted:true,rollback:err.rollback}:void 0,void 0,{message:"provider"})}}catch{return{kind:"error",error:new DvmError2("deploy_failed",currentData,void 0,void 0,void 0,{message:"provider"})}}}currentEvent=""}}chunk=await reader.read()}return{kind:"dropped"}}function isDeployStreamTransportError(err){return err instanceof DvmError2&&err.code==="platform_unreachable"||err instanceof TypeError||transportErrorCode(err)!==void 0}function deployRecoveryError(deployId,release,transportError){const transportCode=transportError instanceof DvmError2?typeof transportError.data?.transport_code==="string"?transportError.data.transport_code:void 0:transportErrorCode(transportError);if(!release){return new DvmError2("deploy_status_unknown",`Deploy ${deployId} is still running or its final status could not be read.`,`Run \`dvmctl deploy-status ${deployId}\` to recover the authoritative result.`,{deploy_id:deployId,...transportCode?{transport_code:transportCode}:{}})}const verificationUrl=`${release.url.replace(/\/$/,"")}/healthz`;const shaCheck=release.commitSha?`confirm \`gitSha\` is \`${release.commitSha}\``:"read the served `gitSha`";return new DvmError2("deploy_release_accepted_status_unknown",`Fly accepted deploy ${deployId}, but dvmctl could not confirm its final platform status.`,`Run \`curl -s ${verificationUrl}\` and ${shaCheck}; then run \`dvmctl deploy-status ${deployId}\` to recover the platform result.`,{outcome:"partial_success",deploy_id:deployId,release_url:release.url,verification_url:verificationUrl,...release.commitSha?{expected_git_sha:release.commitSha}:{},...transportCode?{transport_code:transportCode}:{}},`Fly accepted deploy ${deployId}; only the final metadata/status confirmation was interrupted.`)}function deployAcceptedReleaseError(deployId,release,terminalError){const verificationUrl=`${release.url.replace(/\/$/,"")}/healthz`;const shaCheck=release.commitSha?`confirm \`gitSha\` is \`${release.commitSha}\``:"read the served `gitSha`";const providerMessage=terminalError.proseSources?.message==="provider";if(terminalError.code==="deploy_health_verification_failed"){return new DvmError2(terminalError.code,terminalError.message,"Inspect the rollback outcome, then fix the candidate process and deploy again.",{outcome:"failed",deploy_id:deployId,release_accepted:true,release_url:release.url,...release.commitSha?{expected_git_sha:release.commitSha}:{},...terminalError.data},`Fly accepted deploy ${deployId}, but the candidate application did not become healthy.`,providerMessage?{message:"provider"}:void 0)}return new DvmError2("deploy_release_accepted_epilogue_failed",`Fly accepted deploy ${deployId}, then the platform reported: ${terminalError.message}`,`Run \`curl -s ${verificationUrl}\` and ${shaCheck}; then run \`dvmctl deploy-status ${deployId}\` to recover the authoritative platform result.`,{outcome:"partial_success",deploy_id:deployId,release_url:release.url,verification_url:verificationUrl,...release.commitSha?{expected_git_sha:release.commitSha}:{},terminal_error_code:terminalError.code,terminal_error:providerMessage?{_source:"provider",text:terminalError.message}:terminalError.message},`Fly accepted deploy ${deployId}, but its post-release finalization reported an error.`,providerMessage?{message:"provider"}:void 0)}async function getMetrics(platformUrl,token,dvmId,hours2){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/metrics?hours=${hours2}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"metrics_failed",body2.error,`Failed to get metrics: ${res.status}`)}const body=await res.json();return body.metrics}async function getEvents(platformUrl,token,dvmId,opts={}){const params=new URLSearchParams;if(opts.since)params.set("since",opts.since);const qs=params.toString()?`?${params.toString()}`:"";const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/events${qs}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"events_failed",body.error,`Failed to get events: ${res.status}`)}return await res.json()}async function getEnv(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/env`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"env_failed",body2.error,`Failed to get env: ${res.status}`)}const body=await res.json();return body.env}async function listSecrets(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/secrets`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"secrets_failed",body2.error,`Failed to list secrets: ${res.status}`)}const body=await res.json();return body.secrets}async function setEnv(platformUrl,token,dvmId,changes){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/env`,{method:"PUT",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(changes)});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"env_failed",body.error,`Failed to update env: ${res.status}`)}}async function getLogs(platformUrl,token,dvmId,opts={}){const params=new URLSearchParams({stream:"false"});if(opts.lines!=null)params.set("lines",String(opts.lines));if(opts.since)params.set("since",opts.since);const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/logs?${params.toString()}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"logs_failed",body2.error,`Failed to get logs: ${res.status}`)}const body=await res.json();return body.logs}async function execCommand(platformUrl,token,dvmId,command,opts={}){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/exec`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({command,...opts.machine?{machine:opts.machine}:{}})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"ssh_failed",body.error,`SSH command failed: ${res.status}`)}return await res.json()}async function restartMachines(platformUrl,token,dvmId,opts={}){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/restart`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(opts.machine?{machine:opts.machine}:{})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"restart_failed",body.error,`Restart failed: ${res.status}`)}return await res.json()}async function pauseDvm(platformUrl,token,dvmId){return pauseCall(platformUrl,token,dvmId,"pause")}async function resumeDvm(platformUrl,token,dvmId){return pauseCall(platformUrl,token,dvmId,"resume")}async function pauseCall(platformUrl,token,dvmId,verb){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/${verb}`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:"{}"});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??`${verb}_failed`,body.error,`${verb==="pause"?"Pause":"Resume"} failed: ${res.status}`)}return await res.json()}async function scaleDvm(platformUrl,token,dvmId,opts){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/scale`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({...opts.count!==void 0?{count:opts.count}:{},...opts.size!==void 0?{size:opts.size}:{}})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"scale_failed",body.error,`Scale failed: ${res.status}`)}return await res.json()}async function rollbackDvm(platformUrl,token,dvmId,opts={}){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/rollback`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(opts.to?{to:opts.to}:{})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"rollback_failed",body.error,`Rollback failed: ${res.status}`)}return await res.json()}async function getMachineStatus(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/status`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"status_failed",body.error,`Status failed: ${res.status}`)}return await res.json()}function buildSshWsUrl(platformUrl,dvmId,machine){const wsBase=platformUrl.replace(/^http(s?):\/\//,(_m,s)=>`ws${s}://`).replace(/\/+$/,"");const query=machine?`?machine=${encodeURIComponent(machine)}`:"";return`${wsBase}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/ssh${query}`}async function openSshSession(platformUrl,token,dvmId,opts={}){if(!process.stdin.isTTY||!process.stdout.isTTY){throw new DvmError2("not_a_tty","An interactive shell requires a terminal.",'Run `dvmctl ssh <slug>` from an interactive terminal, or pass --command "..." for a one-shot command.')}const{default:WebSocket3}=await Promise.resolve().then(()=>(init_wrapper(),wrapper_exports));const url2=buildSshWsUrl(platformUrl,dvmId,opts.machine);return new Promise((resolve10,reject)=>{const ws=new WebSocket3(url2,{headers:{Authorization:`Bearer ${token}`}});const stdin=process.stdin;let exitCode=0;let settled=false;const onStdin=chunk=>{if(ws.readyState===WebSocket3.OPEN)ws.send(chunk)};const finish=done=>{if(settled)return;settled=true;stdin.removeListener("data",onStdin);if(stdin.isTTY)stdin.setRawMode(false);stdin.pause();done()};ws.on("unexpected-response",(_req,res)=>{const chunks=[];res.on("data",d=>chunks.push(d));res.on("end",()=>{let code="ssh_failed";let message2=`Failed to open shell: ${res.statusCode}`;let hint;let remote;try{const body=JSON.parse(Buffer.concat(chunks).toString());if(body.error?.code)code=body.error.code;if(body.error?.message)message2=body.error.message;hint=body.error?.hint;remote=body.error}catch{}finish(()=>{reject(platformResponseError(code,remote,message2,{hint}))})})});ws.on("open",()=>{if(stdin.isTTY)stdin.setRawMode(true);stdin.resume();stdin.on("data",onStdin)});ws.on("message",(data,isBinary)=>{const buf=Buffer.isBuffer(data)?data:Array.isArray(data)?Buffer.concat(data):Buffer.from(data);if(isBinary){process.stdout.write(buf);return}try{const msg=JSON.parse(buf.toString());if(msg.type==="exit"){exitCode=msg.code??0}else if(msg.type==="error"){finish(()=>{reject(new DvmError2("ssh_failed",msg.message??"Remote shell error",void 0,void 0,void 0,msg.message?{message:"provider"}:void 0))})}}catch{process.stdout.write(buf)}});ws.on("close",()=>{finish(()=>{resolve10(exitCode)})});ws.on("error",err=>{finish(()=>{reject(new DvmError2("ssh_failed",err.message))})})})}async function streamLogs(platformUrl,token,dvmId,opts,onLine){const params=new URLSearchParams({stream:"true"});if(opts.since)params.set("since",opts.since);const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/logs?${params.toString()}`,{headers:{Authorization:`Bearer ${token}`,Accept:"text/event-stream"}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"logs_failed",body.error,`Failed to stream logs: ${res.status}`)}const reader=res.body?.getReader();if(!reader){throw new DvmError2("logs_failed","No response body")}const decoder3=new TextDecoder;let buffer="";const readLoop=async()=>{let chunk=await reader.read();while(!chunk.done){buffer+=decoder3.decode(chunk.value,{stream:true});const lines=buffer.split("\n");buffer=lines.pop()??"";let currentEvent="";for(const line of lines){if(line.startsWith("event: ")){currentEvent=line.slice(7)}else if(line.startsWith("data: ")&¤tEvent==="log"){onLine(line.slice(6))}else if(line===""){currentEvent=""}}chunk=await reader.read()}};readLoop().catch(()=>{});return{stop:()=>{void reader.cancel()}}}async function transferDvm(platformUrl,token,dvmId,body){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/transfer`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(body)});if(!res.ok){const data=await res.json().catch(()=>({}));throw platformResponseError(data.error?.code??"transfer_failed",data.error,`Transfer failed: ${res.status}`)}return await res.json()}async function getRevenueSeries(platformUrl,token,opts){const params=new URLSearchParams({from:opts.from,to:opts.to});if(opts.currency)params.set("currency",opts.currency);if(opts.rail)params.set("rail",opts.rail);if(opts.org)params.set("org",opts.org);const res=await platformFetch(`${platformUrl}/api/v1/builder/revenue/series?${params.toString()}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"revenue_series_failed","Failed to get revenue",opts.org)}return await res.json()}async function getRevenueEvents(platformUrl,token,opts={}){const params=new URLSearchParams;if(opts.from)params.set("from",opts.from);if(opts.to)params.set("to",opts.to);if(opts.currency)params.set("currency",opts.currency);if(opts.rail)params.set("rail",opts.rail);if(opts.limit!==void 0)params.set("limit",String(opts.limit));if(opts.offset!==void 0)params.set("offset",String(opts.offset));if(opts.org)params.set("org",opts.org);const qs=params.toString()?`?${params.toString()}`:"";const res=await platformFetch(`${platformUrl}/api/v1/builder/revenue/events${qs}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"revenue_events_failed","Failed to get revenue events",opts.org)}return await res.json()}async function getRevenueCsv(platformUrl,token,opts){const params=new URLSearchParams({from:opts.from,to:opts.to});if(opts.currency)params.set("currency",opts.currency);if(opts.rail)params.set("rail",opts.rail);if(opts.org)params.set("org",opts.org);const res=await platformFetch(`${platformUrl}/api/v1/builder/revenue/csv?${params.toString()}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"revenue_csv_failed","Failed to get revenue CSV",opts.org)}return{csv:await res.text(),org:res.headers.get("X-Org")??"personal"}}async function listApiKeys(platformUrl,token){const res=await platformFetch(`${platformUrl}/api/v1/builder/api-keys`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"api_keys_failed",body.error,`Failed to list API keys: ${res.status}`)}return await res.json()}async function createApiKey(platformUrl,token,opts={}){const res=await platformFetch(`${platformUrl}/api/v1/builder/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({label:opts.label})});if(!res.ok){const body=await res.json().catch(()=>({}));if(body.error==="api_key_limit_reached"){throw new DvmError2("api_key_limit_reached",`API key limit reached (max ${body.limit??10}).`,"Revoke an unused key first with `dvmctl api-keys revoke <id>`.",void 0,void 0,{message:"provider"})}if(body.error==="label_too_long"){throw new DvmError2("label_too_long",`Label exceeds max length (${body.max??64} chars).`,void 0,void 0,void 0,{message:"provider"})}const msg=body.message;throw new DvmError2("api_key_create_failed",typeof msg==="string"?msg:`Failed to create API key: ${res.status}`,void 0,void 0,void 0,typeof msg==="string"?{message:"provider"}:void 0)}return await res.json()}async function getBuilderTrace(platformUrl,token,traceId,opts={}){const url2=new URL(`${platformUrl}/api/v1/builder/traces/${encodeURIComponent(traceId)}`);if(opts.org)url2.searchParams.set("org",opts.org);const res=await platformFetch(url2,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"trace_fetch_failed","Failed to fetch trace",opts.org)}return await res.json()}async function deleteApiKey(platformUrl,token,id){const res=await platformFetch(`${platformUrl}/api/v1/builder/api-keys/${encodeURIComponent(id)}`,{method:"DELETE",headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"api_key_delete_failed",body.error,`Failed to revoke API key: ${res.status}`)}}init_output();async function apiKeysCreate(opts){const{token,platformUrl}=requireAuth();const result=await createApiKey(platformUrl,token,{label:opts.label});if(opts.human){info(" API key created.");info("");info(` Key: ${result.key}`);info(` ID: ${result.id}`);info(` Label: ${result.label}`);info("");info(" Save this key now \u2014 it will not be shown again.")}else{json(result)}}init_output();async function apiKeysList(opts){const{token,platformUrl}=requireAuth();const result=await listApiKeys(platformUrl,token);if(opts.human){if(result.keys.length===0){info(" No API keys.");return}info(` ${result.count}/${result.limit} keys used`);info("");const idW=Math.max(2,...result.keys.map(k2=>k2.id.length));const labelW=Math.max(5,...result.keys.map(k2=>(k2.label??"\u2014").length));info(` ${"ID".padEnd(idW)} ${"LABEL".padEnd(labelW)} ${"PREFIX".padEnd(10)} ${"CREATED".padEnd(19)} LAST USED`);for(const k2 of result.keys){const prefix=k2.key_prefix?`${k2.key_prefix}...`:"\u2014";const created=fmtDate(k2.created_at);const lastUsed=k2.last_used_at?fmtDate(k2.last_used_at):"never";info(` ${k2.id.padEnd(idW)} ${(k2.label??"\u2014").padEnd(labelW)} ${prefix.padEnd(10)} ${created.padEnd(19)} ${lastUsed}`)}}else{json(result)}}function fmtDate(epoch){return new Date(epoch).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}init_output();async function apiKeysRevoke(id,opts){const{token,platformUrl}=requireAuth();await deleteApiKey(platformUrl,token,id);if(opts.human){info(` API key ${id} revoked.`)}else{json({deleted:true,id})}}import{createHash,randomBytes}from"crypto";import{hostname}from"os";var CLI_AUTH_TTL_MS=5*60*1e3;var CLI_AUTH_POLL_INTERVAL_MS=1e3;var CLI_AUTH_POLL_JITTER_MS=500;var CLI_AUTH_MAX_POLL_ATTEMPTS=Math.floor(CLI_AUTH_TTL_MS/CLI_AUTH_POLL_INTERVAL_MS);var CLI_AUTH_FINGERPRINT_LEN=12;var PLATFORM_URL=process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev";var WEB_URL=process.env.DVMKIT_WEB_URL??"https://dvmkit.com";async function auth(opts){if(opts.status){showStatus(opts.human);return}if(opts.logout){logout(opts.human);return}await login(opts.human)}function showStatus(human){const creds=resolveAuth();if(!creds){if(human){console.log("Not authenticated. Run `dvmctl auth` to log in.")}else{console.log(JSON.stringify({authenticated:false}))}return}if(human){console.log(`Authenticated as ${creds.account}`)}else{console.log(JSON.stringify({authenticated:true,account:creds.account}))}}function logout(human){clearAuthToken();if(human){console.log("Logged out.")}else{console.log(JSON.stringify({status:"logged_out"}))}}async function login(human){const existing=loadAuthToken();if(existing){if(human){console.log(`Already authenticated as ${existing.account}. Use --logout to sign out first.`)}else{console.log(JSON.stringify({authenticated:true,account:existing.account}))}return}const sessionId=randomBytes(16).toString("hex");const verifier=randomBytes(32).toString("hex");const verifierHash=createHash("sha256").update(verifier).digest("hex");const host=hostname();const authUrl=`${WEB_URL}/cli-auth?session=${sessionId}&hash=${verifierHash}&host=${encodeURIComponent(host)}`;const fingerprint=sessionId.slice(0,CLI_AUTH_FINGERPRINT_LEN);console.log(`
|
|
2134
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=zodSchema=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema2=seen.def??seen.schema;const _cached={...schema2};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema2.allOf=schema2.allOf??[];schema2.allOf.push(refSchema)}else{Object.assign(schema2,refSchema)}Object.assign(schema2,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema2[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])){delete schema2[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema2.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])){delete schema2[key]}}}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}else{}if(ctx.external?.uri){const id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==void 0&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;defs[seen.defId]=seen.def}}if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"){return isTransforming(def.innerType,ctx)}if(def.type==="intersection"){return isTransforming(def.left,ctx)||isTransforming(def.right,ctx)}if(def.type==="record"||def.type==="map"){return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx)}if(def.type==="pipe"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod,createStandardJSONSchemaMethod;var init_to_json_schema=__esm({"node_modules/zod/v4/core/to-json-schema.js"(){"use strict";init_registries();createToJSONSchemaMethod=(schema,processors={})=>params=>{const ctx=initializeContext({...params,processors});process2(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{const{libraryOptions,target}=params??{};const ctx=initializeContext({...libraryOptions??{},target,io,processors});process2(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)}}});function toJSONSchema(input,params){if("_idmap"in input){const registry2=input;const ctx2=initializeContext({...params,processors:allProcessors});const defs={};for(const entry of registry2._idmap.entries()){const[_,schema]=entry;process2(schema,ctx2)}const schemas={};const external={registry:registry2,uri:params?.uri,defs};ctx2.external=external;for(const entry of registry2._idmap.entries()){const[key,schema]=entry;extractDefs(ctx2,schema);schemas[key]=finalize(ctx2,schema)}if(Object.keys(defs).length>0){const defsSegment=ctx2.target==="draft-2020-12"?"$defs":"definitions";schemas.__shared={[defsSegment]:defs}}return{schemas}}const ctx=initializeContext({...params,processors:allProcessors});process2(input,ctx);extractDefs(ctx,input);return finalize(ctx,input)}var formatMap,stringProcessor,numberProcessor,booleanProcessor,bigintProcessor,symbolProcessor,nullProcessor,undefinedProcessor,voidProcessor,neverProcessor,anyProcessor,unknownProcessor,dateProcessor,enumProcessor,literalProcessor,nanProcessor,templateLiteralProcessor,fileProcessor,successProcessor,customProcessor,functionProcessor,transformProcessor,mapProcessor,setProcessor,arrayProcessor,objectProcessor,unionProcessor,intersectionProcessor,tupleProcessor,recordProcessor,nullableProcessor,nonoptionalProcessor,defaultProcessor,prefaultProcessor,catchProcessor,pipeProcessor,readonlyProcessor,promiseProcessor,optionalProcessor,lazyProcessor,allProcessors;var init_json_schema_processors=__esm({"node_modules/zod/v4/core/json-schema-processors.js"(){"use strict";init_to_json_schema();init_util();formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};stringProcessor=(schema,ctx,_json,_params)=>{const json3=_json;json3.type="string";const{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json3.minLength=minimum;if(typeof maximum==="number")json3.maxLength=maximum;if(format){json3.format=formatMap[format]??format;if(json3.format==="")delete json3.format;if(format==="time"){delete json3.format}}if(contentEncoding)json3.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){const regexes=[...patterns];if(regexes.length===1)json3.pattern=regexes[0].source;else if(regexes.length>1){json3.allOf=[...regexes.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}}};numberProcessor=(schema,ctx,_json,_params)=>{const json3=_json;const{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json3.type="integer";else json3.type="number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json3.minimum=exclusiveMinimum;json3.exclusiveMinimum=true}else{json3.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json3.minimum=minimum}if(exMax){if(legacy){json3.maximum=exclusiveMaximum;json3.exclusiveMaximum=true}else{json3.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json3.maximum=maximum}if(typeof multipleOf==="number")json3.multipleOf=multipleOf};booleanProcessor=(_schema,_ctx,json3,_params)=>{json3.type="boolean"};bigintProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("BigInt cannot be represented in JSON Schema")}};symbolProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Symbols cannot be represented in JSON Schema")}};nullProcessor=(_schema,ctx,json3,_params)=>{if(ctx.target==="openapi-3.0"){json3.type="string";json3.nullable=true;json3.enum=[null]}else{json3.type="null"}};undefinedProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Undefined cannot be represented in JSON Schema")}};voidProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Void cannot be represented in JSON Schema")}};neverProcessor=(_schema,_ctx,json3,_params)=>{json3.not={}};anyProcessor=(_schema,_ctx,_json,_params)=>{};unknownProcessor=(_schema,_ctx,_json,_params)=>{};dateProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Date cannot be represented in JSON Schema")}};enumProcessor=(schema,_ctx,json3,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.every(v=>typeof v==="number"))json3.type="number";if(values.every(v=>typeof v==="string"))json3.type="string";json3.enum=values};literalProcessor=(schema,ctx,json3,_params)=>{const def=schema._zod.def;const vals=[];for(const val of def.values){if(val===void 0){if(ctx.unrepresentable==="throw"){throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else{}}else if(typeof val==="bigint"){if(ctx.unrepresentable==="throw"){throw new Error("BigInt literals cannot be represented in JSON Schema")}else{vals.push(Number(val))}}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json3.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json3.enum=[val]}else{json3.const=val}}else{if(vals.every(v=>typeof v==="number"))json3.type="number";if(vals.every(v=>typeof v==="string"))json3.type="string";if(vals.every(v=>typeof v==="boolean"))json3.type="boolean";if(vals.every(v=>v===null))json3.type="null";json3.enum=vals}};nanProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("NaN cannot be represented in JSON Schema")}};templateLiteralProcessor=(schema,_ctx,json3,_params)=>{const _json=json3;const pattern=schema._zod.pattern;if(!pattern)throw new Error("Pattern not found in template literal");_json.type="string";_json.pattern=pattern.source};fileProcessor=(schema,_ctx,json3,_params)=>{const _json=json3;const file2={type:"string",format:"binary",contentEncoding:"binary"};const{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file2.minLength=minimum;if(maximum!==void 0)file2.maxLength=maximum;if(mime){if(mime.length===1){file2.contentMediaType=mime[0];Object.assign(_json,file2)}else{Object.assign(_json,file2);_json.anyOf=mime.map(m=>({contentMediaType:m}))}}else{Object.assign(_json,file2)}};successProcessor=(_schema,_ctx,json3,_params)=>{json3.type="boolean"};customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Custom types cannot be represented in JSON Schema")}};functionProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Function types cannot be represented in JSON Schema")}};transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Transforms cannot be represented in JSON Schema")}};mapProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Map cannot be represented in JSON Schema")}};setProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Set cannot be represented in JSON Schema")}};arrayProcessor=(schema,ctx,_json,params)=>{const json3=_json;const def=schema._zod.def;const{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json3.minItems=minimum;if(typeof maximum==="number")json3.maxItems=maximum;json3.type="array";json3.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})};objectProcessor=(schema,ctx,_json,params)=>{const json3=_json;const def=schema._zod.def;json3.type="object";json3.properties={};const shape2=def.shape;for(const key in shape2){json3.properties[key]=process2(shape2[key],ctx,{...params,path:[...params.path,"properties",key]})}const allKeys=new Set(Object.keys(shape2));const requiredKeys=new Set([...allKeys].filter(key=>{const v=def.shape[key]._zod;if(ctx.io==="input"){return v.optin===void 0}else{return v.optout===void 0}}));if(requiredKeys.size>0){json3.required=Array.from(requiredKeys)}if(def.catchall?._zod.def.type==="never"){json3.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json3.additionalProperties=false}else if(def.catchall){json3.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};unionProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x2,i)=>process2(x2,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json3.oneOf=options}else{json3.anyOf=options}};intersectionProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;const a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b2=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b2)?b2.allOf:[b2]];json3.allOf=allOf};tupleProcessor=(schema,ctx,_json,params)=>{const json3=_json;const def=schema._zod.def;json3.type="array";const prefixPath=ctx.target==="draft-2020-12"?"prefixItems":"items";const restPath=ctx.target==="draft-2020-12"?"items":ctx.target==="openapi-3.0"?"items":"additionalItems";const prefixItems=def.items.map((x2,i)=>process2(x2,ctx,{...params,path:[...params.path,prefixPath,i]}));const rest=def.rest?process2(def.rest,ctx,{...params,path:[...params.path,restPath,...ctx.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(ctx.target==="draft-2020-12"){json3.prefixItems=prefixItems;if(rest){json3.items=rest}}else if(ctx.target==="openapi-3.0"){json3.items={anyOf:prefixItems};if(rest){json3.items.anyOf.push(rest)}json3.minItems=prefixItems.length;if(!rest){json3.maxItems=prefixItems.length}}else{json3.items=prefixItems;if(rest){json3.additionalItems=rest}}const{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json3.minItems=minimum;if(typeof maximum==="number")json3.maxItems=maximum};recordProcessor=(schema,ctx,_json,params)=>{const json3=_json;const def=schema._zod.def;json3.type="object";const keyType=def.keyType;const keyBag=keyType._zod.bag;const patterns=keyBag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){const valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json3.patternProperties={};for(const pattern of patterns){json3.patternProperties[pattern.source]=valueSchema}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json3.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]})}json3.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;if(keyValues){const validKeyValues=[...keyValues].filter(v=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json3.required=validKeyValues}}};nullableProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;const inner=process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json3.nullable=true}else{json3.anyOf=[inner,{type:"null"}]}};nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};defaultProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json3.default=JSON.parse(JSON.stringify(def.defaultValue))};prefaultProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io==="input")json3._prefault=JSON.parse(JSON.stringify(def.defaultValue))};catchProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}json3.default=catchValue};pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;process2(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};readonlyProcessor=(schema,ctx,json3,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json3.readOnly=true};promiseProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};lazyProcessor=(schema,ctx,_json,params)=>{const innerType=schema._zod.innerType;process2(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};allProcessors={string:stringProcessor,number:numberProcessor,boolean:booleanProcessor,bigint:bigintProcessor,symbol:symbolProcessor,null:nullProcessor,undefined:undefinedProcessor,void:voidProcessor,never:neverProcessor,any:anyProcessor,unknown:unknownProcessor,date:dateProcessor,enum:enumProcessor,literal:literalProcessor,nan:nanProcessor,template_literal:templateLiteralProcessor,file:fileProcessor,success:successProcessor,custom:customProcessor,function:functionProcessor,transform:transformProcessor,map:mapProcessor,set:setProcessor,array:arrayProcessor,object:objectProcessor,union:unionProcessor,intersection:intersectionProcessor,tuple:tupleProcessor,record:recordProcessor,nullable:nullableProcessor,nonoptional:nonoptionalProcessor,default:defaultProcessor,prefault:prefaultProcessor,catch:catchProcessor,pipe:pipeProcessor,readonly:readonlyProcessor,promise:promiseProcessor,optional:optionalProcessor,lazy:lazyProcessor}}});var JSONSchemaGenerator;var init_json_schema_generator=__esm({"node_modules/zod/v4/core/json-schema-generator.js"(){"use strict";init_json_schema_processors();init_to_json_schema();JSONSchemaGenerator=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(value){this.ctx.counter=value}get seen(){return this.ctx.seen}constructor(params){let normalizedTarget=params?.target??"draft-2020-12";if(normalizedTarget==="draft-4")normalizedTarget="draft-04";if(normalizedTarget==="draft-7")normalizedTarget="draft-07";this.ctx=initializeContext({processors:allProcessors,target:normalizedTarget,...params?.metadata&&{metadata:params.metadata},...params?.unrepresentable&&{unrepresentable:params.unrepresentable},...params?.override&&{override:params.override},...params?.io&&{io:params.io}})}process(schema,_params={path:[],schemaPath:[]}){return process2(schema,this.ctx,_params)}emit(schema,_params){if(_params){if(_params.cycles)this.ctx.cycles=_params.cycles;if(_params.reused)this.ctx.reused=_params.reused;if(_params.external)this.ctx.external=_params.external}extractDefs(this.ctx,schema);const result=finalize(this.ctx,schema);const{"~standard":_,...plainResult}=result;return plainResult}}}});var json_schema_exports={};var init_json_schema=__esm({"node_modules/zod/v4/core/json-schema.js"(){"use strict"}});var core_exports2={};__export(core_exports2,{$ZodAny:()=>$ZodAny,$ZodArray:()=>$ZodArray,$ZodAsyncError:()=>$ZodAsyncError,$ZodBase64:()=>$ZodBase64,$ZodBase64URL:()=>$ZodBase64URL,$ZodBigInt:()=>$ZodBigInt,$ZodBigIntFormat:()=>$ZodBigIntFormat,$ZodBoolean:()=>$ZodBoolean,$ZodCIDRv4:()=>$ZodCIDRv4,$ZodCIDRv6:()=>$ZodCIDRv6,$ZodCUID:()=>$ZodCUID,$ZodCUID2:()=>$ZodCUID2,$ZodCatch:()=>$ZodCatch,$ZodCheck:()=>$ZodCheck,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat,$ZodCheckEndsWith:()=>$ZodCheckEndsWith,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan,$ZodCheckIncludes:()=>$ZodCheckIncludes,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals,$ZodCheckLessThan:()=>$ZodCheckLessThan,$ZodCheckLowerCase:()=>$ZodCheckLowerCase,$ZodCheckMaxLength:()=>$ZodCheckMaxLength,$ZodCheckMaxSize:()=>$ZodCheckMaxSize,$ZodCheckMimeType:()=>$ZodCheckMimeType,$ZodCheckMinLength:()=>$ZodCheckMinLength,$ZodCheckMinSize:()=>$ZodCheckMinSize,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat,$ZodCheckOverwrite:()=>$ZodCheckOverwrite,$ZodCheckProperty:()=>$ZodCheckProperty,$ZodCheckRegex:()=>$ZodCheckRegex,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals,$ZodCheckStartsWith:()=>$ZodCheckStartsWith,$ZodCheckStringFormat:()=>$ZodCheckStringFormat,$ZodCheckUpperCase:()=>$ZodCheckUpperCase,$ZodCodec:()=>$ZodCodec,$ZodCustom:()=>$ZodCustom,$ZodCustomStringFormat:()=>$ZodCustomStringFormat,$ZodDate:()=>$ZodDate,$ZodDefault:()=>$ZodDefault,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion,$ZodE164:()=>$ZodE164,$ZodEmail:()=>$ZodEmail,$ZodEmoji:()=>$ZodEmoji,$ZodEncodeError:()=>$ZodEncodeError,$ZodEnum:()=>$ZodEnum,$ZodError:()=>$ZodError,$ZodExactOptional:()=>$ZodExactOptional,$ZodFile:()=>$ZodFile,$ZodFunction:()=>$ZodFunction,$ZodGUID:()=>$ZodGUID,$ZodIPv4:()=>$ZodIPv4,$ZodIPv6:()=>$ZodIPv6,$ZodISODate:()=>$ZodISODate,$ZodISODateTime:()=>$ZodISODateTime,$ZodISODuration:()=>$ZodISODuration,$ZodISOTime:()=>$ZodISOTime,$ZodIntersection:()=>$ZodIntersection,$ZodJWT:()=>$ZodJWT,$ZodKSUID:()=>$ZodKSUID,$ZodLazy:()=>$ZodLazy,$ZodLiteral:()=>$ZodLiteral,$ZodMAC:()=>$ZodMAC,$ZodMap:()=>$ZodMap,$ZodNaN:()=>$ZodNaN,$ZodNanoID:()=>$ZodNanoID,$ZodNever:()=>$ZodNever,$ZodNonOptional:()=>$ZodNonOptional,$ZodNull:()=>$ZodNull,$ZodNullable:()=>$ZodNullable,$ZodNumber:()=>$ZodNumber,$ZodNumberFormat:()=>$ZodNumberFormat,$ZodObject:()=>$ZodObject,$ZodObjectJIT:()=>$ZodObjectJIT,$ZodOptional:()=>$ZodOptional,$ZodPipe:()=>$ZodPipe,$ZodPrefault:()=>$ZodPrefault,$ZodPreprocess:()=>$ZodPreprocess,$ZodPromise:()=>$ZodPromise,$ZodReadonly:()=>$ZodReadonly,$ZodRealError:()=>$ZodRealError,$ZodRecord:()=>$ZodRecord,$ZodRegistry:()=>$ZodRegistry,$ZodSet:()=>$ZodSet,$ZodString:()=>$ZodString,$ZodStringFormat:()=>$ZodStringFormat,$ZodSuccess:()=>$ZodSuccess,$ZodSymbol:()=>$ZodSymbol,$ZodTemplateLiteral:()=>$ZodTemplateLiteral,$ZodTransform:()=>$ZodTransform,$ZodTuple:()=>$ZodTuple,$ZodType:()=>$ZodType,$ZodULID:()=>$ZodULID,$ZodURL:()=>$ZodURL,$ZodUUID:()=>$ZodUUID,$ZodUndefined:()=>$ZodUndefined,$ZodUnion:()=>$ZodUnion,$ZodUnknown:()=>$ZodUnknown,$ZodVoid:()=>$ZodVoid,$ZodXID:()=>$ZodXID,$ZodXor:()=>$ZodXor,$brand:()=>$brand,$constructor:()=>$constructor,$input:()=>$input,$output:()=>$output,Doc:()=>Doc,JSONSchema:()=>json_schema_exports,JSONSchemaGenerator:()=>JSONSchemaGenerator,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,_any:()=>_any,_array:()=>_array,_base64:()=>_base64,_base64url:()=>_base64url,_bigint:()=>_bigint,_boolean:()=>_boolean,_catch:()=>_catch,_check:()=>_check,_cidrv4:()=>_cidrv4,_cidrv6:()=>_cidrv6,_coercedBigint:()=>_coercedBigint,_coercedBoolean:()=>_coercedBoolean,_coercedDate:()=>_coercedDate,_coercedNumber:()=>_coercedNumber,_coercedString:()=>_coercedString,_cuid:()=>_cuid,_cuid2:()=>_cuid2,_custom:()=>_custom,_date:()=>_date,_decode:()=>_decode,_decodeAsync:()=>_decodeAsync,_default:()=>_default,_discriminatedUnion:()=>_discriminatedUnion,_e164:()=>_e164,_email:()=>_email,_emoji:()=>_emoji2,_encode:()=>_encode,_encodeAsync:()=>_encodeAsync,_endsWith:()=>_endsWith,_enum:()=>_enum,_file:()=>_file,_float32:()=>_float32,_float64:()=>_float64,_gt:()=>_gt,_gte:()=>_gte,_guid:()=>_guid,_includes:()=>_includes,_int:()=>_int,_int32:()=>_int32,_int64:()=>_int64,_intersection:()=>_intersection,_ipv4:()=>_ipv4,_ipv6:()=>_ipv6,_isoDate:()=>_isoDate,_isoDateTime:()=>_isoDateTime,_isoDuration:()=>_isoDuration,_isoTime:()=>_isoTime,_jwt:()=>_jwt,_ksuid:()=>_ksuid,_lazy:()=>_lazy,_length:()=>_length,_literal:()=>_literal,_lowercase:()=>_lowercase,_lt:()=>_lt,_lte:()=>_lte,_mac:()=>_mac,_map:()=>_map,_max:()=>_lte,_maxLength:()=>_maxLength,_maxSize:()=>_maxSize,_mime:()=>_mime,_min:()=>_gte,_minLength:()=>_minLength,_minSize:()=>_minSize,_multipleOf:()=>_multipleOf,_nan:()=>_nan,_nanoid:()=>_nanoid,_nativeEnum:()=>_nativeEnum,_negative:()=>_negative,_never:()=>_never,_nonnegative:()=>_nonnegative,_nonoptional:()=>_nonoptional,_nonpositive:()=>_nonpositive,_normalize:()=>_normalize,_null:()=>_null2,_nullable:()=>_nullable,_number:()=>_number,_optional:()=>_optional,_overwrite:()=>_overwrite,_parse:()=>_parse,_parseAsync:()=>_parseAsync,_pipe:()=>_pipe,_positive:()=>_positive,_promise:()=>_promise,_property:()=>_property,_readonly:()=>_readonly,_record:()=>_record,_refine:()=>_refine,_regex:()=>_regex,_safeDecode:()=>_safeDecode,_safeDecodeAsync:()=>_safeDecodeAsync,_safeEncode:()=>_safeEncode,_safeEncodeAsync:()=>_safeEncodeAsync,_safeParse:()=>_safeParse,_safeParseAsync:()=>_safeParseAsync,_set:()=>_set,_size:()=>_size,_slugify:()=>_slugify,_startsWith:()=>_startsWith,_string:()=>_string,_stringFormat:()=>_stringFormat,_stringbool:()=>_stringbool,_success:()=>_success,_superRefine:()=>_superRefine,_symbol:()=>_symbol,_templateLiteral:()=>_templateLiteral,_toLowerCase:()=>_toLowerCase,_toUpperCase:()=>_toUpperCase,_transform:()=>_transform,_trim:()=>_trim,_tuple:()=>_tuple,_uint32:()=>_uint32,_uint64:()=>_uint64,_ulid:()=>_ulid,_undefined:()=>_undefined2,_union:()=>_union,_unknown:()=>_unknown,_uppercase:()=>_uppercase,_url:()=>_url,_uuid:()=>_uuid,_uuidv4:()=>_uuidv4,_uuidv6:()=>_uuidv6,_uuidv7:()=>_uuidv7,_void:()=>_void,_xid:()=>_xid,_xor:()=>_xor,clone:()=>clone,config:()=>config,createStandardJSONSchemaMethod:()=>createStandardJSONSchemaMethod,createToJSONSchemaMethod:()=>createToJSONSchemaMethod,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe,encode:()=>encode,encodeAsync:()=>encodeAsync,extractDefs:()=>extractDefs,finalize:()=>finalize,flattenError:()=>flattenError,formatError:()=>formatError,globalConfig:()=>globalConfig,globalRegistry:()=>globalRegistry,initializeContext:()=>initializeContext,isValidBase64:()=>isValidBase64,isValidBase64URL:()=>isValidBase64URL,isValidJWT:()=>isValidJWT,locales:()=>locales_exports,meta:()=>meta,parse:()=>parse2,parseAsync:()=>parseAsync,prettifyError:()=>prettifyError,process:()=>process2,regexes:()=>regexes_exports,registry:()=>registry,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,toDotPath:()=>toDotPath,toJSONSchema:()=>toJSONSchema,treeifyError:()=>treeifyError,util:()=>util_exports,version:()=>version2});var init_core2=__esm({"node_modules/zod/v4/core/index.js"(){"use strict";init_core();init_parse();init_errors2();init_schemas();init_checks();init_versions();init_util();init_regexes();init_locales();init_registries();init_doc();init_api();init_to_json_schema();init_json_schema_processors();init_json_schema_generator();init_json_schema()}});var init_parse2=__esm({"node_modules/zod/v4/mini/parse.js"(){"use strict";init_core2()}});function string2(params){return _string(ZodMiniString,params)}function email2(params){return _email(ZodMiniEmail,params)}function guid2(params){return _guid(ZodMiniGUID,params)}function uuid2(params){return _uuid(ZodMiniUUID,params)}function uuidv4(params){return _uuidv4(ZodMiniUUID,params)}function uuidv6(params){return _uuidv6(ZodMiniUUID,params)}function uuidv7(params){return _uuidv7(ZodMiniUUID,params)}function url(params){return _url(ZodMiniURL,params)}function httpUrl(params){return _url(ZodMiniURL,{protocol:regexes_exports.httpProtocol,hostname:regexes_exports.domain,...normalizeParams(params)})}function emoji2(params){return _emoji2(ZodMiniEmoji,params)}function nanoid2(params){return _nanoid(ZodMiniNanoID,params)}function cuid3(params){return _cuid(ZodMiniCUID,params)}function cuid22(params){return _cuid2(ZodMiniCUID2,params)}function ulid2(params){return _ulid(ZodMiniULID,params)}function xid2(params){return _xid(ZodMiniXID,params)}function ksuid2(params){return _ksuid(ZodMiniKSUID,params)}function ipv42(params){return _ipv4(ZodMiniIPv4,params)}function ipv62(params){return _ipv6(ZodMiniIPv6,params)}function cidrv42(params){return _cidrv4(ZodMiniCIDRv4,params)}function cidrv62(params){return _cidrv6(ZodMiniCIDRv6,params)}function mac2(params){return _mac(ZodMiniMAC,params)}function base642(params){return _base64(ZodMiniBase64,params)}function base64url2(params){return _base64url(ZodMiniBase64URL,params)}function e1642(params){return _e164(ZodMiniE164,params)}function jwt(params){return _jwt(ZodMiniJWT,params)}function stringFormat(format,fnOrRegex,_params={}){return _stringFormat(ZodMiniCustomStringFormat,format,fnOrRegex,_params)}function hostname3(_params){return _stringFormat(ZodMiniCustomStringFormat,"hostname",regexes_exports.hostname,_params)}function hex2(_params){return _stringFormat(ZodMiniCustomStringFormat,"hex",regexes_exports.hex,_params)}function hash(alg,params){const enc=params?.enc??"hex";const format=`${alg}_${enc}`;const regex=regexes_exports[format];if(!regex)throw new Error(`Unrecognized hash format: ${format}`);return _stringFormat(ZodMiniCustomStringFormat,format,regex,params)}function number2(params){return _number(ZodMiniNumber,params)}function int(params){return _int(ZodMiniNumberFormat,params)}function float32(params){return _float32(ZodMiniNumberFormat,params)}function float64(params){return _float64(ZodMiniNumberFormat,params)}function int32(params){return _int32(ZodMiniNumberFormat,params)}function uint32(params){return _uint32(ZodMiniNumberFormat,params)}function boolean2(params){return _boolean(ZodMiniBoolean,params)}function bigint2(params){return _bigint(ZodMiniBigInt,params)}function int64(params){return _int64(ZodMiniBigIntFormat,params)}function uint64(params){return _uint64(ZodMiniBigIntFormat,params)}function symbol(params){return _symbol(ZodMiniSymbol,params)}function _undefined3(params){return _undefined2(ZodMiniUndefined,params)}function _null3(params){return _null2(ZodMiniNull,params)}function any(){return _any(ZodMiniAny)}function unknown(){return _unknown(ZodMiniUnknown)}function never(params){return _never(ZodMiniNever,params)}function _void2(params){return _void(ZodMiniVoid,params)}function date2(params){return _date(ZodMiniDate,params)}function array(element,params){return new ZodMiniArray({type:"array",element,...normalizeParams(params)})}function keyof(schema){const shape2=schema._zod.def.shape;return _enum2(Object.keys(shape2))}function object(shape2,params){const def={type:"object",shape:shape2??{},...normalizeParams(params)};return new ZodMiniObject(def)}function strictObject(shape2,params){return new ZodMiniObject({type:"object",shape:shape2,catchall:never(),...normalizeParams(params)})}function looseObject(shape2,params){return new ZodMiniObject({type:"object",shape:shape2,catchall:unknown(),...normalizeParams(params)})}function extend2(schema,shape2){return extend(schema,shape2)}function safeExtend2(schema,shape2){return safeExtend(schema,shape2)}function merge2(schema,shape2){return extend(schema,shape2)}function pick2(schema,mask){return pick(schema,mask)}function omit2(schema,mask){return omit(schema,mask)}function partial2(schema,mask){return partial(ZodMiniOptional,schema,mask)}function required2(schema,mask){return required(ZodMiniNonOptional,schema,mask)}function catchall(inst,catchall2){return inst.clone({...inst._zod.def,catchall:catchall2})}function union(options,params){return new ZodMiniUnion({type:"union",options,...normalizeParams(params)})}function xor(options,params){return new ZodMiniXor({type:"union",options,inclusive:false,...normalizeParams(params)})}function discriminatedUnion(discriminator,options,params){return new ZodMiniDiscriminatedUnion({type:"union",options,discriminator,...normalizeParams(params)})}function intersection(left,right){return new ZodMiniIntersection({type:"intersection",left,right})}function tuple(items,_paramsOrRest,_params){const hasRest=_paramsOrRest instanceof $ZodType;const params=hasRest?_params:_paramsOrRest;const rest=hasRest?_paramsOrRest:null;return new ZodMiniTuple({type:"tuple",items,rest,...normalizeParams(params)})}function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodMiniRecord({type:"record",keyType:string2(),valueType:keyType,...normalizeParams(valueType)})}return new ZodMiniRecord({type:"record",keyType,valueType,...normalizeParams(params)})}function partialRecord(keyType,valueType,params){const k2=clone(keyType);k2._zod.values=void 0;return new ZodMiniRecord({type:"record",keyType:k2,valueType,...normalizeParams(params)})}function looseRecord(keyType,valueType,params){return new ZodMiniRecord({type:"record",keyType,valueType,mode:"loose",...normalizeParams(params)})}function map(keyType,valueType,params){return new ZodMiniMap({type:"map",keyType,valueType,...normalizeParams(params)})}function set(valueType,params){return new ZodMiniSet({type:"set",valueType,...normalizeParams(params)})}function _enum2(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodMiniEnum({type:"enum",entries,...normalizeParams(params)})}function nativeEnum(entries,params){return new ZodMiniEnum({type:"enum",entries,...normalizeParams(params)})}function literal(value,params){return new ZodMiniLiteral({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams(params)})}function file(params){return _file(ZodMiniFile,params)}function transform(fn){return new ZodMiniTransform({type:"transform",transform:fn})}function optional(innerType){return new ZodMiniOptional({type:"optional",innerType})}function exactOptional(innerType){return new ZodMiniExactOptional({type:"optional",innerType})}function nullable(innerType){return new ZodMiniNullable({type:"nullable",innerType})}function nullish2(innerType){return optional(nullable(innerType))}function _default2(innerType,defaultValue){return new ZodMiniDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function prefault(innerType,defaultValue){return new ZodMiniPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone(defaultValue)}})}function nonoptional(innerType,params){return new ZodMiniNonOptional({type:"nonoptional",innerType,...normalizeParams(params)})}function success(innerType){return new ZodMiniSuccess({type:"success",innerType})}function _catch2(innerType,catchValue){return new ZodMiniCatch({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan(params){return _nan(ZodMiniNaN,params)}function pipe(in_,out){return new ZodMiniPipe({type:"pipe",in:in_,out})}function codec(in_,out,params){return new ZodMiniCodec({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function invertCodec(codec2){const def=codec2._zod.def;return new ZodMiniCodec({type:"pipe",in:def.out,out:def.in,transform:def.reverseTransform,reverseTransform:def.transform})}function readonly(innerType){return new ZodMiniReadonly({type:"readonly",innerType})}function templateLiteral(parts,params){return new ZodMiniTemplateLiteral({type:"template_literal",parts,...normalizeParams(params)})}function _lazy2(getter){return new ZodMiniLazy({type:"lazy",getter})}function promise(innerType){return new ZodMiniPromise({type:"promise",innerType})}function check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function custom(fn,_params){return _custom(ZodMiniCustom,fn??(()=>true),_params)}function refine(fn,_params={}){return _refine(ZodMiniCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function _instanceof(cls,params={}){const inst=custom(data=>data instanceof cls,params);inst._zod.bag.Class=cls;inst._zod.check=payload=>{if(!(payload.value instanceof cls)){payload.issues.push({code:"invalid_type",expected:cls.name,input:payload.value,inst,path:[...inst._zod.def.path??[]]})}};return inst}function json2(){const jsonSchema=_lazy2(()=>{return union([string2(),number2(),boolean2(),_null3(),array(jsonSchema),record(string2(),jsonSchema)])});return jsonSchema}function _function(params){return new ZodMiniFunction({type:"function",input:Array.isArray(params?.input)?tuple(params?.input):params?.input??array(unknown()),output:params?.output??unknown()})}var ZodMiniType,ZodMiniString,ZodMiniStringFormat,ZodMiniEmail,ZodMiniGUID,ZodMiniUUID,ZodMiniURL,ZodMiniEmoji,ZodMiniNanoID,ZodMiniCUID,ZodMiniCUID2,ZodMiniULID,ZodMiniXID,ZodMiniKSUID,ZodMiniIPv4,ZodMiniIPv6,ZodMiniCIDRv4,ZodMiniCIDRv6,ZodMiniMAC,ZodMiniBase64,ZodMiniBase64URL,ZodMiniE164,ZodMiniJWT,ZodMiniCustomStringFormat,ZodMiniNumber,ZodMiniNumberFormat,ZodMiniBoolean,ZodMiniBigInt,ZodMiniBigIntFormat,ZodMiniSymbol,ZodMiniUndefined,ZodMiniNull,ZodMiniAny,ZodMiniUnknown,ZodMiniNever,ZodMiniVoid,ZodMiniDate,ZodMiniArray,ZodMiniObject,ZodMiniUnion,ZodMiniXor,ZodMiniDiscriminatedUnion,ZodMiniIntersection,ZodMiniTuple,ZodMiniRecord,ZodMiniMap,ZodMiniSet,ZodMiniEnum,ZodMiniLiteral,ZodMiniFile,ZodMiniTransform,ZodMiniOptional,ZodMiniExactOptional,ZodMiniNullable,ZodMiniDefault,ZodMiniPrefault,ZodMiniNonOptional,ZodMiniSuccess,ZodMiniCatch,ZodMiniNaN,ZodMiniPipe,ZodMiniCodec,ZodMiniReadonly,ZodMiniTemplateLiteral,ZodMiniLazy,ZodMiniPromise,ZodMiniCustom,describe2,meta2,stringbool,ZodMiniFunction;var init_schemas2=__esm({"node_modules/zod/v4/mini/schemas.js"(){"use strict";init_core2();init_util();init_parse2();ZodMiniType=$constructor("ZodMiniType",(inst,def)=>{if(!inst._zod)throw new Error("Uninitialized schema in ZodMiniType.");$ZodType.init(inst,def);inst.def=def;inst.type=def.type;inst.parse=(data,params)=>parse2(inst,data,params,{callee:inst.parse});inst.safeParse=(data,params)=>safeParse(inst,data,params);inst.parseAsync=async(data,params)=>parseAsync(inst,data,params,{callee:inst.parseAsync});inst.safeParseAsync=async(data,params)=>safeParseAsync(inst,data,params);inst.check=(...checks)=>{return inst.clone({...def,checks:[...def.checks??[],...checks.map(ch=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]},{parent:true})};inst.with=inst.check;inst.clone=(_def,params)=>clone(inst,_def,params);inst.brand=()=>inst;inst.register=((reg,meta4)=>{reg.add(inst,meta4);return inst});inst.apply=fn=>fn(inst)});ZodMiniString=$constructor("ZodMiniString",(inst,def)=>{$ZodString.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniStringFormat=$constructor("ZodMiniStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);ZodMiniString.init(inst,def)});ZodMiniEmail=$constructor("ZodMiniEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniGUID=$constructor("ZodMiniGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniUUID=$constructor("ZodMiniUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniURL=$constructor("ZodMiniURL",(inst,def)=>{$ZodURL.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniEmoji=$constructor("ZodMiniEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniNanoID=$constructor("ZodMiniNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCUID=$constructor("ZodMiniCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCUID2=$constructor("ZodMiniCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniULID=$constructor("ZodMiniULID",(inst,def)=>{$ZodULID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniXID=$constructor("ZodMiniXID",(inst,def)=>{$ZodXID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniKSUID=$constructor("ZodMiniKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniIPv4=$constructor("ZodMiniIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniIPv6=$constructor("ZodMiniIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCIDRv4=$constructor("ZodMiniCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCIDRv6=$constructor("ZodMiniCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniMAC=$constructor("ZodMiniMAC",(inst,def)=>{$ZodMAC.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniBase64=$constructor("ZodMiniBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniBase64URL=$constructor("ZodMiniBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniE164=$constructor("ZodMiniE164",(inst,def)=>{$ZodE164.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniJWT=$constructor("ZodMiniJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniCustomStringFormat=$constructor("ZodMiniCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniNumber=$constructor("ZodMiniNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNumberFormat=$constructor("ZodMiniNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodMiniNumber.init(inst,def)});ZodMiniBoolean=$constructor("ZodMiniBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniBigInt=$constructor("ZodMiniBigInt",(inst,def)=>{$ZodBigInt.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniBigIntFormat=$constructor("ZodMiniBigIntFormat",(inst,def)=>{$ZodBigIntFormat.init(inst,def);ZodMiniBigInt.init(inst,def)});ZodMiniSymbol=$constructor("ZodMiniSymbol",(inst,def)=>{$ZodSymbol.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniUndefined=$constructor("ZodMiniUndefined",(inst,def)=>{$ZodUndefined.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNull=$constructor("ZodMiniNull",(inst,def)=>{$ZodNull.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniAny=$constructor("ZodMiniAny",(inst,def)=>{$ZodAny.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniUnknown=$constructor("ZodMiniUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNever=$constructor("ZodMiniNever",(inst,def)=>{$ZodNever.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniVoid=$constructor("ZodMiniVoid",(inst,def)=>{$ZodVoid.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniDate=$constructor("ZodMiniDate",(inst,def)=>{$ZodDate.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniArray=$constructor("ZodMiniArray",(inst,def)=>{$ZodArray.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniObject=$constructor("ZodMiniObject",(inst,def)=>{$ZodObject.init(inst,def);ZodMiniType.init(inst,def);defineLazy(inst,"shape",()=>def.shape)});ZodMiniUnion=$constructor("ZodMiniUnion",(inst,def)=>{$ZodUnion.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniXor=$constructor("ZodMiniXor",(inst,def)=>{ZodMiniUnion.init(inst,def);$ZodXor.init(inst,def)});ZodMiniDiscriminatedUnion=$constructor("ZodMiniDiscriminatedUnion",(inst,def)=>{$ZodDiscriminatedUnion.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniIntersection=$constructor("ZodMiniIntersection",(inst,def)=>{$ZodIntersection.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniTuple=$constructor("ZodMiniTuple",(inst,def)=>{$ZodTuple.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniRecord=$constructor("ZodMiniRecord",(inst,def)=>{$ZodRecord.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniMap=$constructor("ZodMiniMap",(inst,def)=>{$ZodMap.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniSet=$constructor("ZodMiniSet",(inst,def)=>{$ZodSet.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniEnum=$constructor("ZodMiniEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodMiniType.init(inst,def);inst.options=Object.values(def.entries)});ZodMiniLiteral=$constructor("ZodMiniLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniFile=$constructor("ZodMiniFile",(inst,def)=>{$ZodFile.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniTransform=$constructor("ZodMiniTransform",(inst,def)=>{$ZodTransform.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniOptional=$constructor("ZodMiniOptional",(inst,def)=>{$ZodOptional.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniExactOptional=$constructor("ZodMiniExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNullable=$constructor("ZodMiniNullable",(inst,def)=>{$ZodNullable.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniDefault=$constructor("ZodMiniDefault",(inst,def)=>{$ZodDefault.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniPrefault=$constructor("ZodMiniPrefault",(inst,def)=>{$ZodPrefault.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNonOptional=$constructor("ZodMiniNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniSuccess=$constructor("ZodMiniSuccess",(inst,def)=>{$ZodSuccess.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniCatch=$constructor("ZodMiniCatch",(inst,def)=>{$ZodCatch.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniNaN=$constructor("ZodMiniNaN",(inst,def)=>{$ZodNaN.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniPipe=$constructor("ZodMiniPipe",(inst,def)=>{$ZodPipe.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniCodec=$constructor("ZodMiniCodec",(inst,def)=>{ZodMiniPipe.init(inst,def);$ZodCodec.init(inst,def)});ZodMiniReadonly=$constructor("ZodMiniReadonly",(inst,def)=>{$ZodReadonly.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniTemplateLiteral=$constructor("ZodMiniTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniLazy=$constructor("ZodMiniLazy",(inst,def)=>{$ZodLazy.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniPromise=$constructor("ZodMiniPromise",(inst,def)=>{$ZodPromise.init(inst,def);ZodMiniType.init(inst,def)});ZodMiniCustom=$constructor("ZodMiniCustom",(inst,def)=>{$ZodCustom.init(inst,def);ZodMiniType.init(inst,def)});describe2=describe;meta2=meta;stringbool=(...args)=>_stringbool({Codec:ZodMiniCodec,Boolean:ZodMiniBoolean,String:ZodMiniString},...args);ZodMiniFunction=$constructor("ZodMiniFunction",(inst,def)=>{$ZodFunction.init(inst,def);ZodMiniType.init(inst,def)})}});var init_checks2=__esm({"node_modules/zod/v4/mini/checks.js"(){"use strict";init_core2()}});var iso_exports={};__export(iso_exports,{ZodMiniISODate:()=>ZodMiniISODate,ZodMiniISODateTime:()=>ZodMiniISODateTime,ZodMiniISODuration:()=>ZodMiniISODuration,ZodMiniISOTime:()=>ZodMiniISOTime,date:()=>date3,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodMiniISODateTime,params)}function date3(params){return _isoDate(ZodMiniISODate,params)}function time2(params){return _isoTime(ZodMiniISOTime,params)}function duration2(params){return _isoDuration(ZodMiniISODuration,params)}var ZodMiniISODateTime,ZodMiniISODate,ZodMiniISOTime,ZodMiniISODuration;var init_iso=__esm({"node_modules/zod/v4/mini/iso.js"(){"use strict";init_core2();init_schemas2();ZodMiniISODateTime=$constructor("ZodMiniISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniISODate=$constructor("ZodMiniISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniISOTime=$constructor("ZodMiniISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodMiniStringFormat.init(inst,def)});ZodMiniISODuration=$constructor("ZodMiniISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodMiniStringFormat.init(inst,def)})}});var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint3,boolean:()=>boolean3,date:()=>date4,number:()=>number3,string:()=>string3});function string3(params){return _coercedString(ZodMiniString,params)}function number3(params){return _coercedNumber(ZodMiniNumber,params)}function boolean3(params){return _coercedBoolean(ZodMiniBoolean,params)}function bigint3(params){return _coercedBigint(ZodMiniBigInt,params)}function date4(params){return _coercedDate(ZodMiniDate,params)}var init_coerce=__esm({"node_modules/zod/v4/mini/coerce.js"(){"use strict";init_core2();init_schemas2()}});var external_exports={};__export(external_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodMiniAny:()=>ZodMiniAny,ZodMiniArray:()=>ZodMiniArray,ZodMiniBase64:()=>ZodMiniBase64,ZodMiniBase64URL:()=>ZodMiniBase64URL,ZodMiniBigInt:()=>ZodMiniBigInt,ZodMiniBigIntFormat:()=>ZodMiniBigIntFormat,ZodMiniBoolean:()=>ZodMiniBoolean,ZodMiniCIDRv4:()=>ZodMiniCIDRv4,ZodMiniCIDRv6:()=>ZodMiniCIDRv6,ZodMiniCUID:()=>ZodMiniCUID,ZodMiniCUID2:()=>ZodMiniCUID2,ZodMiniCatch:()=>ZodMiniCatch,ZodMiniCodec:()=>ZodMiniCodec,ZodMiniCustom:()=>ZodMiniCustom,ZodMiniCustomStringFormat:()=>ZodMiniCustomStringFormat,ZodMiniDate:()=>ZodMiniDate,ZodMiniDefault:()=>ZodMiniDefault,ZodMiniDiscriminatedUnion:()=>ZodMiniDiscriminatedUnion,ZodMiniE164:()=>ZodMiniE164,ZodMiniEmail:()=>ZodMiniEmail,ZodMiniEmoji:()=>ZodMiniEmoji,ZodMiniEnum:()=>ZodMiniEnum,ZodMiniExactOptional:()=>ZodMiniExactOptional,ZodMiniFile:()=>ZodMiniFile,ZodMiniFunction:()=>ZodMiniFunction,ZodMiniGUID:()=>ZodMiniGUID,ZodMiniIPv4:()=>ZodMiniIPv4,ZodMiniIPv6:()=>ZodMiniIPv6,ZodMiniISODate:()=>ZodMiniISODate,ZodMiniISODateTime:()=>ZodMiniISODateTime,ZodMiniISODuration:()=>ZodMiniISODuration,ZodMiniISOTime:()=>ZodMiniISOTime,ZodMiniIntersection:()=>ZodMiniIntersection,ZodMiniJWT:()=>ZodMiniJWT,ZodMiniKSUID:()=>ZodMiniKSUID,ZodMiniLazy:()=>ZodMiniLazy,ZodMiniLiteral:()=>ZodMiniLiteral,ZodMiniMAC:()=>ZodMiniMAC,ZodMiniMap:()=>ZodMiniMap,ZodMiniNaN:()=>ZodMiniNaN,ZodMiniNanoID:()=>ZodMiniNanoID,ZodMiniNever:()=>ZodMiniNever,ZodMiniNonOptional:()=>ZodMiniNonOptional,ZodMiniNull:()=>ZodMiniNull,ZodMiniNullable:()=>ZodMiniNullable,ZodMiniNumber:()=>ZodMiniNumber,ZodMiniNumberFormat:()=>ZodMiniNumberFormat,ZodMiniObject:()=>ZodMiniObject,ZodMiniOptional:()=>ZodMiniOptional,ZodMiniPipe:()=>ZodMiniPipe,ZodMiniPrefault:()=>ZodMiniPrefault,ZodMiniPromise:()=>ZodMiniPromise,ZodMiniReadonly:()=>ZodMiniReadonly,ZodMiniRecord:()=>ZodMiniRecord,ZodMiniSet:()=>ZodMiniSet,ZodMiniString:()=>ZodMiniString,ZodMiniStringFormat:()=>ZodMiniStringFormat,ZodMiniSuccess:()=>ZodMiniSuccess,ZodMiniSymbol:()=>ZodMiniSymbol,ZodMiniTemplateLiteral:()=>ZodMiniTemplateLiteral,ZodMiniTransform:()=>ZodMiniTransform,ZodMiniTuple:()=>ZodMiniTuple,ZodMiniType:()=>ZodMiniType,ZodMiniULID:()=>ZodMiniULID,ZodMiniURL:()=>ZodMiniURL,ZodMiniUUID:()=>ZodMiniUUID,ZodMiniUndefined:()=>ZodMiniUndefined,ZodMiniUnion:()=>ZodMiniUnion,ZodMiniUnknown:()=>ZodMiniUnknown,ZodMiniVoid:()=>ZodMiniVoid,ZodMiniXID:()=>ZodMiniXID,ZodMiniXor:()=>ZodMiniXor,_default:()=>_default2,_function:()=>_function,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,catchall:()=>catchall,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>coerce_exports,config:()=>config,core:()=>core_exports2,cuid:()=>cuid3,cuid2:()=>cuid22,custom:()=>custom,date:()=>date2,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode,encodeAsync:()=>encodeAsync,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,extend:()=>extend2,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,function:()=>_function,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash,hex:()=>hex2,hostname:()=>hostname3,httpUrl:()=>httpUrl,includes:()=>_includes,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>iso_exports,json:()=>json2,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>_lazy2,length:()=>_length,literal:()=>literal,locales:()=>locales_exports,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,maximum:()=>_lte,merge:()=>merge2,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,minimum:()=>_gte,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,omit:()=>omit2,optional:()=>optional,overwrite:()=>_overwrite,parse:()=>parse2,parseAsync:()=>parseAsync,partial:()=>partial2,partialRecord:()=>partialRecord,pick:()=>pick2,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,prettifyError:()=>prettifyError,promise:()=>promise,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>regexes_exports,registry:()=>registry,required:()=>required2,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeExtend:()=>safeExtend2,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,set:()=>set,size:()=>_size,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,uppercase:()=>_uppercase,url:()=>url,util:()=>util_exports,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor});var init_external=__esm({"node_modules/zod/v4/mini/external.js"(){"use strict";init_core2();init_parse2();init_schemas2();init_checks2();init_core2();init_json_schema_processors();init_locales();init_iso();init_iso();init_coerce()}});var init_mini=__esm({"node_modules/zod/mini/index.js"(){"use strict";init_external();init_external()}});var zod_exports={};__export(zod_exports,{$brand:()=>$brand,$input:()=>$input,$output:()=>$output,NEVER:()=>NEVER,TimePrecision:()=>TimePrecision,ZodMiniAny:()=>ZodMiniAny,ZodMiniArray:()=>ZodMiniArray,ZodMiniBase64:()=>ZodMiniBase64,ZodMiniBase64URL:()=>ZodMiniBase64URL,ZodMiniBigInt:()=>ZodMiniBigInt,ZodMiniBigIntFormat:()=>ZodMiniBigIntFormat,ZodMiniBoolean:()=>ZodMiniBoolean,ZodMiniCIDRv4:()=>ZodMiniCIDRv4,ZodMiniCIDRv6:()=>ZodMiniCIDRv6,ZodMiniCUID:()=>ZodMiniCUID,ZodMiniCUID2:()=>ZodMiniCUID2,ZodMiniCatch:()=>ZodMiniCatch,ZodMiniCodec:()=>ZodMiniCodec,ZodMiniCustom:()=>ZodMiniCustom,ZodMiniCustomStringFormat:()=>ZodMiniCustomStringFormat,ZodMiniDate:()=>ZodMiniDate,ZodMiniDefault:()=>ZodMiniDefault,ZodMiniDiscriminatedUnion:()=>ZodMiniDiscriminatedUnion,ZodMiniE164:()=>ZodMiniE164,ZodMiniEmail:()=>ZodMiniEmail,ZodMiniEmoji:()=>ZodMiniEmoji,ZodMiniEnum:()=>ZodMiniEnum,ZodMiniExactOptional:()=>ZodMiniExactOptional,ZodMiniFile:()=>ZodMiniFile,ZodMiniFunction:()=>ZodMiniFunction,ZodMiniGUID:()=>ZodMiniGUID,ZodMiniIPv4:()=>ZodMiniIPv4,ZodMiniIPv6:()=>ZodMiniIPv6,ZodMiniISODate:()=>ZodMiniISODate,ZodMiniISODateTime:()=>ZodMiniISODateTime,ZodMiniISODuration:()=>ZodMiniISODuration,ZodMiniISOTime:()=>ZodMiniISOTime,ZodMiniIntersection:()=>ZodMiniIntersection,ZodMiniJWT:()=>ZodMiniJWT,ZodMiniKSUID:()=>ZodMiniKSUID,ZodMiniLazy:()=>ZodMiniLazy,ZodMiniLiteral:()=>ZodMiniLiteral,ZodMiniMAC:()=>ZodMiniMAC,ZodMiniMap:()=>ZodMiniMap,ZodMiniNaN:()=>ZodMiniNaN,ZodMiniNanoID:()=>ZodMiniNanoID,ZodMiniNever:()=>ZodMiniNever,ZodMiniNonOptional:()=>ZodMiniNonOptional,ZodMiniNull:()=>ZodMiniNull,ZodMiniNullable:()=>ZodMiniNullable,ZodMiniNumber:()=>ZodMiniNumber,ZodMiniNumberFormat:()=>ZodMiniNumberFormat,ZodMiniObject:()=>ZodMiniObject,ZodMiniOptional:()=>ZodMiniOptional,ZodMiniPipe:()=>ZodMiniPipe,ZodMiniPrefault:()=>ZodMiniPrefault,ZodMiniPromise:()=>ZodMiniPromise,ZodMiniReadonly:()=>ZodMiniReadonly,ZodMiniRecord:()=>ZodMiniRecord,ZodMiniSet:()=>ZodMiniSet,ZodMiniString:()=>ZodMiniString,ZodMiniStringFormat:()=>ZodMiniStringFormat,ZodMiniSuccess:()=>ZodMiniSuccess,ZodMiniSymbol:()=>ZodMiniSymbol,ZodMiniTemplateLiteral:()=>ZodMiniTemplateLiteral,ZodMiniTransform:()=>ZodMiniTransform,ZodMiniTuple:()=>ZodMiniTuple,ZodMiniType:()=>ZodMiniType,ZodMiniULID:()=>ZodMiniULID,ZodMiniURL:()=>ZodMiniURL,ZodMiniUUID:()=>ZodMiniUUID,ZodMiniUndefined:()=>ZodMiniUndefined,ZodMiniUnion:()=>ZodMiniUnion,ZodMiniUnknown:()=>ZodMiniUnknown,ZodMiniVoid:()=>ZodMiniVoid,ZodMiniXID:()=>ZodMiniXID,ZodMiniXor:()=>ZodMiniXor,_default:()=>_default2,_function:()=>_function,address:()=>address,amount:()=>amount,any:()=>any,array:()=>array,base64:()=>base642,base64url:()=>base64url2,bigint:()=>bigint2,boolean:()=>boolean2,catch:()=>_catch2,catchall:()=>catchall,check:()=>check,cidrv4:()=>cidrv42,cidrv6:()=>cidrv62,clone:()=>clone,codec:()=>codec,coerce:()=>coerce_exports,config:()=>config,core:()=>core_exports2,cuid:()=>cuid3,cuid2:()=>cuid22,custom:()=>custom,date:()=>date2,datetime:()=>datetime3,datetimeInput:()=>datetimeInput,decode:()=>decode,decodeAsync:()=>decodeAsync,describe:()=>describe2,discriminatedUnion:()=>discriminatedUnion,e164:()=>e1642,email:()=>email2,emoji:()=>emoji2,encode:()=>encode,encodeAsync:()=>encodeAsync,endsWith:()=>_endsWith,enum:()=>_enum2,exactOptional:()=>exactOptional,extend:()=>extend2,file:()=>file,flattenError:()=>flattenError,float32:()=>float32,float64:()=>float64,formatError:()=>formatError,function:()=>_function,globalRegistry:()=>globalRegistry,gt:()=>_gt,gte:()=>_gte,guid:()=>guid2,hash:()=>hash2,hex:()=>hex2,hostname:()=>hostname3,httpUrl:()=>httpUrl,includes:()=>_includes,instanceof:()=>_instanceof,int:()=>int,int32:()=>int32,int64:()=>int64,intersection:()=>intersection,invertCodec:()=>invertCodec,ipv4:()=>ipv42,ipv6:()=>ipv62,iso:()=>iso_exports,json:()=>json2,jwt:()=>jwt,keyof:()=>keyof,ksuid:()=>ksuid2,lazy:()=>_lazy2,length:()=>_length,literal:()=>literal,locales:()=>locales_exports,looseObject:()=>looseObject,looseRecord:()=>looseRecord,lowercase:()=>_lowercase,lt:()=>_lt,lte:()=>_lte,mac:()=>mac2,map:()=>map,maxLength:()=>_maxLength,maxSize:()=>_maxSize,maximum:()=>_lte,merge:()=>merge2,meta:()=>meta2,mime:()=>_mime,minLength:()=>_minLength,minSize:()=>_minSize,minimum:()=>_gte,multipleOf:()=>_multipleOf,nan:()=>nan,nanoid:()=>nanoid2,nativeEnum:()=>nativeEnum,negative:()=>_negative,never:()=>never,nonnegative:()=>_nonnegative,nonoptional:()=>nonoptional,nonpositive:()=>_nonpositive,normalize:()=>_normalize,null:()=>_null3,nullable:()=>nullable,nullish:()=>nullish2,number:()=>number2,object:()=>object,omit:()=>omit2,optional:()=>optional,overwrite:()=>_overwrite,parse:()=>parse2,parseAsync:()=>parseAsync,partial:()=>partial2,partialRecord:()=>partialRecord,period:()=>period,pick:()=>pick2,pipe:()=>pipe,positive:()=>_positive,prefault:()=>prefault,prettifyError:()=>prettifyError,promise:()=>promise,property:()=>_property,readonly:()=>readonly,record:()=>record,refine:()=>refine,regex:()=>_regex,regexes:()=>regexes_exports,registry:()=>registry,required:()=>required2,safeDecode:()=>safeDecode,safeDecodeAsync:()=>safeDecodeAsync,safeEncode:()=>safeEncode,safeEncodeAsync:()=>safeEncodeAsync,safeExtend:()=>safeExtend2,safeParse:()=>safeParse,safeParseAsync:()=>safeParseAsync,set:()=>set,signature:()=>signature,size:()=>_size,startsWith:()=>_startsWith,strictObject:()=>strictObject,string:()=>string2,stringFormat:()=>stringFormat,stringbool:()=>stringbool,success:()=>success,superRefine:()=>superRefine,symbol:()=>symbol,templateLiteral:()=>templateLiteral,toDate:()=>toDate,toDatetimeString:()=>toDatetimeString,toJSONSchema:()=>toJSONSchema,toLowerCase:()=>_toLowerCase,toUpperCase:()=>_toUpperCase,transform:()=>transform,treeifyError:()=>treeifyError,trim:()=>_trim,tuple:()=>tuple,uint32:()=>uint32,uint64:()=>uint64,ulid:()=>ulid2,undefined:()=>_undefined3,union:()=>union,unknown:()=>unknown,unwrapOptional:()=>unwrapOptional,uppercase:()=>_uppercase,url:()=>url,util:()=>util_exports,uuid:()=>uuid2,uuidv4:()=>uuidv4,uuidv6:()=>uuidv6,uuidv7:()=>uuidv7,void:()=>_void2,xid:()=>xid2,xor:()=>xor,z:()=>external_exports});function amount(){return external_exports.string().check(external_exports.regex(/^\d+(\.\d+)?$/,"Invalid amount"))}function datetime3(){return external_exports.string().check(external_exports.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,"Invalid ISO 8601 datetime"))}function datetimeInput(message2="Invalid ISO 8601 datetime"){return external_exports.pipe(external_exports.union([datetime3(),external_exports.custom(value=>value instanceof Date)]),external_exports.transform(toDate)).check(external_exports.refine(value=>Number.isFinite(value.getTime()),message2))}function toDate(value){return value instanceof Date?value:new Date(value)}function toDatetimeString(value){if(!(value instanceof Date))return value;if(!Number.isFinite(value.getTime()))return"Invalid Date";return value.toISOString()}function address(){return external_exports.string().check(external_exports.regex(/^0x[0-9a-fA-F]{40}$/,"Invalid address"))}function hash2(){return external_exports.string().check(external_exports.regex(/^0x[0-9a-fA-F]{64}$/,"Invalid hash"))}function period(){return external_exports.string().check(external_exports.regex(/^(day|week|month|year|\d+)$/,"Invalid period"))}function signature(){return external_exports.string().check(external_exports.regex(/^0x[0-9a-fA-F]+$/,"Invalid signature"))}function unwrapOptional(schema){if(schema._zod.def.type==="optional")return schema._zod.def.innerType;return schema}var init_zod=__esm({"node_modules/mppx/dist/zod.js"(){"use strict";init_mini();init_mini()}});var Challenge_exports={};__export(Challenge_exports,{Schema:()=>Schema,deserialize:()=>deserialize2,deserializeList:()=>deserializeList,from:()=>from4,fromHeaders:()=>fromHeaders,fromHeadersList:()=>fromHeadersList,fromMethod:()=>fromMethod2,fromResponse:()=>fromResponse,fromResponseList:()=>fromResponseList,meta:()=>meta3,serialize:()=>serialize2,verify:()=>verify2});function from4(parameters,options){void options;const{description,digest,meta:meta4,method:methodName,intent,realm,request,secretKey}=parameters;const expires=parameters.expires?toDatetimeString(parameters.expires):void 0;const opaque=parameters.opaque??(meta4!==void 0?serialize(meta4):void 0);const id=secretKey?computeId({...parameters,expires,...meta4!==void 0&&{meta:meta4},opaque},{secretKey}):parameters.id;return Schema.parse({id,realm,method:methodName,intent,request,...description&&{description},...digest&&{digest},...expires&&{expires},...meta4!==void 0&&{meta:meta4},...opaque!==void 0&&{opaque}})}function fromMethod2(method,parameters){const{name:methodName,intent}=method;const{description,digest,expires,id,meta:meta4,realm,secretKey}=parameters;const request=fromMethod(method,parameters.request);return from4({...id!==void 0?{id}:{secretKey},realm,method:methodName,intent,request,description,digest,expires,meta:meta4})}function serialize2(challenge){const parts=[authParam("id",challenge.id),authParam("realm",challenge.realm),authParam("method",challenge.method),authParam("intent",challenge.intent),authParam("request",serialize(challenge.request))];if(challenge.description!==void 0)parts.push(authParam("description",challenge.description));if(challenge.digest!==void 0)parts.push(authParam("digest",challenge.digest));if(challenge.expires!==void 0)parts.push(authParam("expires",challenge.expires));if(challenge.opaque!==void 0)parts.push(authParam("opaque",challenge.opaque));else if(challenge.meta!==void 0)parts.push(authParam("opaque",serialize(challenge.meta)));return`${Schemes.payment} ${parts.join(", ")}`}function authParam(name,value){if(/[\r\n]/.test(value))throw new Error("Invalid quoted-string value.");return`${name}="${value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function deserialize2(value,options){const params=extractPaymentAuthParams(value);if(!params)throw new Error("Missing Payment scheme.");const result=parseAuthParams(params);const{request,opaque,...rest}=result;if(!request)throw new Error("Missing request parameter.");if(request.length>maxRequestParameterLength)throw new Error("Request parameter too large.");if(rest.method&&!/^[a-z][a-z0-9:_-]*$/.test(rest.method))throw new Error(`Invalid method: "${rest.method}". Must be lowercase per spec.`);return from4({...rest,request:deserialize(request),...opaque&&{opaque}},options)}function extractPaymentAuthParams(header){const token=Schemes.payment;let inQuotes=false;let escaped=false;for(let i=0;i<header.length;i++){const char=header[i];if(inQuotes){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char==='"')inQuotes=false;continue}if(char==='"'){inQuotes=true;continue}if(!startsWithSchemeToken(header,i,token))continue;const prefix=header.slice(0,i);if(prefix.trim()&&!prefix.trimEnd().endsWith(","))continue;let paramsStart=i+token.length;while(paramsStart<header.length&&/\s/.test(header[paramsStart]??""))paramsStart++;return header.slice(paramsStart)}return null}function parseAuthParams(input){const result={};let i=0;while(i<input.length){while(i<input.length&&/[\s,]/.test(input[i]??""))i++;if(i>=input.length)break;const keyStart=i;while(i<input.length&&/[A-Za-z0-9_-]/.test(input[i]??""))i++;const key=input.slice(keyStart,i);if(!key)throw new Error("Malformed auth-param.");while(i<input.length&&/\s/.test(input[i]??""))i++;if(input[i]!=="=")break;i++;while(i<input.length&&/\s/.test(input[i]??""))i++;const[value,nextIndex]=readAuthParamValue(input,i);i=nextIndex;if(key in result)throw new Error(`Duplicate parameter: ${key}`);result[key]=value}return result}function readAuthParamValue(input,start){if(input[start]==='"')return readQuotedAuthParamValue(input,start+1);let i=start;while(i<input.length&&input[i]!==",")i++;return[input.slice(start,i).trim(),i]}function readQuotedAuthParamValue(input,start){let i=start;let escaped=false;let segmentStart=start;let parts;while(i<input.length){const char=input[i];i++;if(escaped){parts??=[];parts.push(char);segmentStart=i;escaped=false;continue}if(char==="\\"){parts??=[];parts.push(input.slice(segmentStart,i-1));segmentStart=i;escaped=true;continue}if(char==='"'){const value=parts?[...parts,input.slice(segmentStart,i-1)].join(""):input.slice(start,i-1);return[value,i]}}throw new Error("Unterminated quoted-string.")}function startsWithSchemeToken(value,index,token){if(!value.slice(index).toLowerCase().startsWith(token.toLowerCase()))return false;const next=value[index+token.length];return Boolean(next&&/\s/.test(next))}function fromHeaders(headers,options){const header=headers.get(Headers2.wwwAuthenticate);if(!header)throw new Error(`Missing ${Headers2.wwwAuthenticate} header.`);return deserialize2(header,options)}function fromResponse(response,options){if(response.status!==402)throw new Error("Response status is not 402.");return fromHeaders(response.headers,options)}function fromResponseList(response,options){if(response.status!==402)throw new Error("Response status is not 402.");return fromHeadersList(response.headers,options)}function fromHeadersList(headers,options){const header=headers.get(Headers2.wwwAuthenticate);if(!header)throw new Error(`Missing ${Headers2.wwwAuthenticate} header.`);return deserializeList(header,options)}function deserializeList(value,options){const starts=[];const schemePattern=new RegExp(`${Schemes.payment}\\s+`,"gi");for(const match of value.matchAll(schemePattern)){starts.push(match.index)}if(starts.length===0)throw new Error("No Payment schemes found.");return starts.map((start,i)=>{const end=i+1<starts.length?starts[i+1]:value.length;const chunk=value.slice(start,end).replace(/,\s*$/,"");return deserialize2(chunk,options)})}function verify2(challenge,options){const expectedId=computeId(challenge,options);return constantTimeEqual(challenge.id,expectedId)}function meta3(challenge){return challenge.meta}function idBindingInput(challenge){return[challenge.realm,challenge.method,challenge.intent,serialize(challenge.request),challenge.expires??"",challenge.digest??"",challenge.opaque??(challenge.meta?serialize(challenge.meta):"")].join("|")}function computeId(challenge,options){const input=idBindingInput(challenge);const key=Bytes_exports.fromString(options.secretKey);const data=Bytes_exports.fromString(input);const mac3=Hash_exports.hmac256(key,data,{as:"Bytes"});return Base64_exports.fromBytes(mac3,{url:true,pad:false})}var maxRequestParameterLength,Schema;var init_Challenge=__esm({"node_modules/mppx/dist/Challenge.js"(){"use strict";init_esm2();init_Constants();init_constantTimeEqual();init_PaymentRequest();init_zod();maxRequestParameterLength=16*1024;Schema=object({description:optional(string2()),digest:optional(string2().check(_regex(/^sha-256=/,"Invalid digest format"))),expires:optional(datetime3()),id:string2().check(_minLength(1)),intent:string2(),method:string2(),meta:optional(record(string2(),string2())),opaque:optional(string2()),realm:string2(),request:record(string2(),unknown())})}});var Credential_exports={};__export(Credential_exports,{InvalidCredentialEncodingError:()=>InvalidCredentialEncodingError,MissingAuthorizationHeaderError:()=>MissingAuthorizationHeaderError,MissingPaymentSchemeError:()=>MissingPaymentSchemeError,deserialize:()=>deserialize3,extractPaymentScheme:()=>extractPaymentScheme,from:()=>from5,fromRequest:()=>fromRequest,serialize:()=>serialize3});function deserialize3(value){const prefixMatch=value.match(new RegExp(`^${Schemes.payment}\\s+(.+)$`,"i"));if(!prefixMatch?.[1])throw new MissingPaymentSchemeError;try{const json3=Base64_exports.toString(prefixMatch[1]);const parsed=JSON.parse(json3);const{opaque:challengeOpaque,request,meta:_meta,...challengeFields}=parsed.challenge;const{meta:meta4,opaque}=normalizeCredentialOpaque(challengeOpaque);const challenge=Schema.parse({...challengeFields,...meta4!==void 0&&{meta:meta4},...opaque!==void 0&&{opaque},request:deserialize(request)});return{challenge,payload:parsed.payload,...parsed.source&&{source:parsed.source}}}catch{throw new InvalidCredentialEncodingError}}function normalizeCredentialOpaque(value){if(value===void 0)return{};if(typeof value==="string")return{opaque:value};if(!isStringRecord(value))throw new Error("Invalid opaque.");return{meta:value,opaque:serialize(value)}}function isStringRecord(value){if(typeof value!=="object"||value===null||Array.isArray(value))return false;return Object.values(value).every(entry=>typeof entry==="string")}function from5(parameters){const{challenge,payload,source}=parameters;return{challenge,payload,...source&&{source}}}function fromRequest(request){const header=request.headers.get(Headers2.authorization);if(!header)throw new MissingAuthorizationHeaderError;const payment=extractPaymentScheme(header);if(!payment)throw new MissingPaymentSchemeError;return deserialize3(payment)}function serialize3(credential){const{meta:meta4,opaque,request,...challenge}=credential.challenge;const wireOpaque=opaque??(meta4!==void 0?serialize(meta4):void 0);const wire={challenge:{...challenge,...wireOpaque!==void 0&&{opaque:wireOpaque},request:serialize(request)},payload:credential.payload,...credential.source&&{source:credential.source}};const json3=JSON.stringify(wire);const encoded=Base64_exports.fromString(json3,{pad:false,url:true});return`${Schemes.payment} ${encoded}`}function extractPaymentScheme(header){const schemes2=header.split(",").map(s=>s.trim());return schemes2.find(s=>new RegExp(`^${Schemes.payment}\\s+`,"i").test(s))??null}var MissingAuthorizationHeaderError,MissingPaymentSchemeError,InvalidCredentialEncodingError;var init_Credential=__esm({"node_modules/mppx/dist/Credential.js"(){"use strict";init_esm2();init_Challenge();init_Constants();init_PaymentRequest();MissingAuthorizationHeaderError=class extends Error{name="MissingAuthorizationHeaderError";constructor(){super("Missing Authorization header.")}};MissingPaymentSchemeError=class extends Error{name="MissingPaymentSchemeError";constructor(){super("Missing Payment scheme.")}};InvalidCredentialEncodingError=class extends Error{name="InvalidCredentialEncodingError";constructor(){super("Invalid base64url or JSON.")}}}});var Errors_exports2={};__export(Errors_exports2,{AmountExceedsDepositError:()=>AmountExceedsDepositError,BadRequestError:()=>BadRequestError,ChannelClosedError:()=>ChannelClosedError,ChannelNotFoundError:()=>ChannelNotFoundError,DeltaTooSmallError:()=>DeltaTooSmallError,Hints:()=>Hints,InsufficientBalanceError:()=>InsufficientBalanceError,InvalidChallengeError:()=>InvalidChallengeError,InvalidPayloadError:()=>InvalidPayloadError,InvalidSignatureError:()=>InvalidSignatureError,MalformedCredentialError:()=>MalformedCredentialError,PaymentActionRequiredError:()=>PaymentActionRequiredError,PaymentError:()=>PaymentError,PaymentExpiredError:()=>PaymentExpiredError,PaymentInsufficientError:()=>PaymentInsufficientError,PaymentMethodUnsupportedError:()=>PaymentMethodUnsupportedError,PaymentRequiredError:()=>PaymentRequiredError,SignerMismatchError:()=>SignerMismatchError,VerificationFailedError:()=>VerificationFailedError});var Hints,PaymentError,MalformedCredentialError,InvalidChallengeError,VerificationFailedError,PaymentActionRequiredError,PaymentExpiredError,PaymentRequiredError,InvalidPayloadError,BadRequestError,PaymentInsufficientError,PaymentMethodUnsupportedError,InsufficientBalanceError,InvalidSignatureError,SignerMismatchError,AmountExceedsDepositError,DeltaTooSmallError,ChannelNotFoundError,ChannelClosedError;var init_Errors2=__esm({"node_modules/mppx/dist/Errors.js"(){"use strict";Hints={paymentRequired:"Use a supported wallet to pay for this resource using one of the supported payment methods returned in the WWW-Authenticate header. See https://mpp.dev/tools/wallet.md",malformedCredential:"Use a supported wallet to construct valid credentials for one of the supported payment methods returned in the WWW-Authenticate header. See https://mpp.dev/tools/wallet.md",methodUnsupported:"Use a supported wallet to pay for this resource using one of the supported payment methods returned in the WWW-Authenticate header. See https://mpp.dev/tools/wallet.md"};PaymentError=class extends Error{details;status=402;hint;constructor(message2,options={}){super(message2);this.details=options.details}toProblemDetails(challengeId){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...challengeId&&{challengeId}}}};MalformedCredentialError=class extends PaymentError{name="MalformedCredentialError";title="Malformed Credential";status=402;type="https://paymentauth.org/problems/malformed-credential";hint=Hints.malformedCredential;constructor(options={}){const{reason}=options;super(reason?`Credential is malformed: ${reason}.`:"Credential is malformed.")}};InvalidChallengeError=class extends PaymentError{name="InvalidChallengeError";title="Invalid Challenge";status=402;type="https://paymentauth.org/problems/invalid-challenge";constructor(options={}){const{id,reason}=options;const idPart=id?` "${id}"`:"";const reasonPart=reason?`: ${reason}`:"";super(`Challenge${idPart} is invalid${reasonPart}.`)}};VerificationFailedError=class extends PaymentError{name="VerificationFailedError";title="Verification Failed";type="https://paymentauth.org/problems/verification-failed";constructor(options={}){const{details,reason}=options;super(reason?`Payment verification failed: ${reason}.`:"Payment verification failed.",{details})}};PaymentActionRequiredError=class extends PaymentError{name="PaymentActionRequiredError";title="Payment Action Required";type="https://paymentauth.org/problems/payment-action-required";constructor(options={}){const{reason}=options;super(reason?`Payment requires action: ${reason}.`:"Payment requires action.")}};PaymentExpiredError=class extends PaymentError{name="PaymentExpiredError";title="Payment Expired";type="https://paymentauth.org/problems/payment-expired";constructor(options={}){const{expires}=options;super(expires?`Payment expired at ${expires}.`:"Payment has expired.")}};PaymentRequiredError=class extends PaymentError{name="PaymentRequiredError";title="Payment Required";type="https://paymentauth.org/problems/payment-required";hint=Hints.paymentRequired;constructor(options={}){const{description}=options;const parts=["Payment is required"];if(description)parts.push(`(${description})`);super(`${parts.join(" ")}.`)}};InvalidPayloadError=class extends PaymentError{name="InvalidPayloadError";title="Invalid Payload";type="https://paymentauth.org/problems/invalid-payload";constructor(options={}){const{reason}=options;super(reason?`Credential payload is invalid: ${reason}.`:"Credential payload is invalid.")}};BadRequestError=class extends PaymentError{name="BadRequestError";title="Bad Request";status=400;type="https://paymentauth.org/problems/bad-request";constructor(options={}){const{reason}=options;super(reason?`Bad request: ${reason}.`:"Bad request.")}};PaymentInsufficientError=class extends PaymentError{name="PaymentInsufficientError";title="Payment Insufficient";type="https://paymentauth.org/problems/payment-insufficient";constructor(options={}){const{reason}=options;super(reason?`Payment insufficient: ${reason}.`:"Payment amount is insufficient.")}};PaymentMethodUnsupportedError=class extends PaymentError{name="PaymentMethodUnsupportedError";title="Method Unsupported";status=400;type="https://paymentauth.org/problems/method-unsupported";hint=Hints.methodUnsupported;constructor(options={}){const{method}=options;super(method?`Payment method "${method}" is not supported.`:"Payment method is not supported.")}};InsufficientBalanceError=class extends PaymentError{name="InsufficientBalanceError";title="Insufficient Balance";status=402;type="https://paymentauth.org/problems/session/insufficient-balance";constructor(options={}){const{reason}=options;super(reason?`Insufficient balance: ${reason}.`:"Insufficient balance.")}};InvalidSignatureError=class extends PaymentError{name="InvalidSignatureError";title="Invalid Signature";status=402;type="https://paymentauth.org/problems/session/invalid-signature";constructor(options={}){const{reason}=options;super(reason?`Invalid signature: ${reason}.`:"Invalid signature.")}};SignerMismatchError=class extends PaymentError{name="SignerMismatchError";title="Signer Mismatch";status=402;type="https://paymentauth.org/problems/session/signer-mismatch";constructor(options={}){const{reason}=options;super(reason?`Signer mismatch: ${reason}.`:"Signer is not authorized for this channel.")}};AmountExceedsDepositError=class extends PaymentError{name="AmountExceedsDepositError";title="Amount Exceeds Deposit";status=402;type="https://paymentauth.org/problems/session/amount-exceeds-deposit";constructor(options={}){const{reason}=options;super(reason?`Amount exceeds deposit: ${reason}.`:"Voucher amount exceeds channel deposit.")}};DeltaTooSmallError=class extends PaymentError{name="DeltaTooSmallError";title="Delta Too Small";status=402;type="https://paymentauth.org/problems/session/delta-too-small";constructor(options={}){const{reason}=options;super(reason?`Delta too small: ${reason}.`:"Amount increase below minimum voucher delta.")}};ChannelNotFoundError=class extends PaymentError{name="ChannelNotFoundError";title="Channel Not Found";status=410;type="https://paymentauth.org/problems/session/channel-not-found";constructor(options={}){const{reason}=options;super(reason?`Channel not found: ${reason}.`:"No channel with this ID exists.")}};ChannelClosedError=class extends PaymentError{name="ChannelClosedError";title="Channel Closed";status=410;type="https://paymentauth.org/problems/session/channel-finalized";constructor(options={}){const{reason}=options;super(reason?`Channel closed: ${reason}.`:"Channel is closed.")}}}});var Expires_exports={};__export(Expires_exports,{assert:()=>assert5,days:()=>days,hours:()=>hours,minutes:()=>minutes,months:()=>months,seconds:()=>seconds,weeks:()=>weeks,years:()=>years});function assert5(expires,challengeId){if(!expires)throw new InvalidChallengeError({...challengeId&&{id:challengeId},reason:"missing required expires field"});if(Number.isNaN(new Date(expires).getTime()))throw new InvalidChallengeError({...challengeId&&{id:challengeId},reason:"malformed expires timestamp"});if(new Date(expires)<new Date)throw new PaymentExpiredError({expires})}function days(n){return new Date(Date.now()+n*24*60*60*1e3).toISOString()}function hours(n){return new Date(Date.now()+n*60*60*1e3).toISOString()}function minutes(n){return new Date(Date.now()+n*60*1e3).toISOString()}function months(n){return new Date(Date.now()+n*30*24*60*60*1e3).toISOString()}function seconds(n){return new Date(Date.now()+n*1e3).toISOString()}function weeks(n){return new Date(Date.now()+n*7*24*60*60*1e3).toISOString()}function years(n){return new Date(Date.now()+n*365*24*60*60*1e3).toISOString()}var init_Expires=__esm({"node_modules/mppx/dist/Expires.js"(){"use strict";init_Errors2()}});function isHex(value,{strict=true}={}){if(!value)return false;if(typeof value!=="string")return false;return strict?/^0x[0-9a-fA-F]*$/.test(value):value.startsWith("0x")}var init_isHex=__esm({"node_modules/viem/_esm/utils/data/isHex.js"(){"use strict"}});function size3(value){if(isHex(value,{strict:false}))return Math.ceil((value.length-2)/2);return value.length}var init_size=__esm({"node_modules/viem/_esm/utils/data/size.js"(){"use strict";init_isHex()}});var version3;var init_version2=__esm({"node_modules/viem/_esm/errors/version.js"(){"use strict";version3="2.55.11"}});function walk2(err,fn){if(fn?.(err))return err;if(err&&typeof err==="object"&&"cause"in err&&err.cause!==void 0)return walk2(err.cause,fn);return fn?null:err}var errorConfig,BaseError3;var init_base2=__esm({"node_modules/viem/_esm/errors/base.js"(){"use strict";init_version2();errorConfig={getDocsUrl:({docsBaseUrl,docsPath="",docsSlug})=>docsPath?`${docsBaseUrl??"https://viem.sh"}${docsPath}${docsSlug?`#${docsSlug}`:""}`:void 0,version:`viem@${version3}`};BaseError3=class _BaseError extends Error{constructor(shortMessage,args={}){const details=(()=>{if(args.cause instanceof _BaseError)return args.cause.details;if(args.cause?.message)return args.cause.message;return args.details})();const docsPath=(()=>{if(args.cause instanceof _BaseError)return args.cause.docsPath||args.docsPath;return args.docsPath})();const docsUrl=errorConfig.getDocsUrl?.({...args,docsPath});const message2=[shortMessage||"An error occurred.","",...args.metaMessages?[...args.metaMessages,""]:[],...docsUrl?[`Docs: ${docsUrl}`]:[],...details?[`Details: ${details}`]:[],...errorConfig.version?[`Version: ${errorConfig.version}`]:[]].join("\n");super(message2,args.cause?{cause:args.cause}:void 0);Object.defineProperty(this,"details",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"docsPath",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"metaMessages",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"shortMessage",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"version",{enumerable:true,configurable:true,writable:true,value:void 0});Object.defineProperty(this,"name",{enumerable:true,configurable:true,writable:true,value:"BaseError"});this.details=details;this.docsPath=docsPath;this.metaMessages=args.metaMessages;this.name=args.name??this.name;this.shortMessage=shortMessage;this.version=version3}walk(fn){return walk2(this,fn)}}}});var SizeExceedsPaddingSizeError3;var init_data=__esm({"node_modules/viem/_esm/errors/data.js"(){"use strict";init_base2();SizeExceedsPaddingSizeError3=class extends BaseError3{constructor({size:size4,targetSize,type}){super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size4}) exceeds padding size (${targetSize}).`,{name:"SizeExceedsPaddingSizeError"})}}}});function pad3(hexOrBytes,{dir,size:size4=32}={}){if(typeof hexOrBytes==="string")return padHex(hexOrBytes,{dir,size:size4});return padBytes(hexOrBytes,{dir,size:size4})}function padHex(hex_,{dir,size:size4=32}={}){if(size4===null)return hex_;const hex3=hex_.replace("0x","");if(hex3.length>size4*2)throw new SizeExceedsPaddingSizeError3({size:Math.ceil(hex3.length/2),targetSize:size4,type:"hex"});return`0x${hex3[dir==="right"?"padEnd":"padStart"](size4*2,"0")}`}function padBytes(bytes,{dir,size:size4=32}={}){if(size4===null)return bytes;if(bytes.length>size4)throw new SizeExceedsPaddingSizeError3({size:bytes.length,targetSize:size4,type:"bytes"});const paddedBytes=new Uint8Array(size4);for(let i=0;i<size4;i++){const padEnd=dir==="right";paddedBytes[padEnd?i:size4-i-1]=bytes[padEnd?i:bytes.length-i-1]}return paddedBytes}var init_pad=__esm({"node_modules/viem/_esm/utils/data/pad.js"(){"use strict";init_data()}});var IntegerOutOfRangeError2,SizeOverflowError3;var init_encoding=__esm({"node_modules/viem/_esm/errors/encoding.js"(){"use strict";init_base2();IntegerOutOfRangeError2=class extends BaseError3{constructor({max,min,signed,size:size4,value}){super(`Number "${value}" is not in safe ${size4?`${size4*8}-bit ${signed?"signed":"unsigned"} `:""}integer range ${max?`(${min} to ${max})`:`(above ${min})`}`,{name:"IntegerOutOfRangeError"})}};SizeOverflowError3=class extends BaseError3{constructor({givenSize,maxSize}){super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`,{name:"SizeOverflowError"})}}}});function assertSize3(hexOrBytes,{size:size4}){if(size3(hexOrBytes)>size4)throw new SizeOverflowError3({givenSize:size3(hexOrBytes),maxSize:size4})}var init_fromHex=__esm({"node_modules/viem/_esm/utils/encoding/fromHex.js"(){"use strict";init_encoding();init_size()}});function toHex3(value,opts={}){if(typeof value==="number"||typeof value==="bigint")return numberToHex(value,opts);if(typeof value==="string"){return stringToHex(value,opts)}if(typeof value==="boolean")return boolToHex(value,opts);return bytesToHex(value,opts)}function boolToHex(value,opts={}){const hex3=`0x${Number(value)}`;if(typeof opts.size==="number"){assertSize3(hex3,{size:opts.size});return pad3(hex3,{size:opts.size})}return hex3}function bytesToHex(value,opts={}){let string4="";for(let i=0;i<value.length;i++){string4+=hexes2[value[i]]}const hex3=`0x${string4}`;if(typeof opts.size==="number"){assertSize3(hex3,{size:opts.size});return pad3(hex3,{dir:"right",size:opts.size})}return hex3}function numberToHex(value_,opts={}){const{signed,size:size4}=opts;const value=BigInt(value_);let maxValue;if(size4){if(signed)maxValue=(1n<<BigInt(size4)*8n-1n)-1n;else maxValue=2n**(BigInt(size4)*8n)-1n}else if(typeof value_==="number"){maxValue=BigInt(Number.MAX_SAFE_INTEGER)}const minValue=typeof maxValue==="bigint"&&signed?-maxValue-1n:0;if(maxValue&&value>maxValue||value<minValue){const suffix=typeof value_==="bigint"?"n":"";throw new IntegerOutOfRangeError2({max:maxValue?`${maxValue}${suffix}`:void 0,min:`${minValue}${suffix}`,signed,size:size4,value:`${value_}${suffix}`})}const hex3=`0x${(signed&&value<0?(1n<<BigInt(size4*8))+BigInt(value):value).toString(16)}`;if(size4)return pad3(hex3,{size:size4});return hex3}function stringToHex(value_,opts={}){const value=encoder4.encode(value_);return bytesToHex(value,opts)}var hexes2,encoder4;var init_toHex=__esm({"node_modules/viem/_esm/utils/encoding/toHex.js"(){"use strict";init_encoding();init_pad();init_fromHex();hexes2=Array.from({length:256},(_v,i)=>i.toString(16).padStart(2,"0"));encoder4=new TextEncoder}});function toBytes4(value,opts={}){if(typeof value==="number"||typeof value==="bigint")return numberToBytes(value,opts);if(typeof value==="boolean")return boolToBytes(value,opts);if(isHex(value))return hexToBytes(value,opts);return stringToBytes(value,opts)}function boolToBytes(value,opts={}){const bytes=new Uint8Array(1);bytes[0]=Number(value);if(typeof opts.size==="number"){assertSize3(bytes,{size:opts.size});return pad3(bytes,{size:opts.size})}return bytes}function charCodeToBase162(char){if(char>=charCodeMap2.zero&&char<=charCodeMap2.nine)return char-charCodeMap2.zero;if(char>=charCodeMap2.A&&char<=charCodeMap2.F)return char-(charCodeMap2.A-10);if(char>=charCodeMap2.a&&char<=charCodeMap2.f)return char-(charCodeMap2.a-10);return void 0}function hexToBytes(hex_,opts={}){let hex3=hex_;if(opts.size){assertSize3(hex3,{size:opts.size});hex3=pad3(hex3,{dir:"right",size:opts.size})}let hexString=hex3.slice(2);if(hexString.length%2)hexString=`0${hexString}`;const length=hexString.length/2;const bytes=new Uint8Array(length);for(let index=0,j2=0;index<length;index++){const nibbleLeft=charCodeToBase162(hexString.charCodeAt(j2++));const nibbleRight=charCodeToBase162(hexString.charCodeAt(j2++));if(nibbleLeft===void 0||nibbleRight===void 0){throw new BaseError3(`Invalid byte sequence ("${hexString[j2-2]}${hexString[j2-1]}" in "${hexString}").`)}bytes[index]=nibbleLeft*16+nibbleRight}return bytes}function numberToBytes(value,opts){const hex3=numberToHex(value,opts);return hexToBytes(hex3)}function stringToBytes(value,opts={}){const bytes=encoder5.encode(value);if(typeof opts.size==="number"){assertSize3(bytes,{size:opts.size});return pad3(bytes,{dir:"right",size:opts.size})}return bytes}var encoder5,charCodeMap2;var init_toBytes=__esm({"node_modules/viem/_esm/utils/encoding/toBytes.js"(){"use strict";init_base2();init_isHex();init_pad();init_fromHex();init_toHex();encoder5=new TextEncoder;charCodeMap2={zero:48,nine:57,A:65,F:70,a:97,f:102}}});function fromBig2(n,le=false){if(le)return{h:Number(n&U32_MASK642),l:Number(n>>_32n2&U32_MASK642)};return{h:Number(n>>_32n2&U32_MASK642)|0,l:Number(n&U32_MASK642)|0}}function split2(lst,le=false){const len=lst.length;let Ah=new Uint32Array(len);let Al=new Uint32Array(len);for(let i=0;i<len;i++){const{h,l}=fromBig2(lst[i],le);[Ah[i],Al[i]]=[h,l]}return[Ah,Al]}var U32_MASK642,_32n2,rotlSH2,rotlSL2,rotlBH2,rotlBL2;var init_u642=__esm({"node_modules/viem/node_modules/@noble/hashes/esm/_u64.js"(){"use strict";U32_MASK642=BigInt(2**32-1);_32n2=BigInt(32);rotlSH2=(h,l,s)=>h<<s|l>>>32-s;rotlSL2=(h,l,s)=>l<<s|h>>>32-s;rotlBH2=(h,l,s)=>l<<s-32|h>>>64-s;rotlBL2=(h,l,s)=>h<<s-32|l>>>64-s}});function isBytes4(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function anumber4(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function abytes3(b2,...lengths){if(!isBytes4(b2))throw new Error("Uint8Array expected");if(lengths.length>0&&!lengths.includes(b2.length))throw new Error("Uint8Array expected of length "+lengths+", got length="+b2.length)}function aexists3(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function aoutput3(out,instance){abytes3(out);const min=instance.outputLen;if(out.length<min){throw new Error("digestInto() expects output buffer of length at least "+min)}}function u322(arr){return new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4))}function clean3(...arrays){for(let i=0;i<arrays.length;i++){arrays[i].fill(0)}}function byteSwap2(word){return word<<24&4278190080|word<<8&16711680|word>>>8&65280|word>>>24&255}function byteSwap322(arr){for(let i=0;i<arr.length;i++){arr[i]=byteSwap2(arr[i])}return arr}function utf8ToBytes2(str2){if(typeof str2!=="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(str2))}function toBytes5(data){if(typeof data==="string")data=utf8ToBytes2(data);abytes3(data);return data}function createHasher3(hashCons){const hashC=msg=>hashCons().update(toBytes5(msg)).digest();const tmp=hashCons();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashCons();return hashC}var isLE2,swap32IfBE2,Hash2;var init_utils4=__esm({"node_modules/viem/node_modules/@noble/hashes/esm/utils.js"(){"use strict";isLE2=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();swap32IfBE2=isLE2?u=>u:byteSwap322;Hash2=class{}}});function keccakP2(s,rounds=24){const B2=new Uint32Array(5*2);for(let round=24-rounds;round<24;round++){for(let x2=0;x2<10;x2++)B2[x2]=s[x2]^s[x2+10]^s[x2+20]^s[x2+30]^s[x2+40];for(let x2=0;x2<10;x2+=2){const idx1=(x2+8)%10;const idx0=(x2+2)%10;const B0=B2[idx0];const B1=B2[idx0+1];const Th=rotlH2(B0,B1,1)^B2[idx1];const Tl=rotlL2(B0,B1,1)^B2[idx1+1];for(let y=0;y<50;y+=10){s[x2+y]^=Th;s[x2+y+1]^=Tl}}let curH=s[2];let curL=s[3];for(let t2=0;t2<24;t2++){const shift=SHA3_ROTL2[t2];const Th=rotlH2(curH,curL,shift);const Tl=rotlL2(curH,curL,shift);const PI=SHA3_PI2[t2];curH=s[PI];curL=s[PI+1];s[PI]=Th;s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x2=0;x2<10;x2++)B2[x2]=s[y+x2];for(let x2=0;x2<10;x2++)s[y+x2]^=~B2[(x2+2)%10]&B2[(x2+4)%10]}s[0]^=SHA3_IOTA_H2[round];s[1]^=SHA3_IOTA_L2[round]}clean3(B2)}var _0n2,_1n2,_2n2,_7n2,_256n2,_0x71n2,SHA3_PI2,SHA3_ROTL2,_SHA3_IOTA2,IOTAS2,SHA3_IOTA_H2,SHA3_IOTA_L2,rotlH2,rotlL2,Keccak2,gen2,keccak_2562;var init_sha32=__esm({"node_modules/viem/node_modules/@noble/hashes/esm/sha3.js"(){"use strict";init_u642();init_utils4();_0n2=BigInt(0);_1n2=BigInt(1);_2n2=BigInt(2);_7n2=BigInt(7);_256n2=BigInt(256);_0x71n2=BigInt(113);SHA3_PI2=[];SHA3_ROTL2=[];_SHA3_IOTA2=[];for(let round=0,R=_1n2,x2=1,y=0;round<24;round++){[x2,y]=[y,(2*x2+3*y)%5];SHA3_PI2.push(2*(5*y+x2));SHA3_ROTL2.push((round+1)*(round+2)/2%64);let t2=_0n2;for(let j2=0;j2<7;j2++){R=(R<<_1n2^(R>>_7n2)*_0x71n2)%_256n2;if(R&_2n2)t2^=_1n2<<(_1n2<<BigInt(j2))-_1n2}_SHA3_IOTA2.push(t2)}IOTAS2=split2(_SHA3_IOTA2,true);SHA3_IOTA_H2=IOTAS2[0];SHA3_IOTA_L2=IOTAS2[1];rotlH2=(h,l,s)=>s>32?rotlBH2(h,l,s):rotlSH2(h,l,s);rotlL2=(h,l,s)=>s>32?rotlBL2(h,l,s):rotlSL2(h,l,s);Keccak2=class _Keccak extends Hash2{constructor(blockLen,suffix,outputLen,enableXOF=false,rounds=24){super();this.pos=0;this.posOut=0;this.finished=false;this.destroyed=false;this.enableXOF=false;this.blockLen=blockLen;this.suffix=suffix;this.outputLen=outputLen;this.enableXOF=enableXOF;this.rounds=rounds;anumber4(outputLen);if(!(0<blockLen&&blockLen<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200);this.state32=u322(this.state)}clone(){return this._cloneInto()}keccak(){swap32IfBE2(this.state32);keccakP2(this.state32,this.rounds);swap32IfBE2(this.state32);this.posOut=0;this.pos=0}update(data){aexists3(this);data=toBytes5(data);abytes3(data);const{blockLen,state}=this;const len=data.length;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);for(let i=0;i<take;i++)state[this.pos++]^=data[pos++];if(this.pos===blockLen)this.keccak()}return this}finish(){if(this.finished)return;this.finished=true;const{state,suffix,pos,blockLen}=this;state[pos]^=suffix;if((suffix&128)!==0&&pos===blockLen-1)this.keccak();state[blockLen-1]^=128;this.keccak()}writeInto(out){aexists3(this,false);abytes3(out);this.finish();const bufferOut=this.state;const{blockLen}=this;for(let pos=0,len=out.length;pos<len;){if(this.posOut>=blockLen)this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos);this.posOut+=take;pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){anumber4(bytes);return this.xofInto(new Uint8Array(bytes))}digestInto(out){aoutput3(out,this);if(this.finished)throw new Error("digest() was already called");this.writeInto(out);this.destroy();return out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true;clean3(this.state)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;to||(to=new _Keccak(blockLen,suffix,outputLen,enableXOF,rounds));to.state32.set(this.state32);to.pos=this.pos;to.posOut=this.posOut;to.finished=this.finished;to.rounds=rounds;to.suffix=suffix;to.outputLen=outputLen;to.enableXOF=enableXOF;to.destroyed=this.destroyed;return to}};gen2=(suffix,blockLen,outputLen)=>createHasher3(()=>new Keccak2(blockLen,suffix,outputLen));keccak_2562=(()=>gen2(1,136,256/8))()}});function keccak2562(value,to_){const to=to_||"hex";const bytes=keccak_2562(isHex(value,{strict:false})?toBytes4(value):value);if(to==="bytes")return bytes;return toHex3(bytes)}var init_keccak256=__esm({"node_modules/viem/_esm/utils/hash/keccak256.js"(){"use strict";init_sha32();init_isHex();init_toBytes();init_toHex()}});var InvalidAddressError2;var init_address=__esm({"node_modules/viem/_esm/errors/address.js"(){"use strict";init_base2();InvalidAddressError2=class extends BaseError3{constructor({address:address3}){super(`Address "${address3}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}}});var LruMap2;var init_lru2=__esm({"node_modules/viem/_esm/utils/lru.js"(){"use strict";LruMap2=class extends Map{constructor(size4){super();Object.defineProperty(this,"maxSize",{enumerable:true,configurable:true,writable:true,value:void 0});this.maxSize=size4}get(key){const value=super.get(key);if(super.has(key)){super.delete(key);super.set(key,value)}return value}set(key,value){if(super.has(key))super.delete(key);super.set(key,value);if(this.maxSize&&this.size>this.maxSize){const firstKey=super.keys().next().value;if(firstKey!==void 0)super.delete(firstKey)}return this}}}});function checksumAddress(address_,chainId){if(checksumAddressCache.has(`${address_}.${chainId}`))return checksumAddressCache.get(`${address_}.${chainId}`);const hexAddress=chainId?`${chainId}${address_.toLowerCase()}`:address_.substring(2).toLowerCase();const hash3=keccak2562(stringToBytes(hexAddress),"bytes");const address3=(chainId?hexAddress.substring(`${chainId}0x`.length):hexAddress).split("");for(let i=0;i<40;i+=2){if(hash3[i>>1]>>4>=8&&address3[i]){address3[i]=address3[i].toUpperCase()}if((hash3[i>>1]&15)>=8&&address3[i+1]){address3[i+1]=address3[i+1].toUpperCase()}}const result=`0x${address3.join("")}`;checksumAddressCache.set(`${address_}.${chainId}`,result);return result}function getAddress(address3,chainId){if(!isAddress(address3,{strict:false}))throw new InvalidAddressError2({address:address3});return checksumAddress(address3,chainId)}var checksumAddressCache;var init_getAddress=__esm({"node_modules/viem/_esm/utils/address/getAddress.js"(){"use strict";init_address();init_toBytes();init_keccak256();init_lru2();init_isAddress();checksumAddressCache=new LruMap2(8192)}});function isAddress(address3,options){const{strict=true}=options??{};const cacheKey=`${address3}.${strict}`;if(isAddressCache.has(cacheKey))return isAddressCache.get(cacheKey);const result=(()=>{if(!addressRegex2.test(address3))return false;if(address3.toLowerCase()===address3)return true;if(strict)return checksumAddress(address3)===address3;return true})();isAddressCache.set(cacheKey,result);return result}var addressRegex2,isAddressCache;var init_isAddress=__esm({"node_modules/viem/_esm/utils/address/isAddress.js"(){"use strict";init_lru2();init_getAddress();addressRegex2=/^0x[a-fA-F0-9]{40}$/;isAddressCache=new LruMap2(8192)}});function from6(value,decimals=0){if(!Number.isInteger(decimals)||decimals<0)throw new InvalidDecimalsError({decimals});if(!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(value))throw new InvalidDecimalNumberError({value});let[integer2="",fraction="0"]=value.split(".");const negative=integer2.startsWith("-");if(negative)integer2=integer2.slice(1);if(integer2==="")integer2="0";fraction=fraction.replace(/(0+)$/,"");if(decimals===0){if(fraction.length>0&&Number.parseInt(fraction[0],10)>=5)integer2=`${BigInt(integer2)+1n}`;fraction=""}else if(fraction.length>decimals){const left=fraction.slice(0,decimals);const roundDigit=Number.parseInt(fraction.slice(decimals,decimals+1),10);if(roundDigit>=5){const carried=carry(left);if(carried.length>decimals){fraction=carried.slice(1);integer2=`${BigInt(integer2)+1n}`}else{fraction=carried}}else{fraction=left}}else{fraction=fraction.padEnd(decimals,"0")}return BigInt(`${negative?"-":""}${integer2}${fraction}`)}function carry(digits){const out=digits.split("");let i=out.length-1;while(i>=0){const d=Number.parseInt(out[i],10)+1;if(d<10){out[i]=String(d);return out.join("")}out[i]="0";i--}return`1${out.join("")}`}var InvalidDecimalNumberError,InvalidDecimalsError;var init_Value2=__esm({"node_modules/viem/_esm/utils/unit/Value.js"(){"use strict";InvalidDecimalNumberError=class extends Error{constructor({value}){super(`Value \`${value}\` is not a valid decimal number.`);Object.defineProperty(this,"name",{enumerable:true,configurable:true,writable:true,value:"Value.InvalidDecimalNumberError"})}};InvalidDecimalsError=class extends Error{constructor({decimals}){super(`\`decimals\` must be a non-negative integer. Got \`${decimals}\`.`);Object.defineProperty(this,"name",{enumerable:true,configurable:true,writable:true,value:"Value.InvalidDecimalsError"})}}}});function parseUnits(value,decimals){return from6(value,decimals)}var init_parseUnits=__esm({"node_modules/viem/_esm/utils/unit/parseUnits.js"(){"use strict";init_Value2()}});var init_esm3=__esm({"node_modules/viem/_esm/index.js"(){"use strict";init_getAddress();init_parseUnits()}});var Assets_exports={};__export(Assets_exports,{base:()=>base,baseSepolia:()=>baseSepolia,celo:()=>celo,celoSepolia:()=>celoSepolia,define:()=>define,fromToken:()=>fromToken,isAsset:()=>isAsset,isRawAddress:()=>isRawAddress,isToken:()=>isToken,matches:()=>matches,resolve:()=>resolve,toChainId:()=>toChainId,toNetwork:()=>toNetwork});function define(parameters){return{[knownAsset]:true,address:parameters.address,decimals:parameters.decimals,network:parameters.network,transfer:parameters.transfer}}function fromToken(token,parameters){const resolved=token(parameters.chainId);return define({address:resolved.address,decimals:resolved.decimals,network:toNetwork(parameters.chainId),transfer:withTokenDefaults(parameters.transfer,resolved)})}function isAsset(value){if(typeof value!=="object"||value===null)return false;return value[knownAsset]===true}function isToken(value){return typeof value==="function"&&typeof value.addresses==="object"&&typeof value.decimals==="number"}function isRawAddress(currency){return typeof currency==="string"}function resolve(currency,network){if(isAsset(currency)){if(currency.network!==network)return void 0;return{address:currency.address,decimals:currency.decimals,transfer:currency.transfer}}if(isToken(currency)){const address3=currency.addresses[toChainId(network)];if(!address3)return void 0;return{address:address3,decimals:currency.decimals,name:currency.name}}return{address:currency}}function matches(currency,acceptedCurrency,network){const resolved=resolve(currency,network);if(!resolved)return false;return getAddress(resolved.address)===getAddress(acceptedCurrency)}function toNetwork(chainId){return`eip155:${chainId}`}function toChainId(network){return Number(network.slice("eip155:".length))}function withTokenDefaults(transfer2,token){if(transfer2.type!=="eip3009")return transfer2;if(transfer2.name)return{...transfer2,name:transfer2.name};if(!token.name)throw new Error("EIP-3009 token assets require a token name.");return{...transfer2,name:token.name}}var knownAsset,base,baseSepolia,celo,celoSepolia;var init_Assets=__esm({"node_modules/mppx/dist/x402/Assets.js"(){"use strict";init_esm3();knownAsset=Symbol("mppx.x402.asset");base={USDC:define({address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,network:"eip155:8453",transfer:{name:"USD Coin",type:"eip3009",version:"2"}})};baseSepolia={USDC:define({address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",decimals:6,network:"eip155:84532",transfer:{name:"USDC",type:"eip3009",version:"2"}})};celo={USDC:define({address:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,network:"eip155:42220",transfer:{name:"USDC",type:"eip3009",version:"2"}}),USDT:define({address:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,network:"eip155:42220",transfer:{name:"Tether USD",type:"eip3009",version:"1"}})};celoSepolia={USDC:define({address:"0x01C5C0122039549AD1493B8220cABEdD739BC44E",decimals:6,network:"eip155:11142220",transfer:{name:"USDC",type:"eip3009",version:"2"}})}}});var Assets_exports2={};__export(Assets_exports2,{base:()=>base,baseSepolia:()=>baseSepolia,celo:()=>celo,celoSepolia:()=>celoSepolia,define:()=>define,fromToken:()=>fromToken,isAsset:()=>isAsset,isRawAddress:()=>isRawAddress,isToken:()=>isToken,matches:()=>matches,resolve:()=>resolve,toChainId:()=>toChainId,toNetwork:()=>toNetwork});var init_Assets2=__esm({"node_modules/mppx/dist/evm/Assets.js"(){"use strict";init_Assets()}});var Chains_exports={};__export(Chains_exports,{base:()=>base2,baseSepolia:()=>baseSepolia2,celo:()=>celo2,celoSepolia:()=>celoSepolia2});var base2,baseSepolia2,celo2,celoSepolia2;var init_Chains=__esm({"node_modules/mppx/dist/evm/Chains.js"(){"use strict";base2=8453;baseSepolia2=84532;celo2=42220;celoSepolia2=11142220}});var Method_exports={};__export(Method_exports,{broadcastCredential:()=>broadcastCredential,from:()=>from7,selectServerMethod:()=>selectServerMethod,toClient:()=>toClient,toServer:()=>toServer,validateCredential:()=>validateCredential});function from7(method){return method}async function validateCredential(methods,input){const prepared=prepareCredential(methods,input);if(!prepared.method.validate)throw new VerificationFailedError({details:{intent:prepared.method.intent,method:prepared.method.name},reason:`${prepared.method.name}/${prepared.method.intent} does not support non-mutating credential validation`});return prepared.method.validate({credential:prepared.credential,request:prepared.request})}async function broadcastCredential(methods,input){const prepared=prepareCredential(methods,input);const{method}=prepared;if(method.broadcast&&method.validate)await method.validate({credential:prepared.credential,request:prepared.request});const broadcast=method.broadcast??method.verify;return broadcast({credential:prepared.credential,request:prepared.request})}function prepareCredential(methods,input){const credential=typeof input==="string"?deserialize3(input):input;const candidates=methods.filter(method2=>method2.name===credential.challenge.method&&method2.intent===credential.challenge.intent);const method=selectServerMethod(candidates,credential.challenge);if(!method)throw new InvalidChallengeError({id:credential.challenge.id,reason:`no registered method for ${credential.challenge.method}/${credential.challenge.intent}`});assert5(credential.challenge.expires,credential.challenge.id);let payload;try{payload=method.schema.credential.payload.parse(credential.payload)}catch(error51){throw new InvalidPayloadError(error51 instanceof Error?{reason:error51.message}:{})}return{credential:{...credential,payload},method,request:credential.challenge.request}}function selectServerMethod(methods,challenge){if(methods.length<=1)return methods[0];if(challenge.method!==Methods.tempo||challenge.intent!==Intents.session)return methods[0];const sessionProtocol=getMethodDetail(challenge.request.methodDetails,MethodDetailKeys.sessionProtocol);if(sessionProtocol===void 0||sessionProtocol===SessionProtocols.v1)return methods.find(method=>method.alias==="sessionLegacy")??methods[0];if(sessionProtocol===SessionProtocols.v2)return methods.find(method=>method.alias===void 0)??methods[0];return void 0}function toClient(method,options){const{canHandleChallenge,context,createCredential}=options;return{...method,canHandleChallenge,context,createCredential}}function toServer(method,options){const{alias,authorize,defaults,extensions,html,preflight,request,respond,broadcast,stableBinding,transport,validate:validate5,verify:verify3}=options;const effectiveVerify=verify3??(async parameters=>{if(validate5)await validate5(parameters);if(!broadcast)throw new VerificationFailedError({reason:`${method.name}/${method.intent} does not support credential broadcast`});return broadcast(parameters)});return{...method,alias,authorize,defaults,extensions,html,preflight,request,respond,broadcast,stableBinding,transport,validate:validate5,verify:effectiveVerify}}var init_Method=__esm({"node_modules/mppx/dist/Method.js"(){"use strict";init_Constants();init_Credential();init_Errors2();init_Expires()}});var Types_exports={};__export(Types_exports,{AuthorizationConfigSchema:()=>AuthorizationConfigSchema,AuthorizationPayloadSchema:()=>AuthorizationPayloadSchema,ChargePayloadSchema:()=>ChargePayloadSchema,ChargeRequestInputSchema:()=>ChargeRequestInputSchema,ChargeRequestSchema:()=>ChargeRequestSchema,MethodDetailsSchema:()=>MethodDetailsSchema,authorizationDomain:()=>authorizationDomain,authorizationTypes:()=>authorizationTypes,challengeHash:()=>challengeHash,chargeIntent:()=>chargeIntent,credentialTypes:()=>credentialTypes,eip3009:()=>eip3009,evmNetworkPrefix:()=>evmNetworkPrefix,networkOf:()=>networkOf,paymentMethod:()=>paymentMethod,toSource:()=>toSource});function authorizationDomain(parameters){return{chainId:parameters.chainId,name:parameters.authorization.name,verifyingContract:parameters.currency,version:parameters.authorization.version}}function challengeHash(challenge){return Hash_exports.keccak256(Bytes_exports.fromString(`${challenge.id}${challenge.realm}`),{as:"Hex"})}function networkOf(chainId){return`${evmNetworkPrefix}${chainId}`}function toSource(parameters){return`did:pkh:eip155:${parameters.chainId}:${parameters.address}`}var paymentMethod,chargeIntent,evmNetworkPrefix,eip3009,credentialTypes,atomicAmount,AuthorizationConfigSchema,MethodDetailsSchema,ChargeRequestSchema,ChargeRequestInputSchema,AuthorizationPayloadSchema,ChargePayloadSchema,authorizationTypes;var init_Types=__esm({"node_modules/mppx/dist/evm/Types.js"(){"use strict";init_esm2();init_zod();paymentMethod="evm";chargeIntent="charge";evmNetworkPrefix="eip155:";eip3009="eip3009";credentialTypes=["authorization"];atomicAmount=string2().check(_regex(/^\d+$/,"Invalid atomic amount"));AuthorizationConfigSchema=object({name:string2().check(_minLength(1)),version:string2().check(_minLength(1))});MethodDetailsSchema=object({chainId:number2(),credentialTypes:optional(array(_enum2(credentialTypes)).check(_minLength(1))),decimals:optional(number2()),permit2Address:optional(address()),splits:optional(array(object({amount:atomicAmount,recipient:address()})))});ChargeRequestSchema=object({amount:atomicAmount,currency:address(),description:optional(string2()),externalId:optional(string2()),methodDetails:MethodDetailsSchema,recipient:address()});ChargeRequestInputSchema=object({amount:amount(),chainId:number2(),currency:address(),credentialTypes:optional(array(_enum2(credentialTypes)).check(_minLength(1))),decimals:number2(),description:optional(string2()),externalId:optional(string2()),permit2Address:optional(address()),recipient:address(),splits:optional(array(object({amount:atomicAmount,recipient:address()})))});AuthorizationPayloadSchema=object({from:address(),nonce:hash2(),signature:signature(),to:address(),type:literal("authorization"),validAfter:atomicAmount,validBefore:atomicAmount,value:atomicAmount});ChargePayloadSchema=AuthorizationPayloadSchema;authorizationTypes={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]}}});var Methods_exports={};__export(Methods_exports,{charge:()=>charge});var charge;var init_Methods=__esm({"node_modules/mppx/dist/evm/Methods.js"(){"use strict";init_esm3();init_Method();init_zod();init_Types();charge=from7({name:paymentMethod,intent:chargeIntent,schema:{credential:{payload:ChargePayloadSchema},request:pipe(ChargeRequestInputSchema,transform(({amount:amount2,chainId,credentialTypes:credentialTypes2=["authorization"],currency,decimals,permit2Address,recipient,splits,...request})=>({...request,amount:parseUnits(amount2,decimals).toString(),currency:getAddress(currency),methodDetails:{chainId,credentialTypes:credentialTypes2,decimals,...permit2Address?{permit2Address:getAddress(permit2Address)}:{},...splits?{splits}:{}},recipient:getAddress(recipient)})))}})}});var evm_exports={};__export(evm_exports,{Assets:()=>Assets_exports2,AuthorizationConfigSchema:()=>AuthorizationConfigSchema,AuthorizationPayloadSchema:()=>AuthorizationPayloadSchema,Chains:()=>Chains_exports,ChargePayloadSchema:()=>ChargePayloadSchema,ChargeRequestInputSchema:()=>ChargeRequestInputSchema,ChargeRequestSchema:()=>ChargeRequestSchema,MethodDetailsSchema:()=>MethodDetailsSchema,Methods:()=>Methods_exports,Types:()=>Types_exports,assets:()=>Assets_exports2,authorizationDomain:()=>authorizationDomain,authorizationTypes:()=>authorizationTypes,chains:()=>Chains_exports,challengeHash:()=>challengeHash,charge:()=>charge,chargeIntent:()=>chargeIntent,credentialTypes:()=>credentialTypes,eip3009:()=>eip3009,evmNetworkPrefix:()=>evmNetworkPrefix,networkOf:()=>networkOf,paymentMethod:()=>paymentMethod,toSource:()=>toSource});var init_evm=__esm({"node_modules/mppx/dist/evm/index.js"(){"use strict";init_Assets2();init_Chains();init_Methods();init_Types();init_Assets2();init_Chains();init_Methods();init_Types()}});var Mcp_exports={};__export(Mcp_exports,{credentialMetaKey:()=>credentialMetaKey,paymentRequiredCode:()=>paymentRequiredCode,paymentRequiredMetaKey:()=>paymentRequiredMetaKey,paymentVerificationFailedCode:()=>paymentVerificationFailedCode,receiptMetaKey:()=>receiptMetaKey});var paymentRequiredCode,paymentVerificationFailedCode,credentialMetaKey,paymentRequiredMetaKey,receiptMetaKey;var init_Mcp=__esm({"node_modules/mppx/dist/Mcp.js"(){"use strict";paymentRequiredCode=-32042;paymentVerificationFailedCode=-32043;credentialMetaKey="org.paymentauth/credential";paymentRequiredMetaKey="org.paymentauth/payment-required";receiptMetaKey="org.paymentauth/receipt"}});var Receipt_exports={};__export(Receipt_exports,{Schema:()=>Schema2,deserialize:()=>deserialize4,from:()=>from8,fromResponse:()=>fromResponse2,serialize:()=>serialize4});function deserialize4(encoded){const json3=Base64_exports.toString(encoded);return from8(JSON.parse(json3))}function from8(parameters){return Schema2.parse(parameters)}function serialize4(receipt){const json3=JSON.stringify(receipt);return Base64_exports.fromString(json3,{pad:false,url:true})}function fromResponse2(response){const header=response.headers.get(Headers2.paymentReceipt);if(!header)throw new Error(`Missing ${Headers2.paymentReceipt} header.`);return deserialize4(header)}var shape,BaseSchema,Schema2;var init_Receipt=__esm({"node_modules/mppx/dist/Receipt.js"(){"use strict";init_esm2();init_Constants();init_zod();shape={method:string2(),reference:string2(),externalId:optional(string2()),subscriptionId:optional(string2()),status:literal("success"),timestamp:datetime3()};BaseSchema=object(shape);Schema2=looseObject(shape)}});var Store_exports={};__export(Store_exports,{cloudflare:()=>cloudflare,from:()=>from9,memory:()=>memory,redis:()=>redis,upstash:()=>upstash});function from9(store,options){return withKeyPrefix(store,options?.keyPrefix)}function withKeyPrefix(store,keyPrefix=""){if(!keyPrefix)return store;const cached2=keyPrefixCache.get(store)?.get(keyPrefix);if(cached2)return cached2;const backing=store;const prefixedKey=key=>`${keyPrefix}${key}`;const prefixed=from9({async get(key){return backing.get(prefixedKey(key))},async put(key,value){await backing.put(prefixedKey(key),value)},async delete(key){await backing.delete(prefixedKey(key))},..."update"in store?{async update(key,fn){return store.update(prefixedKey(key),fn)}}:{}});const cachedByPrefix=keyPrefixCache.get(store)??new Map;cachedByPrefix.set(keyPrefix,prefixed);keyPrefixCache.set(store,cachedByPrefix);return prefixed}function wrapJsonUpdate(update){if(!update)return{};return{async update(key,fn){return update(key,current=>{const parsed=current==null?null:Json_exports.parse(current);const change=fn(parsed);if(change.op!=="set")return change;return{...change,value:Json_exports.stringify(change.value)}})}}}function cloudflare(kv,options){return from9({async get(key){const raw2=await kv.get(key);if(raw2==null)return null;return Json_exports.parse(raw2)},async put(key,value){await kv.put(key,Json_exports.stringify(value))},async delete(key){await kv.delete(key)},...wrapJsonUpdate(kv.update)},options)}function memory(options){const store=new Map;return from9({async get(key){const raw2=store.get(key);if(raw2===void 0)return null;return Json_exports.parse(raw2)},async put(key,value){store.set(key,Json_exports.stringify(value))},async delete(key){store.delete(key)},async update(key,fn){const current=store.has(key)?Json_exports.parse(store.get(key)):null;const change=fn(current);if(change.op==="set")store.set(key,Json_exports.stringify(change.value));if(change.op==="delete")store.delete(key);return change.result}},options)}function redis(client,options){return from9({async get(key){const raw2=await client.get(key);if(raw2==null)return null;return Json_exports.parse(raw2)},async put(key,value){await client.set(key,Json_exports.stringify(value))},async delete(key){await client.del(key)},...wrapJsonUpdate(client.update)},options)}function upstash(redis2,options){return from9({async get(key){return await redis2.get(key)},async put(key,value){await redis2.set(key,value)},async delete(key){await redis2.del(key)},...redis2.update?{update:redis2.update}:{}},options)}var keyPrefixCache;var init_Store=__esm({"node_modules/mppx/dist/Store.js"(){"use strict";init_esm2();keyPrefixCache=new WeakMap}});function createJson(schema){return{encode(value){return Base64_exports.fromString(JSON.stringify(schema.parse(value)))},decode(value){try{return schema.parse(JSON.parse(Base64_exports.toString(value)))}catch{throw new InvalidJsonHeaderError}}}}var InvalidJsonHeaderError;var init_HeaderCodec=__esm({"node_modules/mppx/dist/internal/HeaderCodec.js"(){"use strict";init_esm2();InvalidJsonHeaderError=class extends Error{name="InvalidJsonHeaderError";constructor(){super("Invalid base64 JSON header.")}}}});var Types_exports2={};__export(Types_exports2,{ExactEip3009PayloadSchema:()=>ExactEip3009PayloadSchema,ExactPayloadSchema:()=>ExactPayloadSchema,ExactPermit2PayloadSchema:()=>ExactPermit2PayloadSchema,ExactTransferSchema:()=>ExactTransferSchema,ExtensionSchema:()=>ExtensionSchema,ExtensionsSchema:()=>ExtensionsSchema,PaymentPayloadSchema:()=>PaymentPayloadSchema,PaymentRequiredSchema:()=>PaymentRequiredSchema,PaymentRequirementsSchema:()=>PaymentRequirementsSchema,ResourceInfoSchema:()=>ResourceInfoSchema,SettleResponseSchema:()=>SettleResponseSchema,VerifyResponseSchema:()=>VerifyResponseSchema,assetTransferMethods:()=>assetTransferMethods,evmNetworkPrefix:()=>evmNetworkPrefix2,exactIntent:()=>exactIntent,paymentMethod:()=>paymentMethod2,paymentRequiredHeader:()=>paymentRequiredHeader,paymentResponseHeader:()=>paymentResponseHeader,paymentSignatureHeader:()=>paymentSignatureHeader,schemes:()=>schemes,syntheticChallengeIdPrefix:()=>syntheticChallengeIdPrefix,toPaymentRequirements:()=>toPaymentRequirements,versions:()=>versions});function toPaymentRequirements(request){const{extensions:_extensions,resource:_resource,...paymentRequirements}=request;return PaymentRequirementsSchema.parse(paymentRequirements)}var versions,paymentMethod2,exactIntent,schemes,assetTransferMethods,evmNetworkPrefix2,syntheticChallengeIdPrefix,paymentRequiredHeader,paymentSignatureHeader,paymentResponseHeader,nonEmptyString,positiveNumber,atomicAmount2,address2,evmNetwork,ResourceInfoSchema,ExactTransferSchema,PaymentRequirementsSchema,ExtensionSchema,ExtensionsSchema,PaymentRequiredSchema,ExactEip3009PayloadSchema,ExactPermit2PayloadSchema,ExactPayloadSchema,PaymentPayloadSchema,VerifyResponseSchema,SettleResponseSchema;var init_Types2=__esm({"node_modules/mppx/dist/x402/Types.js"(){"use strict";init_zod();versions=[2];paymentMethod2="evm";exactIntent="charge";schemes=["exact"];assetTransferMethods=["eip3009","permit2"];evmNetworkPrefix2="eip155:";syntheticChallengeIdPrefix="x402:";paymentRequiredHeader="PAYMENT-REQUIRED";paymentSignatureHeader="PAYMENT-SIGNATURE";paymentResponseHeader="PAYMENT-RESPONSE";nonEmptyString=string2().check(_minLength(1));positiveNumber=number2().check(refine(value=>value>0,"Must be positive"));atomicAmount2=string2().check(_regex(/^\d+$/,"Invalid atomic amount"));address2=address();evmNetwork=string2().check(_regex(new RegExp(`^${evmNetworkPrefix2}\\d+$`),"Invalid EVM CAIP-2 network"));ResourceInfoSchema=object({description:optional(string2()),iconUrl:optional(string2()),mimeType:optional(string2()),serviceName:optional(string2()),tags:optional(array(string2())),url:nonEmptyString});ExactTransferSchema=discriminatedUnion("type",[object({name:nonEmptyString,type:literal("eip3009"),version:nonEmptyString}),object({name:optional(string2()),type:literal("permit2"),version:optional(string2())})]);PaymentRequirementsSchema=object({amount:atomicAmount2,asset:nonEmptyString,extra:optional(record(string2(),unknown())),maxTimeoutSeconds:positiveNumber,network:evmNetwork,payTo:nonEmptyString,scheme:_enum2(schemes)});ExtensionSchema=object({info:record(string2(),unknown()),schema:record(string2(),unknown())});ExtensionsSchema=record(string2(),ExtensionSchema);PaymentRequiredSchema=object({accepts:array(PaymentRequirementsSchema).check(_minLength(1)),error:optional(string2()),extensions:optional(ExtensionsSchema),resource:ResourceInfoSchema,x402Version:literal(2)});ExactEip3009PayloadSchema=object({authorization:object({from:address2,nonce:hash2(),to:address2,validAfter:atomicAmount2,validBefore:atomicAmount2,value:atomicAmount2}),signature:signature()});ExactPermit2PayloadSchema=object({permit2Authorization:object({deadline:atomicAmount2,from:address2,nonce:atomicAmount2,permitted:object({amount:atomicAmount2,token:address2}),spender:address2,witness:object({to:address2,validAfter:atomicAmount2})}),signature:signature()});ExactPayloadSchema=union([ExactEip3009PayloadSchema,ExactPermit2PayloadSchema]);PaymentPayloadSchema=object({accepted:PaymentRequirementsSchema,extensions:optional(ExtensionsSchema),payload:ExactPayloadSchema,resource:optional(ResourceInfoSchema),x402Version:literal(2)});VerifyResponseSchema=object({extensions:optional(ExtensionsSchema),extra:optional(record(string2(),unknown())),invalidMessage:optional(string2()),invalidReason:optional(string2()),isValid:boolean2(),payer:optional(string2())});SettleResponseSchema=object({amount:optional(atomicAmount2),errorMessage:optional(string2()),errorReason:optional(string2()),extensions:optional(ExtensionsSchema),extra:optional(record(string2(),unknown())),network:nonEmptyString,payer:optional(string2()),success:boolean2(),transaction:string2()})}});var Header_exports={};__export(Header_exports,{decodePaymentRequired:()=>decodePaymentRequired,decodePaymentRequiredEnvelope:()=>decodePaymentRequiredEnvelope,decodePaymentResponse:()=>decodePaymentResponse,decodePaymentSignature:()=>decodePaymentSignature,encodePaymentRequired:()=>encodePaymentRequired,encodePaymentResponse:()=>encodePaymentResponse,encodePaymentSignature:()=>encodePaymentSignature});function decodePaymentRequiredEnvelope(value){try{const parsed=JSON.parse(Base64_exports.toString(value));return parsePaymentRequiredEnvelope(parsed)}catch{throw new InvalidJsonHeaderError}}var paymentRequired,paymentSignature,paymentResponse,encodePaymentRequired,decodePaymentRequired,encodePaymentSignature,decodePaymentSignature,encodePaymentResponse,decodePaymentResponse,parsePaymentRequiredEnvelope;var init_Header=__esm({"node_modules/mppx/dist/x402/Header.js"(){"use strict";init_esm2();init_HeaderCodec();init_Types2();paymentRequired=createJson(PaymentRequiredSchema);paymentSignature=createJson(PaymentPayloadSchema);paymentResponse=createJson(SettleResponseSchema);encodePaymentRequired=paymentRequired.encode;decodePaymentRequired=paymentRequired.decode;encodePaymentSignature=paymentSignature.encode;decodePaymentSignature=paymentSignature.decode;encodePaymentResponse=paymentResponse.encode;decodePaymentResponse=paymentResponse.decode;parsePaymentRequiredEnvelope=value=>{if(!value||typeof value!=="object"||Array.isArray(value))throw new InvalidJsonHeaderError;const record2=value;if(record2.x402Version!==2||!Array.isArray(record2.accepts))throw new InvalidJsonHeaderError;const resource=ResourceInfoSchema.parse(record2.resource);const extensions=record2.extensions!==void 0?ExtensionsSchema.safeParse(record2.extensions).data:void 0;return{accepts:record2.accepts,...extensions?{extensions}:{},resource,x402Version:2}}}});var x402_exports={};__export(x402_exports,{Assets:()=>Assets_exports,ExactEip3009PayloadSchema:()=>ExactEip3009PayloadSchema,ExactPayloadSchema:()=>ExactPayloadSchema,ExactPermit2PayloadSchema:()=>ExactPermit2PayloadSchema,ExactTransferSchema:()=>ExactTransferSchema,ExtensionSchema:()=>ExtensionSchema,ExtensionsSchema:()=>ExtensionsSchema,Header:()=>Header_exports,PaymentPayloadSchema:()=>PaymentPayloadSchema,PaymentRequiredSchema:()=>PaymentRequiredSchema,PaymentRequirementsSchema:()=>PaymentRequirementsSchema,ResourceInfoSchema:()=>ResourceInfoSchema,SettleResponseSchema:()=>SettleResponseSchema,Types:()=>Types_exports2,VerifyResponseSchema:()=>VerifyResponseSchema,assetTransferMethods:()=>assetTransferMethods,assets:()=>Assets_exports,evmNetworkPrefix:()=>evmNetworkPrefix2,exactIntent:()=>exactIntent,paymentMethod:()=>paymentMethod2,paymentRequiredHeader:()=>paymentRequiredHeader,paymentResponseHeader:()=>paymentResponseHeader,paymentSignatureHeader:()=>paymentSignatureHeader,schemes:()=>schemes,syntheticChallengeIdPrefix:()=>syntheticChallengeIdPrefix,toPaymentRequirements:()=>toPaymentRequirements,versions:()=>versions});var init_x402=__esm({"node_modules/mppx/dist/x402/index.js"(){"use strict";init_Assets();init_Header();init_Types2();init_Assets();init_Types2()}});var dist_exports={};__export(dist_exports,{BodyDigest:()=>BodyDigest_exports,Challenge:()=>Challenge_exports,Constants:()=>Constants_exports,Credential:()=>Credential_exports,Errors:()=>Errors_exports2,Expires:()=>Expires_exports,Mcp:()=>Mcp_exports,Method:()=>Method_exports,PaymentRequest:()=>PaymentRequest_exports,Receipt:()=>Receipt_exports,Store:()=>Store_exports,evm:()=>evm_exports,x402:()=>x402_exports,z:()=>zod_exports});var init_dist2=__esm({"node_modules/mppx/dist/index.js"(){"use strict";init_BodyDigest();init_Challenge();init_Constants();init_Credential();init_Errors2();init_Expires();init_evm();init_Mcp();init_Method();init_PaymentRequest();init_Receipt();init_Store();init_x402();init_zod()}});import{decodePaymentRequiredHeader,DvmError as DvmError6,fetchBtcUsdRate,isAbortError as isAbortError2,isFundingReceipt,isSignedJobReceipt,parseCreditMenu,parseCreditTerms,providerProseSources as providerProseSources2,ROUTER_FEEDBACK_CLAIM_HEADER,SUPPORTED_PROTOCOL_VERSION,usdToMsats,X402_V1_VERSION,X402_VERSION}from"@dvmkit/sdk/internal";function jobTokenHeader(jobToken){return jobToken?{"X-Job-Token":jobToken}:{}}function captureTraceId(res){const tp=res.headers.get("traceparent");if(tp){const parsed=parseTraceparent(tp);if(parsed)setOutputTraceId(parsed.traceId)}}async function tempoTransactionHashFromResponse(res){const encoded=res.headers.get("Payment-Receipt");if(!encoded)return void 0;try{const{Receipt}=await Promise.resolve().then(()=>(init_dist2(),dist_exports));const receipt=Receipt.deserialize(encoded);if(receipt.method!=="tempo")return void 0;const extension2=receipt;const candidate=extension2.intent==="session"?typeof extension2.txHash==="string"?extension2.txHash:void 0:receipt.reference;return candidate&&/^0x[a-f0-9]{64}$/i.test(candidate)?candidate.toLowerCase():void 0}catch{return void 0}}function parseSignedReceipt(value){if(value===void 0)return{};return isSignedJobReceipt(value)?{receipt:value}:{receiptParseError:"shape_invalid"}}function parseFundingReceipt(value){if(value===void 0)return{};return isFundingReceipt(value)?{fundingReceipt:value}:{fundingReceiptParseError:"shape_invalid"}}function parseFundingResponse(data){return{...parseFundingReceipt(data.funding_receipt),...typeof data.funded_micro==="number"?{fundedMicro:data.funded_micro}:{},...data.credit&&typeof data.credit==="object"&&!Array.isArray(data.credit)?{credit:data.credit}:{}}}function parseRequestResultResponse(value,requestId,httpStatus){if(!value||typeof value!=="object"||Array.isArray(value)){throw malformedRequestResult(requestId,"response_not_object")}const data=value;if(data.request_id!==requestId){throw malformedRequestResult(requestId,"request_id_mismatch")}if(typeof data.job_id!=="string"||data.job_id.trim().length===0||data.job_id.length>512||hasAsciiControl(data.job_id)){throw malformedRequestResult(requestId,"job_id_invalid")}const allowedStatuses=new Set(["processing","awaiting-input","completed","failed","cancelled"]);if(!allowedStatuses.has(data.status)){throw malformedRequestResult(requestId,"status_invalid")}const status2=data.status;const terminal=status2==="completed"||status2==="failed"||status2==="cancelled";if(httpStatus===202&&terminal||httpStatus===200&&!terminal){throw malformedRequestResult(requestId,"http_status_mismatch")}if(data.job_token!==void 0&&!isOpaqueJobToken(data.job_token)){throw malformedRequestResult(requestId,"job_token_invalid")}if(data.transaction_hash!==void 0&&(typeof data.transaction_hash!=="string"||!/^0x[0-9a-fA-F]{64}$/.test(data.transaction_hash))){throw malformedRequestResult(requestId,"transaction_hash_invalid")}if(data.summary!==void 0&&typeof data.summary!=="string"){throw malformedRequestResult(requestId,"summary_invalid")}if(data.has_artifacts!==void 0&&typeof data.has_artifacts!=="boolean"){throw malformedRequestResult(requestId,"has_artifacts_invalid")}if(data.artifact_count!==void 0&&(!Number.isSafeInteger(data.artifact_count)||data.artifact_count<0)){throw malformedRequestResult(requestId,"artifact_count_invalid")}if(data.payload_in!==void 0&&data.payload_in!=="summary"&&data.payload_in!=="messages"){throw malformedRequestResult(requestId,"payload_in_invalid")}let receipt;if(data.receipt!==void 0){if(!isSignedJobReceipt(data.receipt)||data.receipt.job_id!==data.job_id||!/^[0-9a-fA-F]{64}$/.test(data.receipt.receipt_pubkey)||!/^[0-9a-fA-F]{128}$/.test(data.receipt.signature)||terminal&&data.receipt.outcome!==status2){throw malformedRequestResult(requestId,"receipt_invalid")}receipt=data.receipt}return{jobId:data.job_id,status:status2,...typeof data.transaction_hash==="string"?{transactionHash:data.transaction_hash}:{},...typeof data.summary==="string"?{summary:data.summary}:{},...typeof data.has_artifacts==="boolean"?{hasArtifacts:data.has_artifacts}:{},...typeof data.artifact_count==="number"?{artifactCount:data.artifact_count}:{},...data.payload_in==="summary"||data.payload_in==="messages"?{payloadIn:data.payload_in}:{},...typeof data.job_token==="string"?{jobToken:data.job_token}:{},...receipt?{receipt}:{},...parseFundingResponse(data)}}function isOpaqueJobToken(value){return typeof value==="string"&&value.length>0&&value.length<=4096&&value.trim()===value&&!hasAsciiControl(value)}function hasAsciiControl(value){for(const character of value){const code=character.charCodeAt(0);if(code<=31||code===127)return true}return false}function malformedRequestResult(requestId,reason){return new DvmError6("request_outcome_unknown","The provider returned a malformed request recovery response.","Do not submit or pay for a replacement. Retry the read-only lookup after the provider is fixed.",{request_id:requestId,status:"unknown",reason})}function parseTrustAnchor(value){if(!value||typeof value!=="object"||Array.isArray(value))return void 0;const b2=value;const attestation=b2.attestation;const wellFormed=typeof b2.pubkey==="string"&&typeof b2.signature==="string"&&!!attestation&&typeof attestation==="object"&&!Array.isArray(attestation);return wellFormed?value:void 0}function parseX402PaymentRequired(headers,body){const v2=headers.get("PAYMENT-REQUIRED");if(v2){try{return decodePaymentRequiredHeader(v2)}catch{}}if(body.x402Version!==X402_V1_VERSION||!Array.isArray(body.accepts))return void 0;return{x402Version:X402_V1_VERSION,...typeof body.message==="string"?{error:body.message}:{},accepts:body.accepts}}function x402RequiredUsdcMicro(required3){if(!required3)return void 0;if(required3.x402Version===X402_VERSION){return required3.accepts.at(0)?.amount}return required3.accepts.at(0)?.maxAmountRequired}async function parseSSEStream(res,options){const messages=[];if(!res.body){return{messages,reason:"error"}}const reader=res.body.getReader();const decoder3=new TextDecoder;let buffer="";let lastReason="yield";try{for(;;){const{done,value}=await reader.read();if(done)break;buffer+=decoder3.decode(value,{stream:true});let hitYield=false;let boundary;while((boundary=buffer.indexOf("\n\n"))!==-1){const block=buffer.slice(0,boundary);buffer=buffer.slice(boundary+2);const dataLine=block.split("\n").find(line=>line.startsWith("data:"));if(!dataLine)continue;const json3=dataLine.slice("data:".length).trim();try{const msg=JSON.parse(json3);messages.push(msg);options?.onMessage?.(msg);if(YIELD_TYPES.has(msg.type)){if(msg.type==="complete")lastReason="complete";else if(msg.type==="cancel")lastReason="cancel";else lastReason="yield";hitYield=true}}catch{}}if(hitYield){reader.cancel().catch(()=>void 0);return{messages,reason:lastReason}}}}catch{lastReason="error"}finally{reader.releaseLock()}return{messages,reason:lastReason}}function parseStructuredError(body){const parsed=parseJsonObject(body);if(!parsed)return null;const err=parsed.error;if(err&&typeof err==="object"&&!Array.isArray(err)){const e17=err;if(typeof e17.code!=="string")return null;return buildStructuredError(e17.code,e17)}if(typeof err!=="string")return null;if(err==="invalid_input"||err==="invalid_quote_data"){const fields={...parsed,...typeof parsed.message!=="string"&&typeof parsed.details==="string"?{message:parsed.details}:{}};return buildStructuredError("invalid_input",fields)}return buildStructuredError(err,parsed)}function jobCredentialError(status2,body){if(status2!==401)return null;return parseStructuredError(body)}function buildStructuredError(code,fields){const display=typeof fields.display==="string"?fields.display:void 0;const providerMessage=typeof fields.message==="string"?fields.message:void 0;const message2=providerMessage??display??"The provider returned an error without explanatory prose.";const hint=typeof fields.hint==="string"?fields.hint:void 0;const data={};if(display!==void 0)data.display=display;if(typeof fields.retryable==="boolean")data.retryable=fields.retryable;if(fields.status==="unknown")data.status=fields.status;if(typeof fields.request_id==="string")data.request_id=fields.request_id;if(fields.server_acceptance==="absent")data.server_acceptance=fields.server_acceptance;if(fields.payment_state==="unknown")data.payment_state=fields.payment_state;const detectedSources=providerProseSources2(fields,data);const proseSources=display!==void 0&&providerMessage===void 0?{...detectedSources,message:"provider"}:detectedSources;return new DvmError6(code,message2,hint,Object.keys(data).length>0?data:void 0,void 0,proseSources)}function providerResponseError(code,message2){return new DvmError6(code,message2,void 0,void 0,void 0,{message:"provider"})}function parseJsonObject(body){try{const parsed=JSON.parse(body);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return null;return parsed}catch{return null}}function isReceipt402(code){return code===void 0||code==="payment_required"||code==="payment_insufficient"}function buildPaymentError(errorBody){const code=typeof errorBody.error==="string"?errorBody.error:"payment_insufficient";return buildStructuredError(code,errorBody)}async function paymentHeaders(payment){const headers={};if(payment?.cashuToken){headers["X-Cashu"]=payment.cashuToken}if(payment?.cashuRequestId){headers["X-Cashu-Request-Id"]=payment.cashuRequestId}if(payment?.x402Payment){headers[payment.x402Version===X402_VERSION?"PAYMENT-SIGNATURE":"X-PAYMENT"]=payment.x402Payment}if(payment?.mppCredentialRaw){headers.Authorization=payment.mppCredentialRaw}else if(payment?.mppCredential){const{Credential}=await Promise.resolve().then(()=>(init_dist2(),dist_exports));headers.Authorization=Credential.serialize(payment.mppCredential)}return headers}function withCreditErrorContext(err,body){const extra={};for(const key of CREDIT_CONTEXT_FIELDS){if(typeof body[key]==="number")extra[key]=body[key]}const menu=parseCreditMenu(body.credit);if(menu)extra.credit=menu;const lightning=parseLightningOffer(body.lightning);if(lightning)extra.lightning=lightning;for(const key of["credit_id","fund_id","drain_id","credit_rail","credit_instrument","credit_channel_id","bound_credit_id","rail","settlement_drain_id"]){if(typeof body[key]==="string")extra[key]=body[key]}for(const key of["drain_registered","drain_id_retired","credential_refresh_required"]){if(typeof body[key]==="boolean")extra[key]=body[key]}for(const key of["funding","alternatives"]){const rails=body[key];if(Array.isArray(rails)&&rails.every(r=>typeof r==="string")){extra[key]=rails}}if(Object.keys(extra).length===0)return err;return new DvmError6(err.code,err.message,err.hint,{...err.data,...extra},err.display,err.proseSources)}function parseLightningOffer(raw2){if(!raw2||typeof raw2!=="object"||Array.isArray(raw2))return void 0;const block=raw2;if(typeof block.invoice!=="string"||block.invoice.length===0)return void 0;if(typeof block.amount_msats!=="number"||block.amount_msats<=0)return void 0;return block}function parseUpfront(data){const raw2=data.upfront;if(raw2&&typeof raw2==="object"){const u=raw2;if(typeof u.amount==="number"&&typeof u.currency==="string"){const amountMicro=exactMicro(u.amount_micro);return{amount:u.amount,currency:u.currency,...amountMicro&&{amount_micro:amountMicro}}}}return{amount:0,currency:"usd"}}function exactMicro(raw2){return typeof raw2==="number"&&Number.isSafeInteger(raw2)&&raw2>0?raw2:void 0}async function deriveAdvisorySats(upfront,data){if(typeof data.price_msats==="number")return data.price_msats;if(upfront.currency!=="usd"||upfront.amount<=0)return void 0;try{const rate=await fetchBtcUsdRate();return usdToMsats(upfront.amount,rate)}catch{return void 0}}var HttpsTransport,YIELD_TYPES,CREDIT_CONTEXT_FIELDS;var init_https=__esm({"src/lib/transport/https.ts"(){"use strict";init_output();init_traceparent();init_http();init_job_envelope();HttpsTransport=class{async describe(provider,options){const url2=`${provider.endpoint}/v1/info`;const signal=options?.timeoutMs&&options.timeoutMs>0?AbortSignal.timeout(options.timeoutMs):void 0;let res;try{res=await dvmFetch(url2,{signal})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","Provider metadata read timed out.","The provider may be starting up. Retry in a few seconds.")}throw err}if(!res.ok){throw providerResponseError("provider_error",`Provider returned ${res.status}: ${await res.text()}`)}const data=await res.json();const providerVersion=data.protocol_version;if(providerVersion!==void 0&&providerVersion>SUPPORTED_PROTOCOL_VERSION){throw new DvmError6("unsupported_version",`Provider requires protocol version ${providerVersion}, but this client only supports up to ${SUPPORTED_PROTOCOL_VERSION}.`,"Upgrade dvmkit to interact with this provider.")}const builder=parseTrustAnchor(data.builder);return{name:data.name,about:data.description,tags:data.tags,auth:data.auth,authAudience:data.auth_audience,pricing:data.pricing,mints:data.mints,quote:data.quote,inputSchema:data.input_schema,protocolVersion:providerVersion,paymentMethods:data.payment?.methods,credit:parseCreditTerms(data.credit),x402:data.x402,tempo:data.tempo,cashu:data.cashu,sdkSha:data.sdk_sha,capabilities:data.capabilities,...data.receipts===true?{receipts:true}:{},...data.request_recovery===true?{requestRecovery:true}:{},...builder?{builder}:{}}}async quote(provider,job){const url2=`${provider.endpoint}/v1/quote`;const body=JSON.stringify(envelopeToPayload(job));const res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json"},body});captureTraceId(res);if(!res.ok){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`Quote failed (${res.status}): ${text}`)}const data=await res.json();const upfront=parseUpfront(data);const description=typeof data.description==="string"?data.description:"";const advisorySats=await deriveAdvisorySats(upfront,data);const quote={upfront,description,priceMsats:advisorySats??0,mints:data.mints,expiresAt:data.expires_at};if(typeof data.hint==="string")quote.hint=data.hint;if(data.shape==="fixed"||data.shape==="rate")quote.shape=data.shape;if(data.rate&&typeof data.rate==="object"){quote.rate=data.rate}const payment=data.payment;if(payment&&Array.isArray(payment.methods)&&payment.refundable&&typeof payment.refundable==="object"){quote.payment={methods:payment.methods,refundable:payment.refundable}}const creditMenu=parseCreditMenu(data.credit);if(creditMenu)quote.credit=creditMenu;return[quote]}async submit(provider,job,payment,options){const url2=`${provider.endpoint}/v1/job`;const body=JSON.stringify(envelopeToPayload(job));const headers={"Content-Type":"application/json",...await paymentHeaders(payment)};const signal=options?.timeoutMs&&options.timeoutMs>0?AbortSignal.timeout(options.timeoutMs):void 0;let res;try{res=await dvmFetch(url2,{method:"POST",headers,body,signal})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","Job submission timed out.","The provider may be starting up. Retry in a few seconds or use a longer --timeout.")}throw new DvmError6("provider_unreachable",`Could not reach ${url2}: ${err instanceof Error?err.message:String(err)}`,"The provider may be down or unreachable from this network. Retry once it is back.")}captureTraceId(res);const tempoTransactionHash=await tempoTransactionHashFromResponse(res);if(res.status===402){let errorBody;try{errorBody=await res.json()}catch{throw new DvmError6("payment_insufficient","Payment required (unparseable response).")}const requiredMsats=errorBody.required_msats;const receivedMsats=errorBody.received_msats;if(requiredMsats!==void 0&&isReceipt402(errorBody.error)){const creditMenu=parseCreditMenu(errorBody.credit);const priceMicro=exactMicro(errorBody.price_micro);const rate=priceMicro===void 0?await fetchBtcUsdRate().catch(()=>null):null;const usd=rate?requiredMsats/1e11*rate:0;const upfront=priceMicro===void 0?{amount:Math.round(usd*1e4)/1e4,currency:"usd"}:{amount:priceMicro/1e6,currency:typeof errorBody.price_currency==="string"?errorBody.price_currency:creditMenu?.currency??"usd",amount_micro:priceMicro};const x402PaymentRequired=parseX402PaymentRequired(res.headers,errorBody);const requiredUsdcMicro=x402RequiredUsdcMicro(x402PaymentRequired);return{jobId:"",status:"payment-required",quotes:[{upfront,description:receivedMsats?`Received ${String(receivedMsats)} msats, need ${String(requiredMsats)} msats`:"Upfront payment required",priceMsats:requiredMsats,...requiredUsdcMicro!==void 0&&{requiredUsdcMicro},...x402PaymentRequired&&{x402PaymentRequired},...creditMenu?{credit:creditMenu}:{},mints:errorBody.mints}]}}throw withCreditErrorContext(buildPaymentError(errorBody),errorBody)}if(!res.ok&&res.status!==202){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`Job submission failed (${res.status}): ${text}`)}const data=await res.json();const feedbackClaim=res.headers.get(ROUTER_FEEDBACK_CLAIM_HEADER)??void 0;const jobToken=data.job_token;if(res.status===202){return{jobId:data.job_id,status:data.status==="awaiting-input"?"awaiting-input":"processing",estimatedSeconds:data.estimated_seconds,jobToken,...tempoTransactionHash?{transactionHash:tempoTransactionHash}:{},...feedbackClaim?{feedbackClaim}:{},...parseFundingResponse(data)}}return{jobId:data.job_id,status:"completed",summary:data.summary,hasArtifacts:data.has_artifacts,artifactCount:data.artifact_count,payloadIn:data.payload_in,cashuChange:res.headers.get("X-Cashu-Change")??void 0,jobToken,...tempoTransactionHash?{transactionHash:tempoTransactionHash}:{},...feedbackClaim?{feedbackClaim}:{},...parseSignedReceipt(data.receipt),...parseFundingResponse(data)}}async requestResult(provider,requestId,signedJob){const url2=`${provider.endpoint}/v1/request-result/${encodeURIComponent(requestId)}`;const res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(envelopeToPayload(signedJob))});captureTraceId(res);if(!res.ok&&res.status!==202){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`Request lookup failed (${res.status}): ${text}`)}let data;try{data=await res.json()}catch{throw malformedRequestResult(requestId,"response_not_json")}return parseRequestResultResponse(data,requestId,res.status)}async requestResume(provider,requestId,signedJob,options){const url2=`${provider.endpoint}/v1/request-resume/${encodeURIComponent(requestId)}`;const signal=options?.timeoutMs&&options.timeoutMs>0?AbortSignal.timeout(options.timeoutMs):void 0;let res;try{res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(envelopeToPayload(signedJob)),signal})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","Request recovery timed out.","Run request-result before retrying recovery.")}throw new DvmError6("provider_unreachable",`Could not reach ${url2}: ${err instanceof Error?err.message:String(err)}`,"Run request-result before retrying recovery.")}captureTraceId(res);if(!res.ok&&res.status!==202){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`Request recovery failed (${res.status}): ${text}`)}}async credit(provider,signedBody,payment,options){const url2=`${provider.endpoint}/v1/credit`;const headers={"Content-Type":"application/json",...await paymentHeaders(payment)};const signal=options?.timeoutMs&&options.timeoutMs>0?AbortSignal.timeout(options.timeoutMs):void 0;let res;try{res=await dvmFetch(url2,{method:"POST",headers,body:JSON.stringify(signedBody),signal})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","Credit operation timed out.","The provider may be starting up. Retry in a few seconds.")}throw new DvmError6("provider_unreachable",`Could not reach ${url2}: ${err instanceof Error?err.message:String(err)}`,"The provider may be down or unreachable from this network. Retry once it is back.")}captureTraceId(res);const tempoTransactionHash=await tempoTransactionHashFromResponse(res);if(!res.ok){const mppChallenges=res.status===402&&res.headers.get("WWW-Authenticate")?(await Promise.resolve().then(()=>(init_dist2(),dist_exports))).Challenge.fromHeadersList(res.headers):[];const text=await res.text();const parsed=parseJsonObject(text);const structured=parseStructuredError(text);if(structured){const contextual=withCreditErrorContext(structured,parsed??{});const x402PaymentRequired=parseX402PaymentRequired(res.headers,parsed??{});if(x402PaymentRequired){contextual.data={...contextual.data,x402_payment_required:x402PaymentRequired}}if(tempoTransactionHash){contextual.data={...contextual.data,transaction_hash:tempoTransactionHash}}throw mppChallenges.length>0?new DvmError6(contextual.code,contextual.message,contextual.hint,{...contextual.data,tempo_challenges:mppChallenges},contextual.display,contextual.proseSources):contextual}throw providerResponseError("provider_error",`Credit operation failed (${res.status}): ${text}`)}const result=await res.json();const{menu:rawMenu,funding_receipt:rawFundingReceipt,...creditResult}=result;const menu=parseCreditMenu(rawMenu);const x402PaymentResponse=res.headers.get("PAYMENT-RESPONSE")??res.headers.get("X-PAYMENT-RESPONSE")??void 0;const enriched={...creditResult,...parseFundingReceipt(rawFundingReceipt),...x402PaymentResponse?{x402PaymentResponse}:{},...tempoTransactionHash?{transactionHash:tempoTransactionHash}:{}};return menu?{...enriched,menu}:enriched}async status(jobId,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS status check requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}`;const res=await dvmFetch(url2,{headers:jobTokenHeader(options?.jobToken)});captureTraceId(res);if(res.status===404){throw new DvmError6("job_not_found",`Job ${jobId} not found.`)}if(!res.ok){const credentialErr=jobCredentialError(res.status,await res.text());if(credentialErr)throw credentialErr;throw new DvmError6("provider_error",`Status check failed (${res.status})`)}const data=await res.json();return{jobId,status:data.status,summary:data.summary,hasArtifacts:data.has_artifacts,artifactCount:data.artifact_count,payloadIn:data.payload_in,message:data.message,cashuChange:res.headers.get("X-Cashu-Change")??void 0,...parseSignedReceipt(data.receipt),...parseFundingResponse(data)}}async getMessages(jobId,after,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS getMessages requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}/messages?after=${after}`;const res=await dvmFetch(url2,{headers:jobTokenHeader(options?.jobToken)});if(!res.ok){const text=await res.text();const credentialErr=jobCredentialError(res.status,text);if(credentialErr)throw credentialErr;throw providerResponseError("provider_error",`getMessages failed (${res.status}): ${text}`)}const data=await res.json();return data.messages}async sendMessage(jobId,message2,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS sendMessage requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}/messages`;const body=JSON.stringify({type:message2.type,content:message2.content});let res;try{res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json",...jobTokenHeader(options?.jobToken)},body})}catch(err){if(isAbortError2(err)){throw new DvmError6("timeout","sendMessage timed out.")}throw err}if(res.status===402){let errorBody;try{errorBody=await res.json()}catch{throw new DvmError6("payment_insufficient","Payment required (unparseable response).")}throw buildPaymentError(errorBody)}if(res.status===409){const body2=parseJsonObject(await res.text());if(body2?.error==="replay_rejected")throw buildPaymentError(body2);throw new DvmError6("job_terminal","Job is no longer active.",`The job has already completed or been cancelled, so it can't accept more messages. Fetch the final result with 'dvm messages ${jobId}'.`)}if(!res.ok){const text=await res.text();const structured=parseStructuredError(text);if(structured)throw structured;throw providerResponseError("provider_error",`sendMessage failed (${res.status}): ${text}`)}}async stream(jobId,afterSeq,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS stream requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}/messages?after=${afterSeq}`;const res=await dvmFetch(url2,{headers:{Accept:"text/event-stream",...jobTokenHeader(options?.jobToken)},signal:options?.signal});if(!res.ok){const text=await res.text();const credentialErr=jobCredentialError(res.status,text);if(credentialErr)throw credentialErr;throw providerResponseError("provider_error",`stream failed (${res.status}): ${text}`)}const contentType=res.headers.get("content-type")??"";if(contentType.includes("application/json")){const body=await res.json();const messages=body.messages??[];const last=messages.at(-1);const reason=last?.type==="complete"?"complete":last?.type==="cancel"?"cancel":"yield";for(const msg of messages)options?.onMessage?.(msg);return{messages,reason}}return parseSSEStream(res,options)}async cancel(jobId,reason,provider,options){const endpoint=provider?.endpoint;if(!endpoint){throw new DvmError6("not_supported","HTTPS cancel requires a provider with an endpoint.")}const url2=`${endpoint}/v1/job/${jobId}`;const body=reason?JSON.stringify({reason}):void 0;const tokenHeader=jobTokenHeader(options?.jobToken);const headers=body?{"Content-Type":"application/json",...tokenHeader}:tokenHeader;const res=await dvmFetch(url2,{method:"DELETE",headers,body});if(!res.ok){const text=await res.text();const credentialErr=jobCredentialError(res.status,text);if(credentialErr)throw credentialErr;throw providerResponseError("provider_error",`Cancel failed (${res.status}): ${text}`)}}async probeMppChallenges(provider,job){const url2=`${provider.endpoint}/v1/job`;const body=JSON.stringify(envelopeToPayload(job));const res=await dvmFetch(url2,{method:"POST",headers:{"Content-Type":"application/json"},body});if(res.status!==402){await res.text().catch(()=>void 0);if(res.ok||res.status===202)return[];throw new DvmError6("provider_error",`MPP probe expected 402 but got ${res.status}.`,"Check the DVM's `/v1/info` for advertised payment methods.")}const{Challenge}=await Promise.resolve().then(()=>(init_dist2(),dist_exports));return Challenge.fromHeadersList(res.headers)}close(){}};YIELD_TYPES=new Set(["prompt","payment-request","working","complete","cancel"]);CREDIT_CONTEXT_FIELDS=["remaining_micro","shortfall_micro","balance_micro","expiry_ms","fundable_micro","expected_micro","min_micro"]}});function createDvmTransport(){return new HttpsTransport}var init_factory=__esm({"src/lib/transport/factory.ts"(){"use strict";init_https()}});import{SUPPORTED_PROTOCOL_VERSION as SUPPORTED_PROTOCOL_VERSION2}from"@dvmkit/sdk/internal";var init_transport=__esm({"src/lib/transport/index.ts"(){"use strict";init_factory();init_https()}});import{deriveBuilderLockKeypair,DvmError as DvmError7,toLockPubkey}from"@dvmkit/sdk/internal";function resolveBuilderLockIdentity(handle2){const{mnemonic,canonicalDvmId,rotationIndex}=readBuilderContextByHandle(handle2);return{handle:handle2,canonicalDvmId,rotationIndex,lockPubkey:deriveBuilderLockKeypair(mnemonic,canonicalDvmId,rotationIndex).pubkey}}function resolveBuilderLockKeyring(dvmId){return buildKeyring(readBuilderContext(dvmId))}async function resolveBuilderLockKeyringByHandle(handle2,endpoint){const mnemonic=requireBuilderMnemonic();const resolved=await resolveBuilderEntryByHandle(handle2,mnemonic,endpoint);return buildKeyring({handle:resolved.entry.handle,mnemonic,canonicalDvmId:resolved.entry.canonical_dvm_id,rotationIndex:resolved.entry.current_rotation_index},resolved.signingRotationIndex)}function buildKeyring({handle:handle2,mnemonic,canonicalDvmId,rotationIndex},signingRotationIndex=rotationIndex){const keypairsByPubkey=new Map;let currentKeypair;for(let i=0;i<=rotationIndex;i++){const kp=deriveBuilderLockKeypair(mnemonic,canonicalDvmId,i);keypairsByPubkey.set(toLockPubkey(kp.pubkey),kp);if(i===signingRotationIndex)currentKeypair=kp}if(!currentKeypair){throw new Error("unreachable: signing rotation index walk produced no keypair")}return{handle:handle2,canonicalDvmId,rotationIndex,currentKeypair,keypairsByPubkey}}function readBuilderContext(dvmId){const mnemonic=requireBuilderMnemonic();const entry=requireSelectedBuilderDvm(dvmId);return{handle:entry.handle,mnemonic,canonicalDvmId:entry.canonical_dvm_id,rotationIndex:entry.current_rotation_index}}function readBuilderContextByHandle(handle2){const mnemonic=requireBuilderMnemonic();const entry=requireBuilderDvmByHandle(handle2);return{handle:entry.handle,mnemonic,canonicalDvmId:entry.canonical_dvm_id,rotationIndex:entry.current_rotation_index}}function requireBuilderMnemonic(){const mnemonic=readBuilderMnemonic();if(!mnemonic){throw new DvmError7("no_builder_mnemonic","No builder mnemonic found.","Run `dvmctl lock create` first to generate or import a mnemonic.")}return mnemonic}async function resolveBuilderEntryByHandle(handle2,mnemonic,endpoint){let ambiguity;try{const entry=requireBuilderDvmByHandle(handle2);return{entry,signingRotationIndex:entry.current_rotation_index}}catch(err){if(!(err instanceof DvmError7)||err.code!=="ambiguous_dvm_handle"||!endpoint){throw err}ambiguity=err}const advertised=await readAdvertisedCurrentLockPubkey(endpoint);if(!advertised)throw ambiguity;const candidates=findBuilderDvmsByHandle(handle2);const matching=candidates.flatMap(entry=>{const signingRotationIndex=matchingRotationIndex(entry,mnemonic,advertised);return signingRotationIndex===void 0?[]:[{entry,signingRotationIndex}]});if(matching.length===1)return matching[0];const candidateIds=candidates.map(entry=>entry.canonical_dvm_id);const matchingIds=matching.map(({entry})=>entry.canonical_dvm_id);const diagnostic=matching.length===0?`None of your entries derive the key this DVM advertises (${advertised}) across their recorded rotation indexes.`:`${matching.length} of your entries derive the key this DVM advertises (${advertised}), so the endpoint cannot settle which record is right.`;throw new DvmError7("ambiguous_dvm_handle",ambiguity.message,`${diagnostic} Candidates: ${candidateIds.join(", ")}.${matchingIds.length>0?` Matching candidates: ${matchingIds.join(", ")}.`:""} Restore the correct entry or rotation index in ${BUILDER_FILE}; nothing uses a guessed identity because the wrong keys would strand proofs.`,{advertised_lock_pubkey:advertised,candidates:candidateIds,matching_candidates:matchingIds})}async function readAdvertisedCurrentLockPubkey(endpoint){try{const provider=await createDvmTransport().describe({endpoint:endpoint.replace(/\/+$/,"")},{timeoutMs:DVM_INFO_PROBE_TIMEOUT_MS});const current=provider.cashu?.lock_pubkeys[0];return typeof current==="string"&&COMPRESSED_PUBKEY_PATTERN.test(current.trim())?toLockPubkey(current):void 0}catch{return void 0}}function matchingRotationIndex(entry,mnemonic,advertised){for(let i=0;i<=entry.current_rotation_index;i++){const derived=deriveBuilderLockKeypair(mnemonic,entry.canonical_dvm_id,i);if(toLockPubkey(derived.pubkey)===advertised)return i}return void 0}var DVM_INFO_PROBE_TIMEOUT_MS,COMPRESSED_PUBKEY_PATTERN;var init_builder_lock_identity=__esm({"src/lib/cashu/builder-lock-identity.ts"(){"use strict";init_builder_store();init_defaults();init_builder_mnemonic();init_transport();DVM_INFO_PROBE_TIMEOUT_MS=5e3;COMPRESSED_PUBKEY_PATTERN=/^0[23][0-9a-f]{64}$/i}});function blockUntilShutdown(getServer){let shuttingDown=false;const shutdown=()=>{if(shuttingDown)return;shuttingDown=true;void Promise.resolve(getServer().close()).finally(()=>process.exit(0))};process.once("SIGINT",shutdown);process.once("SIGTERM",shutdown);return new Promise(()=>{})}var init_keep_alive=__esm({"src/lib/keep-alive.ts"(){"use strict"}});import{existsSync as existsSync5,readFileSync as readFileSync5}from"fs";import{basename as basename2,resolve as resolve3}from"path";import{buildAttestation,deriveReceiptKeypair,DvmError as DvmError16,loadIdentitySecret,signAttestation}from"@dvmkit/sdk/internal";function signDeployAttestation(args){const receipt=args.withReceiptKey?deriveReceiptKeypair(args.builderSecret,args.dvmId):void 0;const payload=buildAttestation({dvmId:args.dvmId,slug:args.slug,capabilities:args.capabilities,builderPubkey:args.builderPubkey,receiptPubkey:receipt?.pubkey});return{identityPubkey:args.builderPubkey,payload,signature:signAttestation(payload,args.builderSecret),capabilities:args.capabilities,receiptSecret:receipt?.secret}}function buildDeployAttestation(cwd,slug,dvmId,opts={}){const pubkey=loadIdentityPubkey();const secret=loadIdentitySecret();if(!pubkey||!secret){throw new DvmError16("identity_required","Builder identity is missing or partial (pubkey \u2260 secret on disk).","Run `dvmctl identity create --force` to regenerate.")}return signDeployAttestation({builderSecret:secret,builderPubkey:pubkey,dvmId,slug,capabilities:readCapabilitiesForAttestation(cwd),withReceiptKey:opts.withReceiptKey})}function attestationEnv(attestation){const env2={DVMKIT_BUILDER_PUBKEY:attestation.identityPubkey,DVMKIT_BUILDER_ATTESTATION:JSON.stringify(attestation.payload),DVMKIT_BUILDER_SIGNATURE:attestation.signature,DVMKIT_DVM_ID:attestation.payload.dvm_id,DVMKIT_CANONICAL_DVM_ID:attestation.payload.dvm_id};if(attestation.receiptSecret)env2.DVMKIT_RECEIPT_KEY=attestation.receiptSecret;return env2}function requireBuilderIdentity(){if(loadIdentitySecret()===null){throw new DvmError16("identity_required","No builder identity found.","Run `dvmctl identity create` once on this workstation, then re-run `dvmctl deploy`.")}}function readCapabilitiesForAttestation(cwd){const pkg=readPackageJson(cwd);const dvmkit=pkg?.dvmkit;if(dvmkit==null||typeof dvmkit!=="object")return{};const raw2=dvmkit.capabilities;if(raw2===void 0)return{};if(raw2===null||typeof raw2!=="object"){throw new DvmError16("invalid_capabilities","`package.json#dvmkit.capabilities` must be an object or an array of capability names (or omitted).","Remove the field, declare an array of capability names, or replace it with an object literal.")}return raw2}function deriveSlug(cwd){const raw2=readPackageJson(cwd)?.name??basename2(cwd);return slugify2(raw2)}function slugify2(input){const slug=input.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");return slug.slice(0,40).replace(/-$/,"")}function readPackageJson(cwd){const pkgPath=resolve3(cwd,"package.json");if(!existsSync5(pkgPath))return null;try{return JSON.parse(readFileSync5(pkgPath,"utf-8"))}catch{return null}}var ATTESTATION_ENV_KEYS;var init_deploy_attestation=__esm({"src/lib/deploy-attestation.ts"(){"use strict";init_builder_store();ATTESTATION_ENV_KEYS=["DVMKIT_BUILDER_PUBKEY","DVMKIT_BUILDER_ATTESTATION","DVMKIT_BUILDER_SIGNATURE","DVMKIT_RECEIPT_KEY","DVMKIT_DVM_ID","DVMKIT_CANONICAL_DVM_ID"]}});import{readFileSync as readFileSync6}from"fs";import{resolve as resolve4}from"path";import{DvmError as DvmError17}from"@dvmkit/sdk/internal";function parseProjectEnvironment(content){const env2={};for(const line of content.split("\n")){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;const eqIdx=trimmed.indexOf("=");if(eqIdx===-1)continue;const key=trimmed.slice(0,eqIdx).trim();if(!key)continue;let value=trimmed.slice(eqIdx+1).trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'")){value=value.slice(1,-1)}env2[key]=value}return env2}function loadProjectEnvironment(cwd=process.cwd()){const envPath=resolve4(cwd,".env");try{return parseProjectEnvironment(readFileSync6(envPath,"utf8"))}catch(err){if(errorCode(err)==="ENOENT")return{};const code=errorCode(err);throw new DvmError17("project_env_unreadable","Could not read the project .env file.",`Check that ${envPath} is a readable file and its parent directory is accessible.`,{path:envPath,...code?{error_code:code}:{}})}}function mergeProjectEnvironment(parent,project){const inherited={};for(const[key,value]of Object.entries(parent)){if(value!==void 0)inherited[key]=value}return{...inherited,...project}}function errorCode(err){return typeof err==="object"&&err!==null&&"code"in err&&typeof err.code==="string"?err.code:void 0}var init_dev_environment=__esm({"src/lib/dev-environment.ts"(){"use strict"}});import{pathToFileURL}from"url";import{configureDVM,isConfiguredDVMDescriptor}from"@dvmkit/sdk";function isDescriptor(value){return isConfiguredDVMDescriptor(value)}async function loadDescriptor(modulePath,opts={}){if(opts.onImport)await registerTsx(opts.onImport);else await registerTsxIfNeeded(modulePath);const url2=modulePath.startsWith("file://")?modulePath:pathToFileURL(modulePath).href;const mod2=await import(url2);const preferred=[mod2.default,mod2.dvm];for(const value of preferred){const descriptor=descriptorFromExport(value,modulePath);if(descriptor)return descriptor}for(const value of Object.values(mod2)){const descriptor=descriptorFromExport(value,modulePath);if(descriptor)return descriptor}throw new Error(`No DVMDescriptor found in ${modulePath}. Export a configureDVM() result as default, "dvm", or any named export.`)}function descriptorFromExport(value,modulePath){if(isDescriptor(value))return value;if(!isDescriptorSketch(value))return void 0;const{config:config2,capabilities:_resolvedCapabilities,inputSchema,...topLevel}=value;const normalizedConfig={...topLevel,...inputSchema!==void 0?{input:inputSchema}:{},...config2};if(typeof normalizedConfig.name!=="string"){throw new Error(`Invalid DVM descriptor export in ${modulePath}: missing required "name" field.`)}try{return configureDVM(normalizedConfig)}catch(err){const message2=err instanceof Error?err.message:String(err);throw new Error(`Invalid DVM descriptor export in ${modulePath}: ${message2}`,{cause:err})}}function isDescriptorSketch(value){if(!isRecord(value)||!isRecord(value.config))return false;return"onJob"in value.config||"capabilities"in value.config}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}async function registerTsxIfNeeded(path){if(!path.endsWith(".ts"))return;await registerTsx()}async function registerTsx(onImport){if(tsxRegistered)return;try{const tsx=await import("tsx/esm/api");tsx.register(onImport?{onImport}:void 0);tsxRegistered=true}catch{}}var tsxRegistered;var init_load_handler=__esm({"src/lib/load-handler.ts"(){"use strict";tsxRegistered=false}});var dev_exports={};__export(dev_exports,{DevPaymentTracker:()=>DevPaymentTracker,dev:()=>dev,printStartup:()=>printStartup,resolveDevEnvironment:()=>resolveDevEnvironment,startReloadingSession:()=>startReloadingSession});import{spawn as spawn2}from"child_process";import{realpathSync as realpathSync2,watch}from"fs";import{basename as basename4,dirname as dirname4,join as join8,resolve as resolve8}from"path";import{fileURLToPath as fileURLToPath2}from"url";import{serve}from"@dvmkit/sdk/server";async function dev(handlerPath,opts){const absPath=resolve8(process.cwd(),handlerPath);if(process.env[WORKER_ENV]==="1"&&process.send){await runDevWorker(absPath);return}const env2=resolveDevEnvironment();const configuredPort=Object.hasOwn(env2,"PORT")?env2.PORT:void 0;const port=Number(opts.port??configuredPort??"3000");const payments=new DevPaymentTracker;if(opts.reload===false){const descriptor=await loadDescriptor(absPath);const server=await startServer(descriptor,port,env2,event=>{payments.observe(event)});printStartup(descriptor,port,server.paymentModes);payments.installExitSummary();await blockUntilShutdown(()=>server);return}const session=await startReloadingSession({entry:absPath,port,env:env2,payments});payments.installExitSummary();await blockUntilShutdown(()=>session)}function resolveDevEnvironment(cwd=process.cwd(),parent=process.env){return mergeProjectEnvironment(parent,loadProjectEnvironment(cwd))}async function startReloadingSession(opts){const command=opts.workerCommand??defaultWorkerCommand();const debounceMs=opts.debounceMs??300;const emit2=opts.onEvent??(()=>void 0);const spawnWorker=()=>{const worker=new DevWorker(command,opts.entry,opts.port,opts.env,opts.payments);emit2({type:"starting",pid:worker.pid});return worker};let active=null;let candidate=null;let graph=[opts.entry];const lifecycle={stopping:false};const isStopping=()=>lifecycle.stopping;let pending3=false;let debounce=null;let draining=null;const watcher=new GraphWatcher(()=>{if(isStopping())return;if(debounce)clearTimeout(debounce);debounce=setTimeout(()=>{debounce=null;pending3=true;draining??=drain().finally(()=>{draining=null})},debounceMs)});const adopt=(worker,files)=>{active=worker;graph=union2([opts.entry],files);watcher.watch(graph);worker.onUnexpectedExit=code=>{if(active!==worker)return;active=null;console.error(`Dev server process exited unexpectedly (${code}). Save a watched file to start it again.`);emit2({type:"exited",pid:worker.pid})};emit2({type:"serving",pid:worker.pid,files})};const reloadOnce=async()=>{console.log("\nFile changed, reloading...");const next=spawnWorker();candidate=next;try{const loaded2=await next.loaded;if(isStopping())return;if(!loaded2.ok){graph=union2(graph,loaded2.files);watcher.watch(graph);console.error(`Reload failed: ${loaded2.message}`);console.log(active?"Still serving the previous version. Fix the error and save again.":"No version is serving. Fix the error and save again.");emit2({type:"reload-failed",message:loaded2.message,serving:active!==null});return}const previous=active;active=null;if(previous)await previous.close();if(isStopping())return;try{await next.listen()}catch(err){if(isStopping())return;const message2=errorMessage(err);graph=union2(graph,loaded2.files);watcher.watch(graph);console.error(`Reload failed: ${message2}`);console.log("No version is serving. Fix the error and save again.");emit2({type:"reload-failed",message:message2,serving:false});return}if(isStopping())return;adopt(next,loaded2.files)}finally{candidate=null;if(active!==next)await next.kill()}};const drain=async()=>{while(pending3&&!isStopping()){pending3=false;await reloadOnce()}};const first=spawnWorker();const loaded=await first.loaded;if(!loaded.ok){await first.kill();throw new Error(loaded.message)}try{await first.listen()}catch(err){await first.kill();throw err}adopt(first,loaded.files);return{close:async()=>{lifecycle.stopping=true;pending3=false;if(debounce)clearTimeout(debounce);watcher.close();await candidate?.kill();await draining;await active?.close()}}}function printStartup(descriptor,port,paymentModes){console.log("");console.log(` Dev server running at http://localhost:${port}`);console.log(` Name: ${descriptor.name}`);console.log(` Tags: ${descriptor.tags.join(", ")}`);if(descriptor.price!==void 0)console.log(` Price: ${JSON.stringify(descriptor.price)}`);printPaymentMode(paymentModes);console.log("");console.log(` Test page: http://localhost:${port}/_dev`);console.log("");console.log(` First call:`);console.log(firstCall(descriptor,port,paymentModes));console.log("")}async function runDevWorker(entry){Reflect.deleteProperty(process.env,WORKER_ENV);const send=message2=>new Promise(done=>{if(!process.connected||!process.send){done();return}process.send(message2,void 0,{},()=>{done()})});process.on("SIGINT",()=>void 0);process.on("SIGTERM",()=>void 0);const inFlight=new Set;const forward=message2=>{const sent=send(message2).finally(()=>inFlight.delete(sent));inFlight.add(sent);return sent};let server=null;let exiting=false;const exit=async code=>{if(!exiting){exiting=true;await server?.close();await Promise.all(inFlight)}process.exit(code)};process.once("disconnect",()=>void exit(0));const messages=messageQueue();const start=await messages.next("start");const imported=new Set;let descriptor;try{descriptor=await loadDescriptor(entry,{onImport:url2=>imported.add(url2)})}catch(err){await loaderSettled();await send({type:"load-failed",message:errorMessage(err),files:localFiles(imported)});return exit(1)}await loaderSettled();await send({type:"loaded",files:localFiles(imported)});await messages.next("listen");try{server=await startServer(descriptor,start.port,start.env,event=>forward({type:"paid",event}))}catch(err){await send({type:"listen-failed",message:errorMessage(err)});return exit(1)}printStartup(descriptor,start.port,server.paymentModes);await send({type:"listening"});await messages.next("close");return exit(0)}function messageQueue(){const received=[];const waiters=[];process.on("message",raw2=>{received.push(raw2);for(const wake of waiters.splice(0))wake()});return{next:async type=>{for(;;){const index=received.findIndex(message2=>message2.type===type);if(index!==-1){return received.splice(index,1)[0]}await new Promise(wake=>waiters.push(wake))}}}}function loaderSettled(){return new Promise(done=>setTimeout(done,25))}function localFiles(urls){const files=new Set;for(const url2 of urls){if(!url2.startsWith("file:"))continue;const path=fileURLToPath2(url2.split("?")[0]);if(path.split(/[\\/]/).includes("node_modules"))continue;files.add(path)}return[...files]}function canonicalPath(file2){try{return join8(realpathSync2.native(dirname4(file2)),basename4(file2))}catch{return file2}}function defaultWorkerCommand(){const nodeFlags=process.execArgv.filter(flag=>!flag.startsWith("--inspect"));return[process.execPath,...nodeFlags,process.argv[1]]}function union2(a,b2){return[...new Set([...a,...b2])]}function errorMessage(err){return err instanceof Error?err.message:String(err)}async function startServer(descriptor,port,env2,onPaid){const mintsRaw="DVMKIT_CASHU_MINTS"in env2?env2.DVMKIT_CASHU_MINTS:void 0;const mints=mintsRaw?mintsRaw.split(",").map(m=>m.trim()):void 0;return serve(descriptor,{port,env:env2,devMode:true,mints,onPaidJobCompleted:onPaid})}function printPaymentMode(paymentModes){const rails=["cashu","x402","tempo"];const configured=new Set;let verificationRequired=false;let verifierAvailable=false;for(const mode of paymentModes){if(mode.verification==="required")verificationRequired=true;for(const[rail,state]of Object.entries(mode.rails)){if(state.status!=="absent")configured.add(rail);if(mode.verification==="required"&&state.status==="verifying"){verifierAvailable=true}}}for(const rail of rails){const states=paymentModes.map(mode=>mode.rails[rail]);const state=states.find(candidate=>candidate.status!=="absent")??states[0];if(state.status==="absent"){console.log(` ${rail}: absent (not configured)`)}else{const funds=state.testFunds===true?"test funds":state.testFunds===false?"live funds":"fund type unknown";console.log(` ${rail}: ${state.status} (${funds})`)}}if(configured.size===0){console.log(" Payments: skipped; no payment rail is configured");console.log(" Enable Cashu with DVMKIT_CASHU_MINTS, x402 with DVMKIT_X402_PAY_TO, or Tempo with DVMKIT_TEMPO_RECIPIENT.");console.log(" dev_auto: /_dev may approve synthetic payments; CLI calls are free in this mode.");return}if(verificationRequired&&!verifierAvailable){console.log(" Payments: required but unavailable; paid CLI calls fail closed")}else{console.log(` Payments: ${verificationRequired?"real verification":"skipped"}`)}console.log(" dev_auto: applies only to /_dev; caller CLI payments use the configured verifier.")}function firstCall(descriptor,port,paymentModes){const capabilities=Object.entries(descriptor.capabilities);if(capabilities.length!==1){const names=capabilities.map(([name])=>name).join(", ");const first=capabilities[0]?.[0]??"<capability>";return` Local endpoint calls cannot select among ${names||"multiple capabilities"}. Use /_dev, or after deployment run dvm request -d <handle>--<slug>/${first} --data <json>.`}const capability=capabilities[0][1];const data=capability.example??"hello";const rail=effectiveRail(paymentModes);if(paymentModes.some(mode=>mode.verification==="required")&&!rail){return" No paid caller command is available until a configured payment verifier recovers."}const cap=typeof capability.price==="string"?capability.price:void 0;const payment=rail&&cap?` --rail ${rail} --budget ${shellQuote2(cap)} --auto-pay-below ${shellQuote2(cap)} --max-increment ${shellQuote2(cap)} --max-payments 1`:"";return` dvm request --endpoint http://localhost:${port} --data ${shellQuote2(JSON.stringify(data))}${payment} </dev/null`}function effectiveRail(paymentModes){for(const rail of["cashu","tempo","x402"]){if(paymentModes.some(mode=>mode.rails[rail].status==="verifying"))return rail}return void 0}function shellQuote2(value){return`'${value.replaceAll("'",`'\\''`)}'`}function formatMoney(amountMicro,currency){const amount2=(amountMicro/1e6).toFixed(6).replace(/\.?0+$/,"");return currency.toLowerCase()==="usd"?`$${amount2} USD`:`${amount2} ${currency.toUpperCase()}`}var DevPaymentTracker,WORKER_ENV,WORKER_CLOSE_TIMEOUT_MS,DevWorker,GraphWatcher;var init_dev=__esm({"src/commands/dev.ts"(){"use strict";init_dev_environment();init_keep_alive();init_load_handler();DevPaymentTracker=class{jobs=new Set;totals=new Map;observe(event){if(this.jobs.has(event.jobId))return;this.jobs.add(event.jobId);const classification=event.testFunds===true?"test":event.testFunds===false?"live":"unknown";const key=`${event.currency}:${classification}`;const prior=this.totals.get(key);this.totals.set(key,{amountMicro:(prior?.amountMicro??0)+event.amountMicro,currency:event.currency,testFunds:event.testFunds});const funds=event.testFunds===true?" test funds":event.testFunds===false?" live funds":" funds not classified";console.log(` Paid job ${event.jobId}: ${formatMoney(event.amountMicro,event.currency)} via ${event.rail}${funds}`);console.log(` Session total (${this.jobs.size} job${this.jobs.size===1?"":"s"}): ${this.totalDisplay()}`)}printSummary(){if(this.jobs.size===0){console.log(" Session total: no paid jobs.");return}console.log(` Session total (${this.jobs.size} paid job${this.jobs.size===1?"":"s"}): ${this.totalDisplay()}`)}installExitSummary(){const print=()=>{this.printSummary()};process.once("SIGINT",print);process.once("SIGTERM",print)}totalDisplay(){return[...this.totals.values()].map(({amountMicro,currency,testFunds})=>{const classification=testFunds===true?"test funds":testFunds===false?"live funds":"funds not classified";return`${formatMoney(amountMicro,currency)} ${classification}`}).join(" + ")}};WORKER_ENV="DVMKIT_DEV_WORKER";WORKER_CLOSE_TIMEOUT_MS=5e3;DevWorker=class{pid;loaded;onUnexpectedExit=null;child;exited;listening=null;closing=false;constructor(command,entry,port,env2,payments){const[executable,...args]=command;this.child=spawn2(executable,[...args,"dev",entry],{env:{...process.env,[WORKER_ENV]:"1"},stdio:["ignore","inherit","inherit","ipc"]});this.pid=this.child.pid??-1;let settleLoad=()=>void 0;this.loaded=new Promise(done=>{settleLoad=done});this.exited=new Promise(done=>{this.child.once("exit",(code,signal)=>{const status2=signal??`exit code ${String(code)}`;settleLoad({ok:false,message:`the handler process ended before it loaded (${status2})`,files:[]});this.listening?.reject(new Error(`the handler process ended (${status2})`));this.listening=null;if(!this.closing)this.onUnexpectedExit?.(status2);done()})});this.child.once("error",err=>{settleLoad({ok:false,message:`could not start the handler process: ${err.message}`,files:[]})});this.child.on("message",raw2=>{const message2=raw2;switch(message2.type){case"loaded":settleLoad({ok:true,files:message2.files});break;case"load-failed":settleLoad({ok:false,message:message2.message,files:message2.files});break;case"listening":this.listening?.resolve();this.listening=null;break;case"listen-failed":this.listening?.reject(new Error(message2.message));this.listening=null;break;case"paid":payments.observe(message2.event);break}});this.send({type:"start",port,env:env2})}listen(){return new Promise((done,fail)=>{this.listening={resolve:done,reject:fail};this.send({type:"listen"})})}async close(){if(!this.running())return;this.closing=true;this.send({type:"close"});const timer=setTimeout(()=>this.child.kill("SIGKILL"),WORKER_CLOSE_TIMEOUT_MS);await this.exited;clearTimeout(timer)}async kill(){if(!this.running())return;this.closing=true;this.child.kill("SIGKILL");await this.exited}running(){return this.child.exitCode===null&&this.child.signalCode===null&&this.pid>0}send(message2){if(this.child.connected)this.child.send(message2)}};GraphWatcher=class{constructor(onChange){this.onChange=onChange}onChange;watchers=new Map;files=new Set;watch(files){const canonical=files.map(canonicalPath);this.files=new Set(canonical);const dirs=new Set(canonical.map(file2=>dirname4(file2)));for(const[dir,watcher]of this.watchers){if(dirs.has(dir))continue;watcher.close();this.watchers.delete(dir)}for(const dir of dirs){if(this.watchers.has(dir))continue;try{const watcher=watch(dir,(_event,filename)=>{if(filename===null||this.files.has(join8(dir,basename4(filename))))this.onChange()});watcher.on("error",()=>{watcher.close();this.watchers.delete(dir)});this.watchers.set(dir,watcher)}catch{}}}close(){for(const watcher of this.watchers.values())watcher.close();this.watchers.clear()}}}});var serve_exports={};__export(serve_exports,{assertProductionDatabase:()=>assertProductionDatabase,attestationEnvOccupied:()=>attestationEnvOccupied,buildServeOpts:()=>buildServeOpts,builderServe:()=>builderServe});import{resolve as resolve9}from"path";import{DvmError as DvmError38,loadIdentitySecret as loadIdentitySecret3}from"@dvmkit/sdk/internal";import{serve as sdkServe}from"@dvmkit/sdk/server";async function builderServe(handlerPath,opts){const absPath=resolve9(process.cwd(),handlerPath);const descriptor=await loadDescriptor(absPath);const identity=opts.dvm?resolveBuilderLockIdentity(opts.dvm):void 0;const attestation=opts.dvm?resolveServeAttestation(process.cwd(),opts.dvm,identity?.canonicalDvmId,process.env):void 0;const serveOpts=buildServeOpts(process.env,opts,identity,attestation);assertProductionDatabase(serveOpts);const{url:url2,close}=await sdkServe(descriptor,serveOpts);console.log(`Serving ${descriptor.name} at ${url2}`);if(identity){console.log(` lock identity: ${identity.handle} (rotation ${identity.rotationIndex})`);console.log(` lock pubkey: ${identity.lockPubkey}`)}if(attestation){console.log(` attested dvm id: ${attestation.payload.dvm_id}`);console.log(` attested slug: ${attestation.payload.slug}`);console.log(` receipt key: ${attestation.payload.receipt_pubkey??"(none)"}`)}else if(opts.dvm){console.log(" receipts: unattested (see the note above)")}await blockUntilShutdown(()=>({close}))}function assertProductionDatabase(opts){if(opts.database)return;throw new DvmError38("production_database_required","Production serving requires a Postgres database.","Set DATABASE_URL to a Postgres connection string, or use `dvmctl dev` for local development.")}function buildServeOpts(env2,opts,identity,attestation){const result={};const port=opts?.port??env2.PORT;if(port)result.port=Number(port);if(env2.DATABASE_URL)result.database=env2.DATABASE_URL;const mintsRaw=env2.DVMKIT_CASHU_MINTS;if(mintsRaw){result.mints=mintsRaw.split(",").map(m=>m.trim())}let serveEnv=env2;if(identity)serveEnv=withLockIdentity(serveEnv,identity);if(attestation)serveEnv={...serveEnv,...attestationEnv(attestation)};result.env=serveEnv;return result}function attestationEnvOccupied(env2){return ATTESTATION_ENV_KEYS.filter(key=>env2[key])}function resolveServeAttestation(cwd,handle2,dvmId,env2){const occupied=attestationEnvOccupied(env2);if(occupied.length>0){console.log(` note: ${occupied.join(", ")} already set \u2014 serving the environment's attestation, not deriving one for --dvm ${handle2}.`);return void 0}const secret=loadIdentitySecret3();const pubkey=loadIdentityPubkey();if(!secret||!pubkey){console.log(` note: no builder identity on disk, so this DVM's receipts will be unattested. Run 'dvmctl identity create' to have --dvm ${handle2} derive and attest a receipt key.`);return void 0}if(!dvmId){throw new DvmError38("durable_dvm_identity_required",`No durable DVM ID is recorded for "${handle2}".`,"Run `dvmctl init <handle> --self-hosted` before serving receipts, then retry.")}return signDeployAttestation({builderSecret:secret,builderPubkey:pubkey,dvmId,slug:handle2,capabilities:readCapabilitiesForAttestation(cwd),withReceiptKey:true})}function withLockIdentity(env2,identity){assertNoConflict(env2,"DVMKIT_CASHU_LOCK_PUBKEY",identity.lockPubkey,identity);assertNoConflict(env2,"DVMKIT_DVM_ID",identity.canonicalDvmId,identity);assertNoConflict(env2,"DVMKIT_CANONICAL_DVM_ID",identity.canonicalDvmId,identity);return{...env2,DVMKIT_CASHU_LOCK_PUBKEY:identity.lockPubkey,DVMKIT_DVM_ID:identity.canonicalDvmId,DVMKIT_CANONICAL_DVM_ID:identity.canonicalDvmId}}function assertNoConflict(env2,key,derived,identity){const existing=env2[key];if(!existing||existing.toLowerCase()===derived.toLowerCase())return;throw new DvmError38("lock_identity_conflict",`${key} is set to "${existing}", but --dvm ${identity.handle} derives "${derived}".`,`Unset ${key} to serve under the builder-store identity, or drop --dvm to serve under the environment's.`)}var init_serve=__esm({"src/commands/builder/serve.ts"(){"use strict";init_builder_lock_identity();init_deploy_attestation();init_keep_alive();init_load_handler();init_builder_store()}});import{realpathSync as realpathSync3}from"fs";import{fileURLToPath as fileURLToPath3}from"url";import{randomTraceId}from"@dvmkit/sdk/internal";var import_index=__toESM(require_commander(),1);var{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{homedir}from"os";import{join}from"path";import{DvmError}from"@dvmkit/sdk/internal";function requireAuth(){const creds=resolveAuth();if(!creds){throw new DvmError("auth_required","Not authenticated.","Set DVMKIT_API_KEY or run `dvmctl auth`.")}return{token:creds.token,platformUrl:process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev"}}function resolveAuth(){const envKey=process.env.DVMKIT_API_KEY;if(envKey){return{token:envKey,account:"api-key"}}return loadAuthToken()}function saveAuthToken(creds){const dir=dvmctlConfigDir();mkdirSync(dir,{recursive:true,mode:448});const configPath=join(dir,"config.json");let config2={};if(existsSync(configPath)){try{config2=JSON.parse(readFileSync(configPath,"utf-8"))}catch{}}config2.auth=creds;writeFileSync(configPath,JSON.stringify(config2,null,2)+"\n",{encoding:"utf-8",mode:384})}function loadAuthToken(){const configPath=join(dvmctlConfigDir(),"config.json");if(!existsSync(configPath))return null;try{const config2=JSON.parse(readFileSync(configPath,"utf-8"));const auth2=config2.auth;if(auth2?.token&&auth2.account)return auth2}catch{}return null}function clearAuthToken(){const configPath=join(dvmctlConfigDir(),"config.json");if(!existsSync(configPath))return;try{const config2=JSON.parse(readFileSync(configPath,"utf-8"));delete config2.auth;writeFileSync(configPath,JSON.stringify(config2,null,2)+"\n","utf-8")}catch{}}function resolveOrgScope(opts={}){return opts.org??loadActiveOrg()??void 0}function loadActiveOrg(){const configPath=join(dvmctlConfigDir(),"config.json");if(!existsSync(configPath))return null;try{const config2=JSON.parse(readFileSync(configPath,"utf-8"));const context=config2.context;return context?.activeOrg??null}catch{return null}}function saveActiveOrg(handle2){const dir=dvmctlConfigDir();mkdirSync(dir,{recursive:true,mode:448});const configPath=join(dir,"config.json");let config2={};if(existsSync(configPath)){try{config2=JSON.parse(readFileSync(configPath,"utf-8"))}catch{}}const existingContext=typeof config2.context==="object"&&config2.context!=null?config2.context:{};config2.context={...existingContext,activeOrg:handle2};writeFileSync(configPath,JSON.stringify(config2,null,2)+"\n",{encoding:"utf-8",mode:384})}function clearActiveOrg(){const configPath=join(dvmctlConfigDir(),"config.json");if(!existsSync(configPath))return;try{const config2=JSON.parse(readFileSync(configPath,"utf-8"));if(typeof config2.context==="object"&&config2.context!=null){const context=config2.context;delete context.activeOrg;if(Object.keys(context).length===0)delete config2.context}writeFileSync(configPath,JSON.stringify(config2,null,2)+"\n","utf-8")}catch{}}function dvmctlConfigDir(){return process.env.DVMCTL_CONFIG_DIR??join(homedir(),".dvmctl")}init_output();init_traceparent();init_http();import{DvmError as DvmError2,isAbortError,providerProseSources,transportErrorCode}from"@dvmkit/sdk/internal";async function platformFetch(input,init2){const method=(init2?.method??(input instanceof Request?input.method:"GET")).toUpperCase();const attempts=method==="GET"||method==="HEAD"?3:1;let lastError;for(let attempt=1;attempt<=attempts;attempt++){try{const res=await dvmFetch(input,init2);const tp=res.headers.get("traceparent");if(tp){const parsed=parseTraceparent(tp);if(parsed)setOutputTraceId(parsed.traceId)}return res}catch(err){if(isAbortError(err)||err instanceof DvmError2)throw err;lastError=err;if(attempt<attempts)await new Promise(resolve10=>setTimeout(resolve10,100*attempt))}}const cause=transportErrorCode(lastError);throw new DvmError2("platform_unreachable",`Could not reach the dvmkit platform after ${attempts} attempt${attempts===1?"":"s"}${cause?` (${cause})`:""}.`,"Check the network connection and retry. No server response was received.",{attempts,method,...cause?{transport_code:cause}:{}})}async function orgScopedError(res,fallbackCode,what,org){const body=await res.json().catch(()=>({}));const scope=org?`org "${org}"`:"your personal context";let hint=body.error?.hint;if(!hint&&org&&res.status===404&&body.error?.code==="not_found"){hint=`No org "${org}" you can see. Check the handle, or ask an admin to invite you.`}if(!hint&&res.status===403){hint=`Your role in ${scope} is too low for this data. Ask an org admin.`}return platformResponseError(body.error?.code??fallbackCode,body.error,`${what} for ${scope}: ${res.status}`,{hint})}function platformResponseError(code,remote,fallbackMessage,local={}){const data=remote?.data||local.data?{...remote?.data??{},...local.data??{}}:void 0;return new DvmError2(code,remote?.message??fallbackMessage,remote?.hint??local.hint,data,remote?.display??local.display,providerProseSources(remote,remote?.data))}async function setHandle(platformUrl,token,handle2){const res=await platformFetch(`${platformUrl}/api/v1/builder/handle`,{method:"PUT",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({handle:handle2})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"handle_failed",body.error,`Failed to set handle: ${res.status}`)}}async function checkHandle(platformUrl,handle2){const res=await platformFetch(`${platformUrl}/api/v1/handle/check/${encodeURIComponent(handle2)}`);return await res.json()}async function addDomain(platformUrl,token,dvmId,domain2){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/domains`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({domain:domain2})});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"domain_failed",body2.error,`Failed to add domain: ${res.status}`)}const body=await res.json().catch(()=>({}));return{hint:body.hint}}async function removeDomain(platformUrl,token,dvmId,domain2){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/domains/${encodeURIComponent(domain2)}`,{method:"DELETE",headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"domain_failed",body.error,`Failed to remove domain: ${res.status}`)}}async function verifyDomain(platformUrl,token,dvmId,domain2){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/domains/${encodeURIComponent(domain2)}/verify`,{method:"POST",headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"verify_failed",body.error,`Failed to verify domain: ${res.status}`)}}async function listDomains(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/domains`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw new DvmError2("domain_failed",`Failed to list domains: ${res.status}`)}const body=await res.json();return body.domains}function scopeLabel(org){return org.personal?"personal":org.handle??org.id}async function listDvms(platformUrl,token,opts={}){const url2=new URL(`${platformUrl}/api/v1/builder/dvms`);if(opts.org)url2.searchParams.set("org",opts.org);const res=await platformFetch(url2,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"list_failed","Failed to list DVMs",opts.org)}return await res.json()}async function getDvm(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"info_failed",body.error,`Failed to get DVM: ${res.status}`)}return await res.json()}async function destroyDvm(platformUrl,token,dvmId,opts){const url2=new URL(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}`);if(opts?.keepDb)url2.searchParams.set("keep_db","true");const res=await platformFetch(url2,{method:"DELETE",headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"destroy_failed",body.error,`Failed to destroy DVM: ${res.status}`)}}async function listBuilderFeedback(platformUrl,token,opts={}){const url2=new URL(`${platformUrl}/api/v1/builder/feedback`);if(opts.dvmId)url2.searchParams.set("dvm_id",opts.dvmId);if(opts.sinceMs!==void 0)url2.searchParams.set("since",String(opts.sinceMs));if(opts.cursor)url2.searchParams.set("cursor",opts.cursor);if(opts.limit!==void 0)url2.searchParams.set("limit",String(opts.limit));if(opts.org)url2.searchParams.set("org",opts.org);const res=await platformFetch(url2,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"feedback_list_failed","Failed to list feedback",opts.org)}return await res.json()}async function updateDvmSettings(platformUrl,token,dvmId,settings){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/settings`,{method:"PATCH",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(settings)});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"settings_update_failed",body.error,`Failed to update DVM settings: ${res.status}`)}return await res.json()}async function getAuthenticatedBuilderProfile(platformUrl,token){const res=await platformFetch(`${platformUrl}/api/v1/builder/me`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"builder_profile_failed",body.error,`Failed to read builder profile: ${res.status}`)}const data=await res.json();return data.builder}async function listBuilderOrgs(platformUrl,token){const res=await platformFetch(`${platformUrl}/api/v1/builder/orgs`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"org_list_failed",body.error,`Failed to list org memberships: ${res.status}`)}const data=await res.json();return data.orgs}async function getOrgMembership(platformUrl,token,handle2){const res=await platformFetch(`${platformUrl}/api/v1/builder/orgs/${encodeURIComponent(handle2)}`,{headers:{Authorization:`Bearer ${token}`}});if(res.status===404){throw new DvmError2("org_not_found",`Org "${handle2}" not found, or you are not a member.`,"Check the handle, or ask an admin to invite you.")}if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"org_lookup_failed",body.error,`Failed to look up org: ${res.status}`)}const data=await res.json();return{handle:data.org.handle,displayName:data.org.displayName,role:data.role}}async function setDvmLockPubkey(platformUrl,token,dvmId,pubkey){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/lock-pubkey`,{method:"PUT",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({pubkey})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError("platform_error",body.error,"Failed to register per-DVM lock pubkey.",{hint:"Ensure the pubkey is a valid 33-byte compressed secp256k1 key (66 hex chars)."})}}async function rotateDvmLockPubkey(platformUrl,token,dvmId,newPubkey){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/rotate-lock-pubkey`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({new_pubkey:newPubkey})});if(!res.ok){const body=await res.json().catch(()=>({}));const code=body.error?.code??"platform_error";throw platformResponseError(code,body.error,`Failed to rotate per-DVM lock pubkey (HTTP ${res.status}).`,{hint:code==="no_op_rotation"?void 0:"Ensure the pubkey is a valid compressed secp256k1 key and the DVM is isolate-tier."})}return await res.json()}async function validateAuth(platformUrl,token){const res=await platformFetch(`${platformUrl}/api/v1/builder/auth/me`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw new DvmError2("auth_failed","Invalid API key.","Check your DVMKIT_API_KEY or run `dvmctl auth`.")}}async function startDeploy(platformUrl,token,opts){const form=new FormData;if(opts.tarball){form.append("tarball",new Blob([new Uint8Array(opts.tarball)]),"project.tar.gz")}form.append("metadata",JSON.stringify({slug:opts.slug,name:opts.name,env:opts.env,runtime:opts.runtime,commit:opts.commit,vmConfig:opts.vmConfig,inheritSecrets:opts.inheritSecrets,features:opts.features,endpointUrl:opts.endpointUrl,dockerfilePath:opts.dockerfilePath,orgHandle:opts.orgHandle,lockPubkey:opts.lockPubkey,expectLockPubkey:opts.expectLockPubkey,expectIdentityFinalization:opts.expectIdentityFinalization,identityPubkey:opts.identityPubkey,attestationPayload:opts.attestationPayload,attestationSignature:opts.attestationSignature,capabilities:opts.capabilities}));const res=await platformFetch(`${platformUrl}/api/v1/builder/deploy`,{method:"POST",headers:{Authorization:`Bearer ${token}`},body:form});if(!res.ok){const body2=await res.json().catch(()=>({}));const code=body2.error?.code??"deploy_failed";throw platformResponseError(code,body2.error,`Deploy failed with status ${res.status}`)}const body=await res.json();if(typeof body.deployId!=="string"||typeof body.dvmId!=="string"||typeof body.slug!=="string"){throw new DvmError2("platform_response_invalid","Platform deploy response is missing required fields (deployId, dvmId, or slug).","Your platform may be outdated. Update it with: fly deploy --config fly.platform.toml")}return body}async function finalizeDvmDeployIdentity(platformUrl,token,dvmId,opts){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/deploy-identity`,{method:"PUT",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(opts)});if(res.ok)return;const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"deploy_identity_finalize_failed",body.error,`Identity finalization failed with status ${res.status}`)}async function deployLocal(platformUrl,token,opts){const res=await platformFetch(`${platformUrl}/api/v1/builder/deploy/local`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({slug:opts.slug,name:opts.name,url:opts.url,runtime:opts.runtime,identityPubkey:opts.identityPubkey,attestationPayload:opts.attestationPayload,attestationSignature:opts.attestationSignature,capabilities:opts.capabilities,orgHandle:opts.orgHandle})});if(!res.ok){const body=await res.json().catch(()=>({}));const code=body.error?.code??"local_deploy_failed";throw platformResponseError(code,body.error,`Local deploy failed with status ${res.status}`,{hint:code==="local_deploy_disabled"?"Start the local stack with `npm run dev:stack` (it sets DVMKIT_ALLOW_LOCAL_DEPLOY=true).":void 0})}return await res.json()}var DEPLOY_POLL_INTERVAL_MS=15e3;async function getDeployStatus(platformUrl,token,deployId){const res=await platformFetch(`${platformUrl}/api/v1/builder/deploys/${encodeURIComponent(deployId)}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"deploy_status_failed",body.error,`Failed to get deploy status: ${res.status}`)}return await res.json()}async function streamDeployLogs(platformUrl,token,deployId,opts){const pollIntervalMs=opts.pollIntervalMs??DEPLOY_POLL_INTERVAL_MS;const recoveryTimeoutMs=opts.recoveryTimeoutMs??75e3;const startTime=Date.now();const abortController=new AbortController;let acceptedRelease;let lastTransportError;let recoveryTimer;let streamLost=false;const state={settled:false};const isSettled=()=>state.settled;let resolveOuter;let rejectOuter;const outerPromise=new Promise((res,rej)=>{resolveOuter=res;rejectOuter=rej});const resolve10=result=>{if(isSettled())return;state.settled=true;abortController.abort();resolveOuter(result)};const reject=err=>{if(isSettled())return;state.settled=true;abortController.abort();rejectOuter(err)};const pollerInterval=setInterval(()=>{if(isSettled())return;void getDeployStatus(platformUrl,token,deployId).then(({deploy:deploy2,dvm,recovery})=>{if(isSettled())return;opts.onPhase?.({status:deploy2.status,elapsedMs:Date.now()-startTime});if(deploy2.status==="deployed"){resolve10({url:dvm.url??"",status:acceptedRelease&&streamLost?"deployed_unverified":"deployed",dvmkitUrl:dvm.dvmkitUrl??null})}else if(deploy2.status==="failed"||deploy2.status==="superseded"){const providerMessage=deploy2.error??void 0;const healthFailure=deploy2.releaseAcceptedAt!=null;reject(new DvmError2(deploy2.status==="superseded"?"deploy_superseded":healthFailure?"deploy_health_verification_failed":"deploy_failed",providerMessage??(deploy2.status==="superseded"?"Deploy was superseded by a recovery rollout.":"Deploy failed"),void 0,healthFailure?{release_accepted:true,rollback:recovery?{attempted:true,status:recovery.status,deploy_id:recovery.deployId,target_deploy_id:recovery.targetDeployId,error:recovery.error}:{attempted:false,status:"not_available"}}:void 0,void 0,providerMessage?{message:"provider"}:void 0))}},err=>{lastTransportError=err})},pollIntervalMs);void(async()=>{try{const streamOnce=async()=>{try{return await streamDeployLogsOnce(platformUrl,token,deployId,opts.onLog,release=>{acceptedRelease=release;opts.onAccepted?.(release)},abortController.signal)}catch(err){if(isAbortError(err))throw err;if(!isDeployStreamTransportError(err))throw err;lastTransportError=err;streamLost=true;return{kind:"dropped"}}};const first=await streamOnce();if(isSettled())return;if(first.kind==="result"){resolve10(first.result);return}if(first.kind==="error"){reject(acceptedRelease?deployAcceptedReleaseError(deployId,acceptedRelease,first.error):first.error);return}streamLost=true;await new Promise(r=>setTimeout(r,opts.streamRetryDelayMs??1500));if(isSettled())return;const second=await streamOnce();if(isSettled())return;if(second.kind==="result"){resolve10(second.result);return}if(second.kind==="error"){reject(acceptedRelease?deployAcceptedReleaseError(deployId,acceptedRelease,second.error):second.error);return}recoveryTimer=setTimeout(()=>{reject(deployRecoveryError(deployId,acceptedRelease,lastTransportError))},recoveryTimeoutMs);recoveryTimer.unref()}catch(err){if(err?.name==="AbortError")return;reject(err)}})();try{return await outerPromise}finally{clearInterval(pollerInterval);if(recoveryTimer)clearTimeout(recoveryTimer);abortController.abort()}}async function streamDeployLogsOnce(platformUrl,token,deployId,onLog,onAccepted,signal){const url2=`${platformUrl}/api/v1/builder/deploys/${deployId}/logs`;const res=await platformFetch(url2,{headers:{Authorization:`Bearer ${token}`,Accept:"text/event-stream"},signal});if(!res.ok){return{kind:"error",error:new DvmError2("deploy_stream_failed",`Failed to stream deploy logs: ${res.status}`)}}const reader=res.body?.getReader();if(!reader){return{kind:"error",error:new DvmError2("deploy_stream_failed","No response body")}}const decoder3=new TextDecoder;let buffer="";let chunk=await reader.read();while(!chunk.done){const{value}=chunk;buffer+=decoder3.decode(value,{stream:true});const lines=buffer.split("\n");buffer=lines.pop()??"";let currentEvent="";const dataLines=[];for(const line of lines){if(line.startsWith("event: ")){currentEvent=line.slice(7)}else if(line.startsWith("data: ")){dataLines.push(line.slice(6))}else if(line===""&¤tEvent){const currentData=dataLines.join("\n");dataLines.length=0;if(currentEvent==="log"){onLog(currentData)}else if(currentEvent==="accepted"){try{const release=JSON.parse(currentData);if(typeof release.deployId!=="string"||typeof release.url!=="string"||release.commitSha!==null&&typeof release.commitSha!=="string"){throw new Error("invalid accepted-release payload")}onAccepted(release)}catch{return{kind:"error",error:new DvmError2("deploy_stream_failed","Platform returned a malformed accepted-release event.")}}}else if(currentEvent==="complete"){try{return{kind:"result",result:JSON.parse(currentData)}}catch{return{kind:"error",error:new DvmError2("deploy_failed",`Malformed deploy result: ${currentData}`,void 0,void 0,void 0,{message:"provider"})}}}else if(currentEvent==="error"){try{const err=JSON.parse(currentData);return{kind:"error",error:new DvmError2(err.code??"deploy_failed",err.message,void 0,err.releaseAccepted?{release_accepted:true,rollback:err.rollback}:void 0,void 0,{message:"provider"})}}catch{return{kind:"error",error:new DvmError2("deploy_failed",currentData,void 0,void 0,void 0,{message:"provider"})}}}currentEvent=""}}chunk=await reader.read()}return{kind:"dropped"}}function isDeployStreamTransportError(err){return err instanceof DvmError2&&err.code==="platform_unreachable"||err instanceof TypeError||transportErrorCode(err)!==void 0}function deployRecoveryError(deployId,release,transportError){const transportCode=transportError instanceof DvmError2?typeof transportError.data?.transport_code==="string"?transportError.data.transport_code:void 0:transportErrorCode(transportError);if(!release){return new DvmError2("deploy_status_unknown",`Deploy ${deployId} is still running or its final status could not be read.`,`Run \`dvmctl deploy-status ${deployId}\` to recover the authoritative result.`,{deploy_id:deployId,...transportCode?{transport_code:transportCode}:{}})}const verificationUrl=`${release.url.replace(/\/$/,"")}/healthz`;const shaCheck=release.commitSha?`confirm \`gitSha\` is \`${release.commitSha}\``:"read the served `gitSha`";return new DvmError2("deploy_release_accepted_status_unknown",`Fly accepted deploy ${deployId}, but dvmctl could not confirm its final platform status.`,`Run \`curl -s ${verificationUrl}\` and ${shaCheck}; then run \`dvmctl deploy-status ${deployId}\` to recover the platform result.`,{outcome:"partial_success",deploy_id:deployId,release_url:release.url,verification_url:verificationUrl,...release.commitSha?{expected_git_sha:release.commitSha}:{},...transportCode?{transport_code:transportCode}:{}},`Fly accepted deploy ${deployId}; only the final metadata/status confirmation was interrupted.`)}function deployAcceptedReleaseError(deployId,release,terminalError){const verificationUrl=`${release.url.replace(/\/$/,"")}/healthz`;const shaCheck=release.commitSha?`confirm \`gitSha\` is \`${release.commitSha}\``:"read the served `gitSha`";const providerMessage=terminalError.proseSources?.message==="provider";if(terminalError.code==="deploy_health_verification_failed"){return new DvmError2(terminalError.code,terminalError.message,"Inspect the rollback outcome, then fix the candidate process and deploy again.",{outcome:"failed",deploy_id:deployId,release_accepted:true,release_url:release.url,...release.commitSha?{expected_git_sha:release.commitSha}:{},...terminalError.data},`Fly accepted deploy ${deployId}, but the candidate application did not become healthy.`,providerMessage?{message:"provider"}:void 0)}return new DvmError2("deploy_release_accepted_epilogue_failed",`Fly accepted deploy ${deployId}, then the platform reported: ${terminalError.message}`,`Run \`curl -s ${verificationUrl}\` and ${shaCheck}; then run \`dvmctl deploy-status ${deployId}\` to recover the authoritative platform result.`,{outcome:"partial_success",deploy_id:deployId,release_url:release.url,verification_url:verificationUrl,...release.commitSha?{expected_git_sha:release.commitSha}:{},terminal_error_code:terminalError.code,terminal_error:providerMessage?{_source:"provider",text:terminalError.message}:terminalError.message},`Fly accepted deploy ${deployId}, but its post-release finalization reported an error.`,providerMessage?{message:"provider"}:void 0)}async function getMetrics(platformUrl,token,dvmId,hours2){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/metrics?hours=${hours2}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"metrics_failed",body2.error,`Failed to get metrics: ${res.status}`)}const body=await res.json();return body.metrics}async function getEvents(platformUrl,token,dvmId,opts={}){const params=new URLSearchParams;if(opts.since)params.set("since",opts.since);const qs=params.toString()?`?${params.toString()}`:"";const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/events${qs}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"events_failed",body.error,`Failed to get events: ${res.status}`)}return await res.json()}async function getEnv(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/env`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"env_failed",body2.error,`Failed to get env: ${res.status}`)}const body=await res.json();return body.env}async function listSecrets(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/secrets`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"secrets_failed",body2.error,`Failed to list secrets: ${res.status}`)}const body=await res.json();return body.secrets}async function setEnv(platformUrl,token,dvmId,changes){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/env`,{method:"PUT",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(changes)});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"env_failed",body.error,`Failed to update env: ${res.status}`)}}async function getLogs(platformUrl,token,dvmId,opts={}){const params=new URLSearchParams({stream:"false"});if(opts.lines!=null)params.set("lines",String(opts.lines));if(opts.since)params.set("since",opts.since);const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/logs?${params.toString()}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body2=await res.json().catch(()=>({}));throw platformResponseError(body2.error?.code??"logs_failed",body2.error,`Failed to get logs: ${res.status}`)}const body=await res.json();return body.logs}async function execCommand(platformUrl,token,dvmId,command,opts={}){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/exec`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({command,...opts.machine?{machine:opts.machine}:{}})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"ssh_failed",body.error,`SSH command failed: ${res.status}`)}return await res.json()}async function restartMachines(platformUrl,token,dvmId,opts={}){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/restart`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(opts.machine?{machine:opts.machine}:{})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"restart_failed",body.error,`Restart failed: ${res.status}`)}return await res.json()}async function pauseDvm(platformUrl,token,dvmId){return pauseCall(platformUrl,token,dvmId,"pause")}async function resumeDvm(platformUrl,token,dvmId){return pauseCall(platformUrl,token,dvmId,"resume")}async function pauseCall(platformUrl,token,dvmId,verb){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/${verb}`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:"{}"});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??`${verb}_failed`,body.error,`${verb==="pause"?"Pause":"Resume"} failed: ${res.status}`)}return await res.json()}async function scaleDvm(platformUrl,token,dvmId,opts){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/scale`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({...opts.count!==void 0?{count:opts.count}:{},...opts.size!==void 0?{size:opts.size}:{}})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"scale_failed",body.error,`Scale failed: ${res.status}`)}return await res.json()}async function rollbackDvm(platformUrl,token,dvmId,opts={}){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/rollback`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(opts.to?{to:opts.to}:{})});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"rollback_failed",body.error,`Rollback failed: ${res.status}`)}return await res.json()}async function getMachineStatus(platformUrl,token,dvmId){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/status`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"status_failed",body.error,`Status failed: ${res.status}`)}return await res.json()}function buildSshWsUrl(platformUrl,dvmId,machine){const wsBase=platformUrl.replace(/^http(s?):\/\//,(_m,s)=>`ws${s}://`).replace(/\/+$/,"");const query=machine?`?machine=${encodeURIComponent(machine)}`:"";return`${wsBase}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/ssh${query}`}async function openSshSession(platformUrl,token,dvmId,opts={}){if(!process.stdin.isTTY||!process.stdout.isTTY){throw new DvmError2("not_a_tty","An interactive shell requires a terminal.",'Run `dvmctl ssh <slug>` from an interactive terminal, or pass --command "..." for a one-shot command.')}const{default:WebSocket3}=await Promise.resolve().then(()=>(init_wrapper(),wrapper_exports));const url2=buildSshWsUrl(platformUrl,dvmId,opts.machine);return new Promise((resolve10,reject)=>{const ws=new WebSocket3(url2,{headers:{Authorization:`Bearer ${token}`}});const stdin=process.stdin;let exitCode=0;let settled=false;const onStdin=chunk=>{if(ws.readyState===WebSocket3.OPEN)ws.send(chunk)};const finish=done=>{if(settled)return;settled=true;stdin.removeListener("data",onStdin);if(stdin.isTTY)stdin.setRawMode(false);stdin.pause();done()};ws.on("unexpected-response",(_req,res)=>{const chunks=[];res.on("data",d=>chunks.push(d));res.on("end",()=>{let code="ssh_failed";let message2=`Failed to open shell: ${res.statusCode}`;let hint;let remote;try{const body=JSON.parse(Buffer.concat(chunks).toString());if(body.error?.code)code=body.error.code;if(body.error?.message)message2=body.error.message;hint=body.error?.hint;remote=body.error}catch{}finish(()=>{reject(platformResponseError(code,remote,message2,{hint}))})})});ws.on("open",()=>{if(stdin.isTTY)stdin.setRawMode(true);stdin.resume();stdin.on("data",onStdin)});ws.on("message",(data,isBinary)=>{const buf=Buffer.isBuffer(data)?data:Array.isArray(data)?Buffer.concat(data):Buffer.from(data);if(isBinary){process.stdout.write(buf);return}try{const msg=JSON.parse(buf.toString());if(msg.type==="exit"){exitCode=msg.code??0}else if(msg.type==="error"){finish(()=>{reject(new DvmError2("ssh_failed",msg.message??"Remote shell error",void 0,void 0,void 0,msg.message?{message:"provider"}:void 0))})}}catch{process.stdout.write(buf)}});ws.on("close",()=>{finish(()=>{resolve10(exitCode)})});ws.on("error",err=>{finish(()=>{reject(new DvmError2("ssh_failed",err.message))})})})}async function streamLogs(platformUrl,token,dvmId,opts,onLine){const params=new URLSearchParams({stream:"true"});if(opts.since)params.set("since",opts.since);const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/logs?${params.toString()}`,{headers:{Authorization:`Bearer ${token}`,Accept:"text/event-stream"}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"logs_failed",body.error,`Failed to stream logs: ${res.status}`)}const reader=res.body?.getReader();if(!reader){throw new DvmError2("logs_failed","No response body")}const decoder3=new TextDecoder;let buffer="";const readLoop=async()=>{let chunk=await reader.read();while(!chunk.done){buffer+=decoder3.decode(chunk.value,{stream:true});const lines=buffer.split("\n");buffer=lines.pop()??"";let currentEvent="";for(const line of lines){if(line.startsWith("event: ")){currentEvent=line.slice(7)}else if(line.startsWith("data: ")&¤tEvent==="log"){onLine(line.slice(6))}else if(line===""){currentEvent=""}}chunk=await reader.read()}};readLoop().catch(()=>{});return{stop:()=>{void reader.cancel()}}}async function transferDvm(platformUrl,token,dvmId,body){const res=await platformFetch(`${platformUrl}/api/v1/builder/dvms/${encodeURIComponent(dvmId)}/transfer`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(body)});if(!res.ok){const data=await res.json().catch(()=>({}));throw platformResponseError(data.error?.code??"transfer_failed",data.error,`Transfer failed: ${res.status}`)}return await res.json()}async function getRevenueSeries(platformUrl,token,opts){const params=new URLSearchParams({from:opts.from,to:opts.to});if(opts.currency)params.set("currency",opts.currency);if(opts.rail)params.set("rail",opts.rail);if(opts.org)params.set("org",opts.org);const res=await platformFetch(`${platformUrl}/api/v1/builder/revenue/series?${params.toString()}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"revenue_series_failed","Failed to get revenue",opts.org)}return await res.json()}async function getRevenueEvents(platformUrl,token,opts={}){const params=new URLSearchParams;if(opts.from)params.set("from",opts.from);if(opts.to)params.set("to",opts.to);if(opts.currency)params.set("currency",opts.currency);if(opts.rail)params.set("rail",opts.rail);if(opts.limit!==void 0)params.set("limit",String(opts.limit));if(opts.offset!==void 0)params.set("offset",String(opts.offset));if(opts.org)params.set("org",opts.org);const qs=params.toString()?`?${params.toString()}`:"";const res=await platformFetch(`${platformUrl}/api/v1/builder/revenue/events${qs}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"revenue_events_failed","Failed to get revenue events",opts.org)}return await res.json()}async function getRevenueCsv(platformUrl,token,opts){const params=new URLSearchParams({from:opts.from,to:opts.to});if(opts.currency)params.set("currency",opts.currency);if(opts.rail)params.set("rail",opts.rail);if(opts.org)params.set("org",opts.org);const res=await platformFetch(`${platformUrl}/api/v1/builder/revenue/csv?${params.toString()}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"revenue_csv_failed","Failed to get revenue CSV",opts.org)}return{csv:await res.text(),org:res.headers.get("X-Org")??"personal"}}async function listApiKeys(platformUrl,token){const res=await platformFetch(`${platformUrl}/api/v1/builder/api-keys`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"api_keys_failed",body.error,`Failed to list API keys: ${res.status}`)}return await res.json()}async function createApiKey(platformUrl,token,opts={}){const res=await platformFetch(`${platformUrl}/api/v1/builder/api-keys`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify({label:opts.label})});if(!res.ok){const body=await res.json().catch(()=>({}));if(body.error==="api_key_limit_reached"){throw new DvmError2("api_key_limit_reached",`API key limit reached (max ${body.limit??10}).`,"Revoke an unused key first with `dvmctl api-keys revoke <id>`.",void 0,void 0,{message:"provider"})}if(body.error==="label_too_long"){throw new DvmError2("label_too_long",`Label exceeds max length (${body.max??64} chars).`,void 0,void 0,void 0,{message:"provider"})}const msg=body.message;throw new DvmError2("api_key_create_failed",typeof msg==="string"?msg:`Failed to create API key: ${res.status}`,void 0,void 0,void 0,typeof msg==="string"?{message:"provider"}:void 0)}return await res.json()}async function getBuilderTrace(platformUrl,token,traceId,opts={}){const url2=new URL(`${platformUrl}/api/v1/builder/traces/${encodeURIComponent(traceId)}`);if(opts.org)url2.searchParams.set("org",opts.org);const res=await platformFetch(url2,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){throw await orgScopedError(res,"trace_fetch_failed","Failed to fetch trace",opts.org)}return await res.json()}async function deleteApiKey(platformUrl,token,id){const res=await platformFetch(`${platformUrl}/api/v1/builder/api-keys/${encodeURIComponent(id)}`,{method:"DELETE",headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.json().catch(()=>({}));throw platformResponseError(body.error?.code??"api_key_delete_failed",body.error,`Failed to revoke API key: ${res.status}`)}}init_output();async function apiKeysCreate(opts){const{token,platformUrl}=requireAuth();const result=await createApiKey(platformUrl,token,{label:opts.label});if(opts.human){info(" API key created.");info("");info(` Key: ${result.key}`);info(` ID: ${result.id}`);info(` Label: ${result.label}`);info("");info(" Save this key now \u2014 it will not be shown again.")}else{json(result)}}init_output();async function apiKeysList(opts){const{token,platformUrl}=requireAuth();const result=await listApiKeys(platformUrl,token);if(opts.human){if(result.keys.length===0){info(" No API keys.");return}info(` ${result.count}/${result.limit} keys used`);info("");const idW=Math.max(2,...result.keys.map(k2=>k2.id.length));const labelW=Math.max(5,...result.keys.map(k2=>(k2.label??"\u2014").length));info(` ${"ID".padEnd(idW)} ${"LABEL".padEnd(labelW)} ${"PREFIX".padEnd(10)} ${"CREATED".padEnd(19)} LAST USED`);for(const k2 of result.keys){const prefix=k2.key_prefix?`${k2.key_prefix}...`:"\u2014";const created=fmtDate(k2.created_at);const lastUsed=k2.last_used_at?fmtDate(k2.last_used_at):"never";info(` ${k2.id.padEnd(idW)} ${(k2.label??"\u2014").padEnd(labelW)} ${prefix.padEnd(10)} ${created.padEnd(19)} ${lastUsed}`)}}else{json(result)}}function fmtDate(epoch){return new Date(epoch).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}init_output();async function apiKeysRevoke(id,opts){const{token,platformUrl}=requireAuth();await deleteApiKey(platformUrl,token,id);if(opts.human){info(` API key ${id} revoked.`)}else{json({deleted:true,id})}}import{createHash,randomBytes}from"crypto";import{hostname}from"os";var CLI_AUTH_TTL_MS=5*60*1e3;var CLI_AUTH_POLL_INTERVAL_MS=1e3;var CLI_AUTH_POLL_JITTER_MS=500;var CLI_AUTH_MAX_POLL_ATTEMPTS=Math.floor(CLI_AUTH_TTL_MS/CLI_AUTH_POLL_INTERVAL_MS);var CLI_AUTH_FINGERPRINT_LEN=12;var PLATFORM_URL=process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev";var WEB_URL=process.env.DVMKIT_WEB_URL??"https://dvmkit.com";async function auth(opts){if(opts.status){showStatus(opts.human);return}if(opts.logout){logout(opts.human);return}await login(opts.human)}function showStatus(human){const creds=resolveAuth();if(!creds){if(human){console.log("Not authenticated. Run `dvmctl auth` to log in.")}else{console.log(JSON.stringify({authenticated:false}))}return}if(human){console.log(`Authenticated as ${creds.account}`)}else{console.log(JSON.stringify({authenticated:true,account:creds.account}))}}function logout(human){clearAuthToken();if(human){console.log("Logged out.")}else{console.log(JSON.stringify({status:"logged_out"}))}}async function login(human){const existing=loadAuthToken();if(existing){if(human){console.log(`Already authenticated as ${existing.account}. Use --logout to sign out first.`)}else{console.log(JSON.stringify({authenticated:true,account:existing.account}))}return}const sessionId=randomBytes(16).toString("hex");const verifier=randomBytes(32).toString("hex");const verifierHash=createHash("sha256").update(verifier).digest("hex");const host=hostname();const authUrl=`${WEB_URL}/cli-auth?session=${sessionId}&hash=${verifierHash}&host=${encodeURIComponent(host)}`;const fingerprint=sessionId.slice(0,CLI_AUTH_FINGERPRINT_LEN);console.log(`
|
|
2135
2135
|
Opening browser to authenticate...`);console.log(`
|
|
2136
2136
|
${authUrl}
|
|
2137
2137
|
`);console.log(`Session code: ${fingerprint}\u2026 (must match the code shown in your browser)
|
|
@@ -2407,30 +2407,30 @@ describe(${JSON.stringify(opts.name)}, () => {
|
|
|
2407
2407
|
Proxying ${slug}'s database on 127.0.0.1:${handle2.port}
|
|
2408
2408
|
`);info(` DATABASE_URL ${url2}`);info(` user ${handle2.ready.user}`);info(` password ${handle2.ready.password}`);info(` database ${handle2.ready.database}
|
|
2409
2409
|
`);info(` psql "${url2}"`);info(` pg_dump "${url2}" > ${slug}.sql
|
|
2410
|
-
`);info("Press Ctrl-C to close the tunnel.")}else{json({dvmId:target.dvmId,slug,host:"127.0.0.1",port:handle2.port,user:handle2.ready.user,database:handle2.ready.database,database_url:url2,display:`Postgres proxy for ${slug} listening on 127.0.0.1:${handle2.port}.`,hint:`Point any Postgres client at database_url (psql, pg_dump, drizzle-kit, a GUI client). The proxy stays up until it is interrupted.`})}await blockUntilShutdown(()=>handle2)}async function startDbProxy(target,opts){const{token,platformUrl,dvmId}=target;const port=parsePort(opts.port);const opening=new Set;const open=async()=>{const controller=new AbortController;opening.add(controller);try{return await openDbTunnel({platformUrl,token,dvmId,machine:opts.machine,signal:controller.signal})}finally{opening.delete(controller)}};const probe=await open();await probe.close();const tunnels=new Set;const sockets=new Set;const connections=new Set;let closing=false;const server=createServer2(sock=>{sockets.add(sock);sock.once("close",()=>sockets.delete(sock));sock.on("error",()=>{sock.destroy()});if(closing){sock.destroy();return}const connection=serveConnection(sock,open,tunnels,()=>closing,opts.human);connections.add(connection);void connection.then(()=>connections.delete(connection),()=>connections.delete(connection))});await new Promise((resolve10,reject)=>{const onListenError=err=>{reject(new DvmError15("local_listener_failed",`Could not open a local port: ${err.message}`))};server.once("error",onListenError);server.listen(port,"127.0.0.1",()=>{server.off("error",onListenError);server.on("error",err=>{reportError("proxy_error","local_listener_failed",err.message,opts.human)});resolve10()})});let closePromise;const close=()=>{closePromise??=(async()=>{closing=true;for(const controller of opening)controller.abort();const serverClosed=new Promise((resolve10,reject)=>{server.close(err=>{if(err)reject(err);else resolve10()})});for(const socket of sockets)socket.destroy();await Promise.all([...tunnels].map(tunnel=>tunnel.close()));await Promise.all([...connections]);await Promise.all([...tunnels].map(tunnel=>tunnel.close()));await serverClosed;tunnels.clear()})();return closePromise};return{port:server.address().port,ready:probe.ready,close}}function buildDatabaseUrl(ready,port){const user=encodeURIComponent(ready.user);const password=encodeURIComponent(ready.password);const database=encodeURIComponent(ready.database);return`postgres://${user}:${password}@127.0.0.1:${port}/${database}?sslmode=disable`}async function serveConnection(sock,open,tunnels,isClosing,human){let tunnel;try{tunnel=await open()}catch(err){if(!isClosing()){const{code,message:message2}=asDvmError(err);reportError("connection_error",code,message2,human)}sock.destroy();return}if(sock.destroyed||isClosing()){sock.destroy();await tunnel.close();return}tunnels.add(tunnel);sock.on("close",()=>{void tunnel.close().then(()=>tunnels.delete(tunnel))});tunnel.attach(sock)}function reportError(event,code,message2,human){const label=event==="connection_error"?"Connection failed":"Proxy error";if(human)info(`${label}: ${providerTextToString(message2)}`);else progress({event,code,message:message2})}function asDvmError(err){if(err instanceof DvmError15){return{code:err.code,message:err.proseSources?.message==="provider"?asProviderText(err.message):err.message}}return{code:"tunnel_failed",message:err instanceof Error?err.message:String(err)}}function parsePort(raw2){if(raw2===void 0)return 0;const port=Number(raw2);if(!Number.isInteger(port)||port<1||port>65535){throw new DvmError15("invalid_port",`'${raw2}' is not a valid port.`,"Pass --port 1-65535, or omit --port for an OS-assigned one.")}return port}init_builder_mnemonic();init_deploy_attestation();import{execFileSync}from"child_process";import{existsSync as existsSync7,mkdirSync as mkdirSync5,mkdtempSync,readFileSync as readFileSync7,rmSync,writeFileSync as writeFileSync5}from"fs";import{tmpdir}from"os";import{dirname as dirname2,join as join6,relative,resolve as resolve5}from"path";import{createInterface as createInterface2}from"readline";import{deriveBuilderLockKeypair as deriveBuilderLockKeypair2,DvmError as DvmError19,loadIdentitySecret as loadIdentitySecret2}from"@dvmkit/sdk/internal";var InheritSecretsError=class extends Error{constructor(code,message2){super(message2);this.code=code;this.name="InheritSecretsError"}code};var PLATFORM_INTERNAL_PREFIXES=["FLY_","STRIPE_","PLATFORM_","GITHUB_APP_","RESEND_","AVATAR_","FEE_GATE_"];var PLATFORM_INTERNAL_EXACT=["APP_URL","DATABASE_URL","DVMKIT_BUILDER_ID","DVMKIT_BUILDER_PUBKEY","DVMKIT_BUILDER_ATTESTATION","DVMKIT_BUILDER_SIGNATURE","DVMKIT_CASHU_LOCK_PUBKEY","DVMKIT_CASHU_MINTS","DVMKIT_DVM_ID","DVMKIT_FX_SOURCE","DVMKIT_ISOLATE_SECRET","DVMKIT_PLATFORM_CALLBACK","DVMKIT_PLATFORM_TOKEN","DVMKIT_PLATFORM_URL","EXTERNAL_REGISTRY_AUTH_REQUIRED","NPM_TOKEN"];var PATTERN_RE=/^[A-Z][A-Z0-9_]*(\*)?$/;function parseInheritSecrets(raw2){if(raw2===void 0||raw2===null)return[];if(!Array.isArray(raw2)){throw new InheritSecretsError("invalid_inherit_secrets","`inheritSecrets` must be an array of strings.")}return raw2.map(entry=>{if(typeof entry!=="string"){throw new InheritSecretsError("invalid_inherit_secrets","`inheritSecrets` entries must be strings.")}validatePattern(entry);return entry})}function validatePattern(pattern){if(pattern===""){throw new InheritSecretsError("invalid_inherit_secrets","`inheritSecrets` entries must not be empty.")}if(pattern==="*"){throw new InheritSecretsError("invalid_inherit_secrets","`inheritSecrets` does not allow a bare `*` (would forward every platform secret).")}if(!PATTERN_RE.test(pattern)){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` pattern ${JSON.stringify(pattern)} must be uppercase letters, digits, or underscores, optionally ending in '*'.`)}if(pattern.endsWith("*")&&pattern.length-1<3){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` glob ${JSON.stringify(pattern)} needs a literal prefix of at least 3 characters.`)}rejectPlatformInternal(pattern)}function rejectPlatformInternal(pattern){if(!pattern.endsWith("*")){if(PLATFORM_INTERNAL_EXACT.includes(pattern)||PLATFORM_INTERNAL_PREFIXES.some(prefix=>pattern.startsWith(prefix))){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` pattern ${JSON.stringify(pattern)} targets a platform-internal env var; DVMs cannot inherit it.`)}return}const literal2=pattern.slice(0,-1);for(const denied of PLATFORM_INTERNAL_PREFIXES){if(literal2.startsWith(denied)||denied.startsWith(literal2)){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` glob ${JSON.stringify(pattern)} would match the platform-internal namespace ${JSON.stringify(denied)}; DVMs cannot inherit it.`)}}for(const exact of PLATFORM_INTERNAL_EXACT){if(exact.startsWith(literal2)){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` glob ${JSON.stringify(pattern)} would match the platform-internal env var ${JSON.stringify(exact)}; DVMs cannot inherit it.`)}}}var FeatureManifestError=class extends Error{constructor(code,message2){super(message2);this.code=code;this.name="FeatureManifestError"}code};function parseFeatures(raw2){if(raw2===void 0||raw2===null)return{};if(typeof raw2!=="object"||Array.isArray(raw2)){throw new FeatureManifestError("invalid_features","`features` must be an object mapping feature names to their required env keys.")}const out={};for(const[feature,value]of Object.entries(raw2)){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new FeatureManifestError("invalid_features",`\`features.${feature}\` must be an object with \`requires\` and/or \`requiresAny\`.`)}const entry=value;const requires=parseKeyList(feature,"requires",entry.requires);const requiresAny=parseKeyList(feature,"requiresAny",entry.requiresAny);if(requires.length===0&&requiresAny.length===0){throw new FeatureManifestError("invalid_features",`\`features.${feature}\` must declare at least one key in \`requires\` or \`requiresAny\`.`)}const parsed={};if(requires.length>0)parsed.requires=requires;if(requiresAny.length>0)parsed.requiresAny=requiresAny;out[feature]=parsed}return out}var KEY_RE=/^[A-Z][A-Z0-9_]*$/;function parseKeyList(feature,field,raw2){if(raw2===void 0)return[];if(!Array.isArray(raw2)){throw new FeatureManifestError("invalid_features",`\`features.${feature}.${field}\` must be an array of env-var names.`)}for(const entry of raw2){if(typeof entry!=="string"||!KEY_RE.test(entry)){throw new FeatureManifestError("invalid_features",`\`features.${feature}.${field}\` entries must be uppercase env-var names (e.g. "ANTHROPIC_API_KEY"); got ${JSON.stringify(entry)}.`)}}return raw2}var VmConfigError=class extends Error{constructor(code,message2,data){super(message2);this.code=code;this.data=data;this.name="VmConfigError"}code;data};function parseVmConfig(raw2){if(raw2===void 0||raw2===null)return{};if(typeof raw2!=="object"||Array.isArray(raw2)){throw new VmConfigError("invalid_vm_config","`dvmkit` must be an object with VM resource fields.")}const src=raw2;const config2={};const memory2=pick3(src,"memory_mb","memoryMb");if(memory2!==void 0){config2.memoryMb=parseIntInRange(memory2,"memory_mb",256,16384)}const cpu=pick3(src,"cpu_count","cpuCount");if(cpu!==void 0){config2.cpuCount=parseIntInRange(cpu,"cpu_count",1,16)}const kind=pick3(src,"cpu_kind","cpuKind");if(kind!==void 0){if(kind!=="shared"&&kind!=="performance"){throw new VmConfigError("invalid_vm_config",'`cpu_kind` must be "shared" or "performance".')}config2.cpuKind=kind}const minMachines=pick3(src,"min_machines_running","minMachinesRunning");if(minMachines!==void 0){config2.minMachinesRunning=parseIntInRange(minMachines,"min_machines_running",0,8)}const maxMachines=pick3(src,"max_machines","maxMachines");if(maxMachines!==void 0){config2.maxMachines=parseIntInRange(maxMachines,"max_machines",1,8)}if(config2.minMachinesRunning!==void 0&&config2.maxMachines!==void 0&&config2.maxMachines<config2.minMachinesRunning){throw new VmConfigError("invalid_vm_config",`\`max_machines\` (${config2.maxMachines}) must be >= \`min_machines_running\` (${config2.minMachinesRunning}).`)}return config2}function pick3(src,snake,camel){const hasSnake=src[snake]!==void 0;const hasCamel=src[camel]!==void 0;if(hasSnake&&hasCamel){throw new VmConfigError("invalid_vm_config",`\`${snake}\` and \`${camel}\` are both set; use one or the other.`)}return hasSnake?src[snake]:src[camel]}function parseIntInRange(value,field,min,max){if(typeof value!=="number"||!Number.isInteger(value)){throw new VmConfigError("invalid_vm_config",`\`${field}\` must be an integer between ${min} and ${max}.`)}if(value<min||value>max){throw new VmConfigError("invalid_vm_config",`\`${field}\` must be an integer between ${min} and ${max} (got ${value}).`)}return value}init_builder_store();var DIRTY_SUFFIX="-dirty";function splitDirtySha(sha){return sha.endsWith(DIRTY_SUFFIX)?{base:sha.slice(0,-DIRTY_SUFFIX.length),dirty:true}:{base:sha,dirty:false}}function shortSha(sha){const{base:base3,dirty}=splitDirtySha(sha);return base3.slice(0,7)+(dirty?DIRTY_SUFFIX:"")}init_output();init_builder_store();init_defaults();init_output();import{DvmError as DvmError17,generateIdentity,writeIdentity}from"@dvmkit/sdk/internal";function identityCreate(opts){const keypair=generateIdentity();writeIdentity(keypair,{force:opts.force});if(opts.quiet)return;const isWindows=process.platform==="win32";if(opts.human){info("Builder identity created.");info(` pubkey: ${keypair.pubkey}`);info(` secret stored at: ${BUILDER_KEY_FILE}`);if(isWindows){info("");info("\u26A0 Windows does not enforce Unix file permissions. Make sure");info(` ${BUILDER_KEY_FILE} sits on disk-encrypted storage and is`);info(" not synced to shared/backup locations.")}else{info(` mode: 0600 (POSIX)`)}info("");info("`dvmctl deploy` will now sign each deploy with this key. Run");info("`dvmctl identity show` to print the pubkey again later.")}else{json({status:"created",identity_pubkey:keypair.pubkey,secret_path:BUILDER_KEY_FILE,pubkey_path:BUILDER_FILE,...isWindows?{windows_note:"Windows does not enforce Unix file permissions; ensure the secret file lives on disk-encrypted storage."}:{mode:"0600"}})}}function identityShow(opts){const pubkey=loadIdentityPubkey();if(!pubkey){throw new DvmError17("identity_missing","No builder identity exists.","Run `dvmctl identity create` to generate one.")}if(opts.human){info(`identity_pubkey: ${pubkey}`);info(`stored at: ${BUILDER_FILE}`)}else{json({identity_pubkey:pubkey,pubkey_path:BUILDER_FILE})}}init_deploy_attestation();init_load_handler();init_output();import{existsSync as existsSync6,readFileSync as readFileSync6}from"fs";import{resolve as resolve4}from"path";import{isZodSchema}from"@dvmkit/sdk";import{DvmError as DvmError18}from"@dvmkit/sdk/internal";function validateManifest(cwd){if(!existsSync6(resolve4(cwd,"package.json"))){throw new DvmError18("missing_package_json",`No package.json found in ${cwd}.`,"Run this from a DVM project directory.")}const slug=deriveSlug(cwd);const name=readDvmName(cwd)??slug;const vmConfig=readVmConfig(cwd);const inheritSecrets=readInheritSecrets(cwd);const features=readFeatures(cwd);return{slug,name,vmConfig,inheritSecrets,features}}async function validate4(opts,cwd){cwd??=process.cwd();const{slug,name,vmConfig,inheritSecrets,features}=validateManifest(cwd);const featureNames=Object.keys(features);const handlerPath=resolveHandlerPath(cwd,opts.handler);let descriptor;try{descriptor=await loadDescriptor(handlerPath)}catch(err){const message2=err instanceof Error?err.message:String(err);throw new DvmError18("invalid_handler",`Could not load DVM handler ${handlerPath}: ${message2}`,"Fix the handler import or descriptor configuration, then run `dvmctl validate` again.")}const capabilityNames=validateDescriptor(descriptor);if(opts.human){info(`Validating ${name} (${slug}): ok`);if(vmConfig){const mem=vmConfig.memoryMb!=null?`${vmConfig.memoryMb} MB`:"(default)";info(` resources ${mem} / ${vmConfig.cpuCount??1} cpu`)}if(inheritSecrets.length>0){info(` inheritSecrets ${inheritSecrets.length} pattern(s)`)}if(featureNames.length>0){info(` features ${featureNames.join(", ")}`)}info(` handler ${handlerPath}`);info(` capabilities ${capabilityNames.join(", ")}`)}else{json({status:"ok",slug,name,vm_config:vmConfig,inherit_secrets:inheritSecrets.length>0?inheritSecrets:void 0,features:featureNames.length>0?features:void 0,handler:handlerPath,capabilities:capabilityNames,display:`${name} is valid with ${capabilityNames.length} ${capabilityNames.length===1?"capability":"capabilities"}.`,hint:"Run `dvmctl dev <handler>` to make the first local call."})}}function resolveHandlerPath(cwd,requested){if(requested){const path=resolve4(cwd,requested);if(!existsSync6(path)){throw new DvmError18("handler_not_found",`Handler file not found: ${path}.`,"Pass --handler <path> or create handler.ts / handler.js in this project.")}return path}for(const name of["handler.ts","handler.js"]){const path=resolve4(cwd,name);if(existsSync6(path))return path}throw new DvmError18("handler_not_found",`No handler.ts or handler.js found in ${cwd}.`,"Add a handler module or pass --handler <path>. A scaffold is not required.")}function validateDescriptor(descriptor){const entries=Object.entries(descriptor.capabilities);if(entries.length===0){throw new DvmError18("missing_capability","The handler declares no capabilities.")}const names=new Set;for(const[name,capability]of entries){if(names.has(name)){throw new DvmError18("duplicate_capability",`Capability name ${JSON.stringify(name)} is duplicated.`)}names.add(name);if(!/^[a-z0-9][a-z0-9-]*$/.test(name)){throw new DvmError18("invalid_capability",`Capability name ${JSON.stringify(name)} is not well formed.`)}if(!isZodSchema(capability.input)){throw new DvmError18("invalid_input_schema",`Capability ${JSON.stringify(name)} does not have a valid Zod input schema.`,"Declare `input: z.object(...)` so callers and the handler agree on request data.")}if(capability.example===void 0){throw new DvmError18("missing_input_example",`Capability ${JSON.stringify(name)} has no example input.`,"Declare an `example` that satisfies this capability's input schema.")}if(!capability.input.safeParse(capability.example).success){throw new DvmError18("invalid_input_example",`Capability ${JSON.stringify(name)} has an example that does not satisfy its input schema.`,"Update `example` to satisfy every field and refinement in the Zod input schema.")}if(capability.price!==void 0&&typeof capability.price!=="string"){throw new DvmError18("invalid_price",`Capability ${JSON.stringify(name)} has an invalid price.`)}}for(const tag of descriptor.tags){if(typeof tag!=="string"||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(tag)){throw new DvmError18("invalid_tag",`Tag ${JSON.stringify(tag)} is not well formed.`,"Use lowercase letters, digits, and single hyphens.")}}return[...names]}function readDvmName(cwd){try{const pkg=JSON.parse(readFileSync6(resolve4(cwd,"package.json"),"utf-8"));return pkg.name??null}catch{return null}}async function deploy(opts,cwd){cwd??=process.cwd();if(!opts.endpointUrl){if(!existsSync7(resolve5(cwd,"handler.ts"))&&!existsSync7(resolve5(cwd,"handler.js"))){throw new Error("No handler.ts or handler.js found. Run this from a DVM project directory.")}}if(existsSync7(resolve5(cwd,"package.json"))){validateManifest(cwd)}if(opts.dryRun){deployDryRun(cwd,opts);return}if(opts.local||opts.target==="local"){await deployLocal2(cwd,opts);return}const target=opts.target??await pickTarget();await ensureBuilderIdentity(opts);if(target==="cloud"){await deployCloud(cwd,opts);return}deploySelfHost(cwd,opts)}async function ensureBuilderIdentity(opts){if(loadIdentitySecret2()!==null)return;let create2=opts.createIdentity===true;if(!create2&&process.stdin.isTTY){create2=await new Promise(resolveAnswer=>{const rl=createInterface2({input:process.stdin,output:process.stdout});rl.question(" No builder signing identity exists. Create it now? [y/N] ",answer=>{rl.close();resolveAnswer(answer.trim().toLowerCase()==="y")})})}if(!create2){throw new DvmError19("identity_required","No builder identity found.","Run `dvmctl deploy --create-identity` (or `dvmctl identity create`) and re-run the deploy.")}identityCreate({human:opts.human,quiet:true});if(opts.human)info("Builder signing identity created.")}async function deployLocal2(cwd,opts){const creds=resolveAuth();if(!creds){throw new DvmError19("auth_required","Not authenticated.","Set DVMKIT_API_KEY (e.g. the seeded `dvmk_aaaa\u2026` key) or run `dvmctl auth`.")}const platformUrl=process.env.DVMKIT_PLATFORM_URL??"http://localhost:8080";const slug=opts.name??deriveSlug(cwd);if(slug.length<3){throw new DvmError19("invalid_slug",`Slug "${slug}" is too short (min 3 characters).`)}const name=readDvmName2(cwd)??slug;const port=loadEnvFile(cwd).PORT??"3000";const url2=opts.url??opts.endpointUrl??`http://localhost:${port}`;const localDvmId=getSelfHostedBuilderDvm(slug)?.canonical_dvm_id;const attestation=loadIdentitySecret2()!==null&&localDvmId!=null?buildDeployAttestation(cwd,slug,localDvmId):void 0;const runtime=opts.runtime==="isolate"?"isolate":"container";const probe=await probeLocalDvm(url2,runtime);if(opts.human){info(`Registering ${name} as ${slug} [local, ${runtime}]...`);info(` url ${url2}`);info(` platform ${platformUrl}`);if(!probe.ok){info(`
|
|
2410
|
+
`);info("Press Ctrl-C to close the tunnel.")}else{json({dvmId:target.dvmId,slug,host:"127.0.0.1",port:handle2.port,user:handle2.ready.user,database:handle2.ready.database,database_url:url2,display:`Postgres proxy for ${slug} listening on 127.0.0.1:${handle2.port}.`,hint:`Point any Postgres client at database_url (psql, pg_dump, drizzle-kit, a GUI client). The proxy stays up until it is interrupted.`})}await blockUntilShutdown(()=>handle2)}async function startDbProxy(target,opts){const{token,platformUrl,dvmId}=target;const port=parsePort(opts.port);const opening=new Set;const open=async()=>{const controller=new AbortController;opening.add(controller);try{return await openDbTunnel({platformUrl,token,dvmId,machine:opts.machine,signal:controller.signal})}finally{opening.delete(controller)}};const probe=await open();await probe.close();const tunnels=new Set;const sockets=new Set;const connections=new Set;let closing=false;const server=createServer2(sock=>{sockets.add(sock);sock.once("close",()=>sockets.delete(sock));sock.on("error",()=>{sock.destroy()});if(closing){sock.destroy();return}const connection=serveConnection(sock,open,tunnels,()=>closing,opts.human);connections.add(connection);void connection.then(()=>connections.delete(connection),()=>connections.delete(connection))});await new Promise((resolve10,reject)=>{const onListenError=err=>{reject(new DvmError15("local_listener_failed",`Could not open a local port: ${err.message}`))};server.once("error",onListenError);server.listen(port,"127.0.0.1",()=>{server.off("error",onListenError);server.on("error",err=>{reportError("proxy_error","local_listener_failed",err.message,opts.human)});resolve10()})});let closePromise;const close=()=>{closePromise??=(async()=>{closing=true;for(const controller of opening)controller.abort();const serverClosed=new Promise((resolve10,reject)=>{server.close(err=>{if(err)reject(err);else resolve10()})});for(const socket of sockets)socket.destroy();await Promise.all([...tunnels].map(tunnel=>tunnel.close()));await Promise.all([...connections]);await Promise.all([...tunnels].map(tunnel=>tunnel.close()));await serverClosed;tunnels.clear()})();return closePromise};return{port:server.address().port,ready:probe.ready,close}}function buildDatabaseUrl(ready,port){const user=encodeURIComponent(ready.user);const password=encodeURIComponent(ready.password);const database=encodeURIComponent(ready.database);return`postgres://${user}:${password}@127.0.0.1:${port}/${database}?sslmode=disable`}async function serveConnection(sock,open,tunnels,isClosing,human){let tunnel;try{tunnel=await open()}catch(err){if(!isClosing()){const{code,message:message2}=asDvmError(err);reportError("connection_error",code,message2,human)}sock.destroy();return}if(sock.destroyed||isClosing()){sock.destroy();await tunnel.close();return}tunnels.add(tunnel);sock.on("close",()=>{void tunnel.close().then(()=>tunnels.delete(tunnel))});tunnel.attach(sock)}function reportError(event,code,message2,human){const label=event==="connection_error"?"Connection failed":"Proxy error";if(human)info(`${label}: ${providerTextToString(message2)}`);else progress({event,code,message:message2})}function asDvmError(err){if(err instanceof DvmError15){return{code:err.code,message:err.proseSources?.message==="provider"?asProviderText(err.message):err.message}}return{code:"tunnel_failed",message:err instanceof Error?err.message:String(err)}}function parsePort(raw2){if(raw2===void 0)return 0;const port=Number(raw2);if(!Number.isInteger(port)||port<1||port>65535){throw new DvmError15("invalid_port",`'${raw2}' is not a valid port.`,"Pass --port 1-65535, or omit --port for an OS-assigned one.")}return port}init_builder_mnemonic();init_deploy_attestation();init_dev_environment();import{execFileSync}from"child_process";import{existsSync as existsSync7,mkdirSync as mkdirSync5,mkdtempSync,rmSync,writeFileSync as writeFileSync5}from"fs";import{tmpdir}from"os";import{dirname as dirname2,join as join6,relative,resolve as resolve6}from"path";import{createInterface as createInterface2}from"readline";import{deriveBuilderLockKeypair as deriveBuilderLockKeypair2,DvmError as DvmError20,loadIdentitySecret as loadIdentitySecret2}from"@dvmkit/sdk/internal";var InheritSecretsError=class extends Error{constructor(code,message2){super(message2);this.code=code;this.name="InheritSecretsError"}code};var PLATFORM_INTERNAL_PREFIXES=["FLY_","STRIPE_","PLATFORM_","GITHUB_APP_","RESEND_","AVATAR_","FEE_GATE_"];var PLATFORM_INTERNAL_EXACT=["APP_URL","DATABASE_URL","DVMKIT_BUILDER_ID","DVMKIT_BUILDER_PUBKEY","DVMKIT_BUILDER_ATTESTATION","DVMKIT_BUILDER_SIGNATURE","DVMKIT_CASHU_LOCK_PUBKEY","DVMKIT_CASHU_MINTS","DVMKIT_DVM_ID","DVMKIT_FX_SOURCE","DVMKIT_ISOLATE_SECRET","DVMKIT_PLATFORM_CALLBACK","DVMKIT_PLATFORM_TOKEN","DVMKIT_PLATFORM_URL","EXTERNAL_REGISTRY_AUTH_REQUIRED","NPM_TOKEN"];var PATTERN_RE=/^[A-Z][A-Z0-9_]*(\*)?$/;function parseInheritSecrets(raw2){if(raw2===void 0||raw2===null)return[];if(!Array.isArray(raw2)){throw new InheritSecretsError("invalid_inherit_secrets","`inheritSecrets` must be an array of strings.")}return raw2.map(entry=>{if(typeof entry!=="string"){throw new InheritSecretsError("invalid_inherit_secrets","`inheritSecrets` entries must be strings.")}validatePattern(entry);return entry})}function validatePattern(pattern){if(pattern===""){throw new InheritSecretsError("invalid_inherit_secrets","`inheritSecrets` entries must not be empty.")}if(pattern==="*"){throw new InheritSecretsError("invalid_inherit_secrets","`inheritSecrets` does not allow a bare `*` (would forward every platform secret).")}if(!PATTERN_RE.test(pattern)){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` pattern ${JSON.stringify(pattern)} must be uppercase letters, digits, or underscores, optionally ending in '*'.`)}if(pattern.endsWith("*")&&pattern.length-1<3){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` glob ${JSON.stringify(pattern)} needs a literal prefix of at least 3 characters.`)}rejectPlatformInternal(pattern)}function rejectPlatformInternal(pattern){if(!pattern.endsWith("*")){if(PLATFORM_INTERNAL_EXACT.includes(pattern)||PLATFORM_INTERNAL_PREFIXES.some(prefix=>pattern.startsWith(prefix))){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` pattern ${JSON.stringify(pattern)} targets a platform-internal env var; DVMs cannot inherit it.`)}return}const literal2=pattern.slice(0,-1);for(const denied of PLATFORM_INTERNAL_PREFIXES){if(literal2.startsWith(denied)||denied.startsWith(literal2)){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` glob ${JSON.stringify(pattern)} would match the platform-internal namespace ${JSON.stringify(denied)}; DVMs cannot inherit it.`)}}for(const exact of PLATFORM_INTERNAL_EXACT){if(exact.startsWith(literal2)){throw new InheritSecretsError("invalid_inherit_secrets",`\`inheritSecrets\` glob ${JSON.stringify(pattern)} would match the platform-internal env var ${JSON.stringify(exact)}; DVMs cannot inherit it.`)}}}var FeatureManifestError=class extends Error{constructor(code,message2){super(message2);this.code=code;this.name="FeatureManifestError"}code};function parseFeatures(raw2){if(raw2===void 0||raw2===null)return{};if(typeof raw2!=="object"||Array.isArray(raw2)){throw new FeatureManifestError("invalid_features","`features` must be an object mapping feature names to their required env keys.")}const out={};for(const[feature,value]of Object.entries(raw2)){if(typeof value!=="object"||value===null||Array.isArray(value)){throw new FeatureManifestError("invalid_features",`\`features.${feature}\` must be an object with \`requires\` and/or \`requiresAny\`.`)}const entry=value;const requires=parseKeyList(feature,"requires",entry.requires);const requiresAny=parseKeyList(feature,"requiresAny",entry.requiresAny);if(requires.length===0&&requiresAny.length===0){throw new FeatureManifestError("invalid_features",`\`features.${feature}\` must declare at least one key in \`requires\` or \`requiresAny\`.`)}const parsed={};if(requires.length>0)parsed.requires=requires;if(requiresAny.length>0)parsed.requiresAny=requiresAny;out[feature]=parsed}return out}var KEY_RE=/^[A-Z][A-Z0-9_]*$/;function parseKeyList(feature,field,raw2){if(raw2===void 0)return[];if(!Array.isArray(raw2)){throw new FeatureManifestError("invalid_features",`\`features.${feature}.${field}\` must be an array of env-var names.`)}for(const entry of raw2){if(typeof entry!=="string"||!KEY_RE.test(entry)){throw new FeatureManifestError("invalid_features",`\`features.${feature}.${field}\` entries must be uppercase env-var names (e.g. "ANTHROPIC_API_KEY"); got ${JSON.stringify(entry)}.`)}}return raw2}var VmConfigError=class extends Error{constructor(code,message2,data){super(message2);this.code=code;this.data=data;this.name="VmConfigError"}code;data};function parseVmConfig(raw2){if(raw2===void 0||raw2===null)return{};if(typeof raw2!=="object"||Array.isArray(raw2)){throw new VmConfigError("invalid_vm_config","`dvmkit` must be an object with VM resource fields.")}const src=raw2;const config2={};const memory2=pick3(src,"memory_mb","memoryMb");if(memory2!==void 0){config2.memoryMb=parseIntInRange(memory2,"memory_mb",256,16384)}const cpu=pick3(src,"cpu_count","cpuCount");if(cpu!==void 0){config2.cpuCount=parseIntInRange(cpu,"cpu_count",1,16)}const kind=pick3(src,"cpu_kind","cpuKind");if(kind!==void 0){if(kind!=="shared"&&kind!=="performance"){throw new VmConfigError("invalid_vm_config",'`cpu_kind` must be "shared" or "performance".')}config2.cpuKind=kind}const minMachines=pick3(src,"min_machines_running","minMachinesRunning");if(minMachines!==void 0){config2.minMachinesRunning=parseIntInRange(minMachines,"min_machines_running",0,8)}const maxMachines=pick3(src,"max_machines","maxMachines");if(maxMachines!==void 0){config2.maxMachines=parseIntInRange(maxMachines,"max_machines",1,8)}if(config2.minMachinesRunning!==void 0&&config2.maxMachines!==void 0&&config2.maxMachines<config2.minMachinesRunning){throw new VmConfigError("invalid_vm_config",`\`max_machines\` (${config2.maxMachines}) must be >= \`min_machines_running\` (${config2.minMachinesRunning}).`)}return config2}function pick3(src,snake,camel){const hasSnake=src[snake]!==void 0;const hasCamel=src[camel]!==void 0;if(hasSnake&&hasCamel){throw new VmConfigError("invalid_vm_config",`\`${snake}\` and \`${camel}\` are both set; use one or the other.`)}return hasSnake?src[snake]:src[camel]}function parseIntInRange(value,field,min,max){if(typeof value!=="number"||!Number.isInteger(value)){throw new VmConfigError("invalid_vm_config",`\`${field}\` must be an integer between ${min} and ${max}.`)}if(value<min||value>max){throw new VmConfigError("invalid_vm_config",`\`${field}\` must be an integer between ${min} and ${max} (got ${value}).`)}return value}init_builder_store();var DIRTY_SUFFIX="-dirty";function splitDirtySha(sha){return sha.endsWith(DIRTY_SUFFIX)?{base:sha.slice(0,-DIRTY_SUFFIX.length),dirty:true}:{base:sha,dirty:false}}function shortSha(sha){const{base:base3,dirty}=splitDirtySha(sha);return base3.slice(0,7)+(dirty?DIRTY_SUFFIX:"")}init_output();init_builder_store();init_defaults();init_output();import{DvmError as DvmError18,generateIdentity,writeIdentity}from"@dvmkit/sdk/internal";function identityCreate(opts){const keypair=generateIdentity();writeIdentity(keypair,{force:opts.force});if(opts.quiet)return;const isWindows=process.platform==="win32";if(opts.human){info("Builder identity created.");info(` pubkey: ${keypair.pubkey}`);info(` secret stored at: ${BUILDER_KEY_FILE}`);if(isWindows){info("");info("\u26A0 Windows does not enforce Unix file permissions. Make sure");info(` ${BUILDER_KEY_FILE} sits on disk-encrypted storage and is`);info(" not synced to shared/backup locations.")}else{info(` mode: 0600 (POSIX)`)}info("");info("`dvmctl deploy` will now sign each deploy with this key. Run");info("`dvmctl identity show` to print the pubkey again later.")}else{json({status:"created",identity_pubkey:keypair.pubkey,secret_path:BUILDER_KEY_FILE,pubkey_path:BUILDER_FILE,...isWindows?{windows_note:"Windows does not enforce Unix file permissions; ensure the secret file lives on disk-encrypted storage."}:{mode:"0600"}})}}function identityShow(opts){const pubkey=loadIdentityPubkey();if(!pubkey){throw new DvmError18("identity_missing","No builder identity exists.","Run `dvmctl identity create` to generate one.")}if(opts.human){info(`identity_pubkey: ${pubkey}`);info(`stored at: ${BUILDER_FILE}`)}else{json({identity_pubkey:pubkey,pubkey_path:BUILDER_FILE})}}init_deploy_attestation();init_load_handler();init_output();import{existsSync as existsSync6,readFileSync as readFileSync7}from"fs";import{resolve as resolve5}from"path";import{isZodSchema}from"@dvmkit/sdk";import{DvmError as DvmError19}from"@dvmkit/sdk/internal";function validateManifest(cwd){if(!existsSync6(resolve5(cwd,"package.json"))){throw new DvmError19("missing_package_json",`No package.json found in ${cwd}.`,"Run this from a DVM project directory.")}const slug=deriveSlug(cwd);const name=readDvmName(cwd)??slug;const vmConfig=readVmConfig(cwd);const inheritSecrets=readInheritSecrets(cwd);const features=readFeatures(cwd);return{slug,name,vmConfig,inheritSecrets,features}}async function validate4(opts,cwd){cwd??=process.cwd();const{slug,name,vmConfig,inheritSecrets,features}=validateManifest(cwd);const featureNames=Object.keys(features);const handlerPath=resolveHandlerPath(cwd,opts.handler);let descriptor;try{descriptor=await loadDescriptor(handlerPath)}catch(err){const message2=err instanceof Error?err.message:String(err);throw new DvmError19("invalid_handler",`Could not load DVM handler ${handlerPath}: ${message2}`,"Fix the handler import or descriptor configuration, then run `dvmctl validate` again.")}const capabilityNames=validateDescriptor(descriptor);if(opts.human){info(`Validating ${name} (${slug}): ok`);if(vmConfig){const mem=vmConfig.memoryMb!=null?`${vmConfig.memoryMb} MB`:"(default)";info(` resources ${mem} / ${vmConfig.cpuCount??1} cpu`)}if(inheritSecrets.length>0){info(` inheritSecrets ${inheritSecrets.length} pattern(s)`)}if(featureNames.length>0){info(` features ${featureNames.join(", ")}`)}info(` handler ${handlerPath}`);info(` capabilities ${capabilityNames.join(", ")}`)}else{json({status:"ok",slug,name,vm_config:vmConfig,inherit_secrets:inheritSecrets.length>0?inheritSecrets:void 0,features:featureNames.length>0?features:void 0,handler:handlerPath,capabilities:capabilityNames,display:`${name} is valid with ${capabilityNames.length} ${capabilityNames.length===1?"capability":"capabilities"}.`,hint:"Run `dvmctl dev <handler>` to make the first local call."})}}function resolveHandlerPath(cwd,requested){if(requested){const path=resolve5(cwd,requested);if(!existsSync6(path)){throw new DvmError19("handler_not_found",`Handler file not found: ${path}.`,"Pass --handler <path> or create handler.ts / handler.js in this project.")}return path}for(const name of["handler.ts","handler.js"]){const path=resolve5(cwd,name);if(existsSync6(path))return path}throw new DvmError19("handler_not_found",`No handler.ts or handler.js found in ${cwd}.`,"Add a handler module or pass --handler <path>. A scaffold is not required.")}function validateDescriptor(descriptor){const entries=Object.entries(descriptor.capabilities);if(entries.length===0){throw new DvmError19("missing_capability","The handler declares no capabilities.")}const names=new Set;for(const[name,capability]of entries){if(names.has(name)){throw new DvmError19("duplicate_capability",`Capability name ${JSON.stringify(name)} is duplicated.`)}names.add(name);if(!/^[a-z0-9][a-z0-9-]*$/.test(name)){throw new DvmError19("invalid_capability",`Capability name ${JSON.stringify(name)} is not well formed.`)}if(!isZodSchema(capability.input)){throw new DvmError19("invalid_input_schema",`Capability ${JSON.stringify(name)} does not have a valid Zod input schema.`,"Declare `input: z.object(...)` so callers and the handler agree on request data.")}if(capability.example===void 0){throw new DvmError19("missing_input_example",`Capability ${JSON.stringify(name)} has no example input.`,"Declare an `example` that satisfies this capability's input schema.")}if(!capability.input.safeParse(capability.example).success){throw new DvmError19("invalid_input_example",`Capability ${JSON.stringify(name)} has an example that does not satisfy its input schema.`,"Update `example` to satisfy every field and refinement in the Zod input schema.")}if(capability.price!==void 0&&typeof capability.price!=="string"){throw new DvmError19("invalid_price",`Capability ${JSON.stringify(name)} has an invalid price.`)}}for(const tag of descriptor.tags){if(typeof tag!=="string"||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(tag)){throw new DvmError19("invalid_tag",`Tag ${JSON.stringify(tag)} is not well formed.`,"Use lowercase letters, digits, and single hyphens.")}}return[...names]}function readDvmName(cwd){try{const pkg=JSON.parse(readFileSync7(resolve5(cwd,"package.json"),"utf-8"));return pkg.name??null}catch{return null}}async function deploy(opts,cwd){cwd??=process.cwd();if(!opts.endpointUrl){if(!existsSync7(resolve6(cwd,"handler.ts"))&&!existsSync7(resolve6(cwd,"handler.js"))){throw new Error("No handler.ts or handler.js found. Run this from a DVM project directory.")}}if(existsSync7(resolve6(cwd,"package.json"))){validateManifest(cwd)}if(opts.dryRun){deployDryRun(cwd,opts);return}if(opts.local||opts.target==="local"){await deployLocal2(cwd,opts);return}const target=opts.target??await pickTarget();await ensureBuilderIdentity(opts);if(target==="cloud"){await deployCloud(cwd,opts);return}deploySelfHost(cwd,opts)}async function ensureBuilderIdentity(opts){if(loadIdentitySecret2()!==null)return;let create2=opts.createIdentity===true;if(!create2&&process.stdin.isTTY){create2=await new Promise(resolveAnswer=>{const rl=createInterface2({input:process.stdin,output:process.stdout});rl.question(" No builder signing identity exists. Create it now? [y/N] ",answer=>{rl.close();resolveAnswer(answer.trim().toLowerCase()==="y")})})}if(!create2){throw new DvmError20("identity_required","No builder identity found.","Run `dvmctl deploy --create-identity` (or `dvmctl identity create`) and re-run the deploy.")}identityCreate({human:opts.human,quiet:true});if(opts.human)info("Builder signing identity created.")}async function deployLocal2(cwd,opts){const creds=resolveAuth();if(!creds){throw new DvmError20("auth_required","Not authenticated.","Set DVMKIT_API_KEY (e.g. the seeded `dvmk_aaaa\u2026` key) or run `dvmctl auth`.")}const platformUrl=process.env.DVMKIT_PLATFORM_URL??"http://localhost:8080";const slug=opts.name??deriveSlug(cwd);if(slug.length<3){throw new DvmError20("invalid_slug",`Slug "${slug}" is too short (min 3 characters).`)}const name=readDvmName2(cwd)??slug;const port=loadProjectEnvironment(cwd).PORT??"3000";const url2=opts.url??opts.endpointUrl??`http://localhost:${port}`;const localDvmId=getSelfHostedBuilderDvm(slug)?.canonical_dvm_id;const attestation=loadIdentitySecret2()!==null&&localDvmId!=null?buildDeployAttestation(cwd,slug,localDvmId):void 0;const runtime=opts.runtime==="isolate"?"isolate":"container";const probe=await probeLocalDvm(url2,runtime);if(opts.human){info(`Registering ${name} as ${slug} [local, ${runtime}]...`);info(` url ${url2}`);info(` platform ${platformUrl}`);if(!probe.ok){info(`
|
|
2411
2411
|
Warning: ${url2} does not look like a running DVM (${probe.reason}).`);info(" Registering anyway \u2014 if this isn't intentional (register-before-serve),");info(" pass --url http://localhost:<your-dvm-port>. The default is :3000, which");info(" is the web app when `npm run dev:stack` is up, not your DVM.")}else if(probe.attestedReceiptKey===false){info("\n Note: this DVM's receipts are signed but unattested \u2014 a caller can check");info(" the signature, but nothing vouches for the signing key. To fix, restart it");info(` with: dvmctl serve <handler> --dvm ${slug}`)}}const result=await deployLocal(platformUrl,creds.token,{slug,name,url:url2,runtime,identityPubkey:attestation?.identityPubkey,attestationPayload:attestation?.payload,attestationSignature:attestation?.signature,capabilities:attestation?.capabilities,orgHandle:resolveOrgScope(opts)??void 0});if(opts.human){if(result.status==="suspended"){if(result.suspensionReason==="builder_pause"){info(`
|
|
2412
2412
|
Registered, but it remains paused. Run \`dvmctl resume ${slug}\` to bring it back online.`)}else if(result.suspensionReason==="free_tier_idle"){info("\n Registered, but it remains idle. The next request wakes it automatically; nothing to fix.")}else{const reason=result.suspensionReason??"operator";const pause2=result.paused?` Your pause is still on record \u2014 "${slug}" returns to paused once the suspension is lifted.`:"";info(`
|
|
2413
2413
|
Registered, but it remains suspended by the platform (${reason}); \`dvmctl resume\` won't lift it.${pause2}`)}}else{info(`
|
|
2414
|
-
Registered. Router proxies to ${result.url}`)}if(result.dvmkitUrl)info(` Local URL: ${result.dvmkitUrl}`);info("")}else{json({status:result.status,paused:result.paused,suspensionReason:result.suspensionReason,url:result.url,dvmkitUrl:result.dvmkitUrl,slug:result.slug,dvmId:result.dvmId,runtime,warning:probe.ok?void 0:`${url2} does not look like a running DVM (${probe.reason}). If unintended, re-run with --url http://localhost:<your-dvm-port>.`,hint:probe.ok&&probe.attestedReceiptKey===false?`This DVM's receipts are signed but unattested. Run 'dvmctl init ${slug} --self-hosted', then restart it with 'dvmctl serve <handler> --dvm ${slug}' so its receipts chain to a durable DVM ID.`:void 0})}}async function probeLocalDvm(url2,runtime="container"){const path=runtime==="isolate"?"/_isolate/info":"/v1/info";try{const res=await fetch(`${url2}${path}`,{signal:AbortSignal.timeout(5e3)});if(!res.ok)return{ok:false,reason:`GET ${url2}${path} returned HTTP ${res.status}`};const contentType=res.headers.get("content-type")??"";if(!contentType.includes("application/json")){return{ok:false,reason:`${path} is not JSON (content-type: ${contentType||"none"})`}}const data=await res.json();if(typeof data.name!=="string"){return{ok:false,reason:`${path} has no DVM \`name\` field`}}return{ok:true,attestedReceiptKey:readAttestedReceiptKey(data)}}catch(err){return{ok:false,reason:`${path} unreachable (${err instanceof Error?err.message:String(err)})`}}}function readAttestedReceiptKey(info2){if(info2.receipts!==true)return void 0;const builder=info2.builder;if(!builder||typeof builder!=="object")return false;const attestation=builder.attestation;if(!attestation||typeof attestation!=="object")return false;return typeof attestation.receipt_pubkey==="string"}async function deployCloud(cwd,opts){const creds=resolveAuth();if(!creds){throw new
|
|
2415
|
-
${dirtyPaths.map(path=>` ${path}`).join("\n")}`,"Commit or discard these paths, or re-run with --allow-dirty only if shipping uncommitted code is intentional. --yes does not bypass this check.",{paths:dirtyPaths,packaged_root:contextRoot})}const tarball=createTarball(contextRoot);const dockerfilePath=contextRoot===cwd?void 0:relative(contextRoot,
|
|
2414
|
+
Registered. Router proxies to ${result.url}`)}if(result.dvmkitUrl)info(` Local URL: ${result.dvmkitUrl}`);info("")}else{json({status:result.status,paused:result.paused,suspensionReason:result.suspensionReason,url:result.url,dvmkitUrl:result.dvmkitUrl,slug:result.slug,dvmId:result.dvmId,runtime,warning:probe.ok?void 0:`${url2} does not look like a running DVM (${probe.reason}). If unintended, re-run with --url http://localhost:<your-dvm-port>.`,hint:probe.ok&&probe.attestedReceiptKey===false?`This DVM's receipts are signed but unattested. Run 'dvmctl init ${slug} --self-hosted', then restart it with 'dvmctl serve <handler> --dvm ${slug}' so its receipts chain to a durable DVM ID.`:void 0})}}async function probeLocalDvm(url2,runtime="container"){const path=runtime==="isolate"?"/_isolate/info":"/v1/info";try{const res=await fetch(`${url2}${path}`,{signal:AbortSignal.timeout(5e3)});if(!res.ok)return{ok:false,reason:`GET ${url2}${path} returned HTTP ${res.status}`};const contentType=res.headers.get("content-type")??"";if(!contentType.includes("application/json")){return{ok:false,reason:`${path} is not JSON (content-type: ${contentType||"none"})`}}const data=await res.json();if(typeof data.name!=="string"){return{ok:false,reason:`${path} has no DVM \`name\` field`}}return{ok:true,attestedReceiptKey:readAttestedReceiptKey(data)}}catch(err){return{ok:false,reason:`${path} unreachable (${err instanceof Error?err.message:String(err)})`}}}function readAttestedReceiptKey(info2){if(info2.receipts!==true)return void 0;const builder=info2.builder;if(!builder||typeof builder!=="object")return false;const attestation=builder.attestation;if(!attestation||typeof attestation!=="object")return false;return typeof attestation.receipt_pubkey==="string"}async function deployCloud(cwd,opts){const creds=resolveAuth();if(!creds){throw new DvmError20("auth_required","Not authenticated.","Set DVMKIT_API_KEY or run `dvmctl auth`.")}requireBuilderIdentity();const platformUrl=process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev";const activeOrg=resolveOrgScope(opts)??null;if(opts.human)info("Verifying credentials...");await validateAuth(platformUrl,creds.token);if(opts.endpointUrl){await deployConnect(cwd,opts,platformUrl,creds.token,activeOrg);return}const hasDockerfile=existsSync7(resolve6(cwd,"Dockerfile"));const runtime=opts.runtime??(hasDockerfile?"container":"isolate");if(runtime==="container"&&!hasDockerfile){throw new DvmError20("missing_dockerfile","No Dockerfile found.","Run `dvmctl deploy --target self-host` first to generate one, or use isolate mode (no Dockerfile needed).")}const slug=opts.name??deriveSlug(cwd);if(slug.length<3){throw new DvmError20("invalid_slug",`Slug "${slug}" is too short (min 3 characters).`)}const name=readDvmName2(cwd)??slug;const env2={...loadProjectEnvironment(cwd),...opts.extraEnv??{}};const contextRoot=findContextRoot(cwd);const dirtyPaths=packagedTreeDirtyPaths(contextRoot);if(dirtyPaths.length>0&&!opts.allowDirty){throw new DvmError20("dirty_worktree",`Cloud deploy refused: the packaged tree at ${contextRoot} has uncommitted changes:
|
|
2415
|
+
${dirtyPaths.map(path=>` ${path}`).join("\n")}`,"Commit or discard these paths, or re-run with --allow-dirty only if shipping uncommitted code is intentional. --yes does not bypass this check.",{paths:dirtyPaths,packaged_root:contextRoot})}const tarball=createTarball(contextRoot);const dockerfilePath=contextRoot===cwd?void 0:relative(contextRoot,resolve6(cwd,"Dockerfile"));const commit=readGitHead(cwd,contextRoot);const vmConfig=readVmConfig(cwd);const inheritSecrets=readInheritSecrets(cwd);const features=readFeatures(cwd);if(opts.human){const tier=runtime==="isolate"?"isolate (handler-only)":"container";info(`Deploying ${name} as ${slug} [${tier}]...`);if(activeOrg){info(` org ${activeOrg}`)}if(commit){info(` commit ${shortSha(commit.sha)} (${commit.ref})`);if(splitDirtySha(commit.sha).dirty){info(` Note: uncommitted changes in ${contextRoot} \u2014 image will report a -dirty sha`)}}if(dockerfilePath){info(` build context ${contextRoot} (Dockerfile: ${dockerfilePath})`)}if(vmConfig){const mem=vmConfig.memoryMb!=null?`${vmConfig.memoryMb} MB`:"(default)";const cpus=vmConfig.cpuCount??1;info(` resources ${mem} / ${cpus} cpu`)}if(inheritSecrets.length>0){info(` inheritSecrets ${inheritSecrets.length} pattern(s)`)}}const mnemonic=readBuilderMnemonic();const scopedDvms=mnemonic?await listDvms(platformUrl,creds.token,{...activeOrg?{org:activeOrg}:{}}):void 0;const existingDvm=scopedDvms?.dvms.find(candidate=>candidate.slug===slug);const existingBuilderEntry=existingDvm?getBuilderDvm(existingDvm.id):void 0;if(existingBuilderEntry?.self_hosted){throw new DvmError20("self_hosted_entry_blocks_cloud_deploy",`builder.json marks "${slug}" as self_hosted with canonical_dvm_id=${existingBuilderEntry.canonical_dvm_id}, but \`dvmctl deploy\` targets the cloud.`,"Delete the entry from ~/.dvmkit/builder.json before cloud-deploying this slug. The cloud deploy will re-derive a fresh lock pubkey from the platform-assigned dvms.id (this retires any proofs locked to the self-hosted pubkey).")}let preComputedLockPubkey;if(mnemonic&&existingBuilderEntry){preComputedLockPubkey=deriveBuilderLockKeypair2(mnemonic,existingBuilderEntry.canonical_dvm_id,existingBuilderEntry.current_rotation_index).pubkey}const identityPubkey=loadIdentityPubkey();if(!identityPubkey)throw new DvmError20("identity_required","Builder identity is missing.");const{deployId,dvmId}=await startDeploy(platformUrl,creds.token,{slug,name,tarball,env:env2,runtime,commit:commit??void 0,vmConfig:vmConfig??void 0,inheritSecrets:inheritSecrets.length>0?inheritSecrets:void 0,features:Object.keys(features).length>0?features:void 0,dockerfilePath,orgHandle:activeOrg??void 0,lockPubkey:preComputedLockPubkey,expectLockPubkey:Boolean(mnemonic&&!existingBuilderEntry),expectIdentityFinalization:true,identityPubkey});if(opts.human)info(` Deploy queued: ${deployId}`);else progress({event:"queued",deploy_id:deployId});const attestation=buildDeployAttestation(cwd,slug,dvmId,{withReceiptKey:true});if(!attestation.receiptSecret){throw new DvmError20("receipt_identity_missing","Receipt identity finalization produced no receipt secret.")}await finalizeDvmDeployIdentity(platformUrl,creds.token,dvmId,{deployId,identityPubkey:attestation.identityPubkey,attestationPayload:attestation.payload,attestationSignature:attestation.signature,capabilities:attestation.capabilities,receiptSecret:attestation.receiptSecret});if(mnemonic&&existingBuilderEntry&&existingBuilderEntry.canonical_dvm_id!==dvmId){const{pubkey}=deriveBuilderLockKeypair2(mnemonic,dvmId,existingBuilderEntry.current_rotation_index);await setDvmLockPubkey(platformUrl,creds.token,dvmId,pubkey);upsertBuilderDvm(dvmId,{handle:slug,canonical_dvm_id:dvmId,current_rotation_index:existingBuilderEntry.current_rotation_index});preComputedLockPubkey=pubkey;if(opts.human){info(` Realigned lock pubkey: platform canonical_dvm_id (${dvmId}) differed from cached value (${existingBuilderEntry.canonical_dvm_id}).`)}}if(mnemonic&&!existingBuilderEntry){const{pubkey}=deriveBuilderLockKeypair2(mnemonic,dvmId,0);await setDvmLockPubkey(platformUrl,creds.token,dvmId,pubkey);upsertBuilderDvm(dvmId,{handle:slug,canonical_dvm_id:dvmId,current_rotation_index:0});if(opts.human)info(` Per-DVM lock pubkey registered: ${pubkey}`)}else if(mnemonic&&opts.human&&preComputedLockPubkey){info(` Per-DVM lock pubkey: ${preComputedLockPubkey}`)}else if(!mnemonic&&opts.human){info(" Note: no recovery mnemonic on disk \u2014 DVM will deploy without a per-DVM lock pubkey. Run `dvmctl lock create` and redeploy to enable cashu accumulator mode.")}const result=await streamDeployLogs(platformUrl,creds.token,deployId,{onLog:line=>{if(opts.human)info(` ${line}`);else progress({event:"log",line})},onPhase:({status:status2,elapsedMs})=>{if(opts.human)info(` ${status2}... (${fmtElapsed(elapsedMs)})`);else progress({event:"phase",phase:status2,elapsed_ms:elapsedMs})},onAccepted:release=>{if(opts.human){info(` Fly accepted deploy ${release.deployId}; verifying the running DVM...`)}else{progress({event:"release_accepted",deploy_id:release.deployId,url:release.url,...release.commitSha?{commit_sha:release.commitSha}:{}})}}});const verificationUrl=`${result.url.replace(/\/$/,"")}/healthz`;const verificationHint=result.status==="deployed_unverified"?`Run \`curl -s ${verificationUrl}\` and ${commit?`confirm \`gitSha\` is \`${commit.sha}\``:"read the served `gitSha`"}.`:void 0;if(opts.human){info(result.status==="deployed_unverified"?`
|
|
2416
2416
|
Fly accepted deploy ${deployId}, but metadata verification did not complete.`:`
|
|
2417
|
-
Deployed to ${result.url}`);if(verificationHint)info(` Check: ${verificationHint}`);if(result.dvmkitUrl){info(` Public URL: ${result.dvmkitUrl}`)}for(const line of opts.resultLines??[])info(` ${line}`);info("")}else{json({status:result.status,deploy_id:deployId,url:result.url,dvmkitUrl:result.dvmkitUrl,slug,dvmId,...verificationHint?{outcome:"partial_success",display:`Fly accepted deploy ${deployId}; only post-deploy metadata verification failed.`,hint:verificationHint,verification_url:verificationUrl,...commit?{expected_git_sha:commit.sha}:{}}:{},...opts.resultFields})}}async function deployConnect(cwd,opts,platformUrl,token,activeOrg){const slug=opts.name??deriveSlug(cwd);if(slug.length<3){throw new
|
|
2418
|
-
Registered. Proxying to ${result.url}`);if(result.dvmkitUrl){info(` Public URL: ${result.dvmkitUrl}`)}if(attestation.receiptSecret){info("");info(" Signed receipts (tracked change) \u2014 set this secret on your endpoint and restart:");for(const[key,value]of Object.entries(attestationEnv(attestation))){info(` ${key}=${value}`)}info(" Until it's set, jobs complete normally but carry no receipt.")}info("")}else{json({status:"deployed",url:result.url,dvmkitUrl:result.dvmkitUrl,slug})}}function deployDryRun(cwd,opts){const slug=opts.name??deriveSlug(cwd);if(slug.length<3){throw new
|
|
2417
|
+
Deployed to ${result.url}`);if(verificationHint)info(` Check: ${verificationHint}`);if(result.dvmkitUrl){info(` Public URL: ${result.dvmkitUrl}`)}for(const line of opts.resultLines??[])info(` ${line}`);info("")}else{json({status:result.status,deploy_id:deployId,url:result.url,dvmkitUrl:result.dvmkitUrl,slug,dvmId,...verificationHint?{outcome:"partial_success",display:`Fly accepted deploy ${deployId}; only post-deploy metadata verification failed.`,hint:verificationHint,verification_url:verificationUrl,...commit?{expected_git_sha:commit.sha}:{}}:{},...opts.resultFields})}}async function deployConnect(cwd,opts,platformUrl,token,activeOrg){const slug=opts.name??deriveSlug(cwd);if(slug.length<3){throw new DvmError20("invalid_slug",`Slug "${slug}" is too short (min 3 characters).`)}const name=readDvmName2(cwd)??slug;const commit=readGitHead(cwd);if(opts.human){info(`Registering ${name} as ${slug} [connect]...`);info(` endpoint ${opts.endpointUrl}`);if(activeOrg){info(` org ${activeOrg}`)}if(commit){info(` commit ${shortSha(commit.sha)} (${commit.ref})`)}}const identityPubkey=loadIdentityPubkey();if(!identityPubkey)throw new DvmError20("identity_required","Builder identity is missing.");const{deployId,dvmId}=await startDeploy(platformUrl,token,{slug,name,commit:commit??void 0,endpointUrl:opts.endpointUrl,orgHandle:activeOrg??void 0,expectIdentityFinalization:true,identityPubkey});if(opts.human)info(` Deploy queued: ${deployId}`);else progress({event:"queued",deploy_id:deployId});const attestation=buildDeployAttestation(cwd,slug,dvmId,{withReceiptKey:true});if(!attestation.receiptSecret){throw new DvmError20("receipt_identity_missing","Receipt identity finalization produced no receipt secret.")}await finalizeDvmDeployIdentity(platformUrl,token,dvmId,{deployId,identityPubkey:attestation.identityPubkey,attestationPayload:attestation.payload,attestationSignature:attestation.signature,capabilities:attestation.capabilities,receiptSecret:attestation.receiptSecret});const result=await streamDeployLogs(platformUrl,token,deployId,{onLog:line=>{if(opts.human)info(` ${line}`);else progress({event:"log",line})},onPhase:({status:status2,elapsedMs})=>{if(opts.human)info(` ${status2}... (${fmtElapsed(elapsedMs)})`);else progress({event:"phase",phase:status2,elapsed_ms:elapsedMs})}});if(opts.human){info(`
|
|
2418
|
+
Registered. Proxying to ${result.url}`);if(result.dvmkitUrl){info(` Public URL: ${result.dvmkitUrl}`)}if(attestation.receiptSecret){info("");info(" Signed receipts (tracked change) \u2014 set this secret on your endpoint and restart:");for(const[key,value]of Object.entries(attestationEnv(attestation))){info(` ${key}=${value}`)}info(" Until it's set, jobs complete normally but carry no receipt.")}info("")}else{json({status:"deployed",url:result.url,dvmkitUrl:result.dvmkitUrl,slug})}}function deployDryRun(cwd,opts){const slug=opts.name??deriveSlug(cwd);if(slug.length<3){throw new DvmError20("invalid_slug",`Slug "${slug}" is too short (min 3 characters).`)}const name=readDvmName2(cwd)??slug;const vmConfig=readVmConfig(cwd);const inheritSecrets=readInheritSecrets(cwd);const isConnect=Boolean(opts.endpointUrl);const hasDockerfile=existsSync7(resolve6(cwd,"Dockerfile"));const runtime=opts.runtime??(hasDockerfile?"container":"isolate");let dockerBuilt=false;let dockerfilePath;if(!isConnect&&runtime==="container"){if(!hasDockerfile){throw new DvmError20("missing_dockerfile","No Dockerfile found.","Run `dvmctl deploy --target self-host` first to generate one.")}const contextRoot=findContextRoot(cwd);const buildDockerfilePath=contextRoot===cwd?"Dockerfile":relative(contextRoot,resolve6(cwd,"Dockerfile"));dockerfilePath=buildDockerfilePath;try{withDeployBuildContext(contextRoot,buildContext=>{execFileSync("docker",["build","-q","-f",resolve6(buildContext,buildDockerfilePath),buildContext],{env:{...process.env,DOCKER_BUILDKIT:"1"},stdio:opts.human?"inherit":["ignore","ignore","ignore"]})});dockerBuilt=true}catch(err){throw new DvmError20("docker_build_failed",`docker build failed: ${err instanceof Error?err.message:String(err)}`,"Ensure Docker is running and the Dockerfile builds locally.")}}if(opts.human){info(`Dry-run for ${name} (${slug}) [${isConnect?"connect":runtime}]: ok`);if(vmConfig){const mem=vmConfig.memoryMb!=null?`${vmConfig.memoryMb} MB`:"(default)";info(` resources ${mem} / ${vmConfig.cpuCount??1} cpu`)}if(inheritSecrets.length>0){info(` inheritSecrets ${inheritSecrets.length} pattern(s)`)}if(dockerBuilt)info(` docker build ok (${dockerfilePath??"Dockerfile"})`)}else{json({status:"dry-run-ok",slug,name,runtime:isConnect?"connect":runtime,docker_built:dockerBuilt,dockerfile:dockerfilePath,vm_config:vmConfig,inherit_secrets:inheritSecrets.length>0?inheritSecrets:void 0})}}function deploySelfHost(cwd,opts){if(!existsSync7(resolve6(cwd,"Dockerfile"))){writeFileSync5(resolve6(cwd,"Dockerfile"),dockerfileTemplate(),"utf-8")}requireBuilderIdentity();const slug=opts.name??deriveSlug(cwd);const dvmId=getSelfHostedBuilderDvm(slug)?.canonical_dvm_id;if(!dvmId){throw new DvmError20("durable_dvm_identity_required",`No durable DVM ID is recorded for "${slug}".`,`For a DVM you host yourself and have never initialized here, \`dvmctl init ${slug} --self-hosted\` records one. If this handle was deployed to the platform, that command refuses by design and the durable ID is already on the machine that deployed it \u2014 generate the receipt material there rather than minting a second identity here.`)}const attestation=buildDeployAttestation(cwd,slug,dvmId,{withReceiptKey:true});const envVars=attestationEnv(attestation);if(opts.human){console.log("\n Dockerfile ready.\n");console.log(" Builder identity attestation (tracked change) \u2014 set these on your container:");for(const[key,value]of Object.entries(envVars)){console.log(` ${key}=${value}`)}console.log("");if(attestation.receiptSecret){console.log(" DVMKIT_RECEIPT_KEY signs job receipts \u2014 treat it as a secret (a container\n secret / secrets manager, not a committed compose file). It re-derives from\n your builder identity, so you never need to back it up separately.\n")}console.log(" Build and run:");console.log(" docker build -t my-dvm .");console.log(` docker run -p 8080:8080 \\
|
|
2419
2419
|
-e DVMKIT_BUILDER_PUBKEY=... \\
|
|
2420
2420
|
-e DVMKIT_BUILDER_ATTESTATION='...' \\
|
|
2421
2421
|
-e DVMKIT_BUILDER_SIGNATURE=... \\
|
|
2422
2422
|
-e DVMKIT_RECEIPT_KEY=... \\
|
|
2423
2423
|
my-dvm
|
|
2424
|
-
`)}else{console.log(JSON.stringify({status:"ready",file:"Dockerfile",target:"self-host",attestation_env:envVars}))}}function readVmConfig(cwd){const pkg=readPackageJson(cwd);if(pkg?.dvmkit==null)return null;try{return parseVmConfig(pkg.dvmkit)}catch(err){if(err instanceof VmConfigError){throw new DvmError19("invalid_dvmkit_config",`Invalid \`dvmkit\` field in package.json: ${err.message}`,"Check your package.json and try again.")}throw err}}function readInheritSecrets(cwd){const pkg=readPackageJson(cwd);const dvmkit=pkg?.dvmkit;if(dvmkit==null||typeof dvmkit!=="object")return[];const raw2=dvmkit.inheritSecrets;try{return parseInheritSecrets(raw2)}catch(err){if(err instanceof InheritSecretsError){throw new DvmError19("invalid_dvmkit_config",`Invalid \`dvmkit.inheritSecrets\` in package.json: ${err.message}`,"Check your package.json and try again.")}throw err}}function readFeatures(cwd){const pkg=readPackageJson(cwd);const dvmkit=pkg?.dvmkit;if(dvmkit==null||typeof dvmkit!=="object")return{};const raw2=dvmkit.features;try{return parseFeatures(raw2)}catch(err){if(err instanceof FeatureManifestError){throw new DvmError19("invalid_dvmkit_config",`Invalid \`dvmkit.features\` in package.json: ${err.message}`,"Check your package.json and try again.")}throw err}}function readDvmName2(cwd){return readPackageJson(cwd)?.name??null}function loadEnvFile(cwd){const envPath=resolve5(cwd,".env");if(!existsSync7(envPath))return{};const content=readFileSync7(envPath,"utf-8");const result={};for(const line of content.split("\n")){const trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;const eqIndex=trimmed.indexOf("=");if(eqIndex===-1)continue;const key=trimmed.slice(0,eqIndex).trim();let value=trimmed.slice(eqIndex+1).trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'")){value=value.slice(1,-1)}if(key)result[key]=value}return result}function findContextRoot(cwd){let dir=cwd;let parent=dirname2(dir);while(parent!==dir){if(existsSync7(resolve5(dir,"package-lock.json")))return dir;dir=parent;parent=dirname2(dir)}if(existsSync7(resolve5(dir,"package-lock.json")))return dir;return cwd}var TARBALL_EXCLUDES=["node_modules",".git","dist",".env",".env.*",".vercel",".next",".turbo","coverage","*.tsbuildinfo",".cache",".verify-logs","*.spec.*-snapshots","*.test.*-snapshots",".claude",".codex"];function createTarball(cwd){return execFileSync("tar",["czf","-",...TARBALL_EXCLUDES.map(e17=>`--exclude=${e17}`),"."],{cwd,maxBuffer:50*1024*1024})}function withDeployBuildContext(cwd,build){const workspaceDir=mkdtempSync(join6(tmpdir(),"dvmkit-deploy-context-"));const contextDir=join6(workspaceDir,"context");const archivePath=join6(workspaceDir,"input.tar.gz");try{mkdirSync5(contextDir);writeFileSync5(archivePath,createTarball(cwd));execFileSync("tar",["xzf",archivePath,"-C",contextDir],{stdio:["ignore","ignore","ignore"]});rmSync(archivePath,{force:true});return build(contextDir)}finally{rmSync(workspaceDir,{recursive:true,force:true})}}function isPackagedTreeDirty(packagedRoot){return packagedTreeDirtyPaths(packagedRoot).length>0}function packagedTreeDirtyPaths(packagedRoot){let raw2;try{raw2=execFileSync("git",["status","--porcelain","-z","--","."],{cwd:packagedRoot,stdio:["ignore","pipe","ignore"],maxBuffer:16*1024*1024}).toString("utf8")}catch{return[]}return raw2.split("\0").filter(Boolean).map(statusEntryPath).filter(isPackaged).sort()}function readGitHead(cwd,packagedRoot){const run=args=>{try{return execFileSync("git",args,{cwd,stdio:["ignore","pipe","ignore"]}).toString("utf8").trim()}catch{return null}};const sha=run(["rev-parse","HEAD"]);if(!sha)return null;const message2=run(["log","-1","--pretty=format:%s","HEAD"]);if(!message2)return null;const ref=run(["symbolic-ref","--short","-q","HEAD"])??"HEAD";const authorName=run(["log","-1","--pretty=format:%an","HEAD"]);const dirty=packagedRoot!=null&&isPackagedTreeDirty(packagedRoot);return{sha:dirty?`${sha}${DIRTY_SUFFIX}`:sha,ref,message:message2,authorName:authorName&&authorName.length>0?authorName:null}}function statusEntryPath(field){return/^[ MADRCU?!][ MADRCU?!] /.test(field)?field.slice(3):field}function isPackaged(path){const segments=path.split("/").filter(Boolean);return!segments.some(segment=>TARBALL_EXCLUDES.some(pattern=>matchesExclude(segment,pattern)))}function matchesExclude(segment,pattern){if(!pattern.includes("*"))return segment===pattern;const source=pattern.split("*").map(part=>part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${source}$`).test(segment)}function fmtElapsed(ms){const total=Math.floor(ms/1e3);const m=Math.floor(total/60);const s=total%60;return`${m}:${s.toString().padStart(2,"0")}`}async function pickTarget(){if(!process.stdin.isTTY){return"cloud"}const rl=createInterface2({input:process.stdin,output:process.stdout});const answer=await new Promise(res=>{console.log("\n Where do you want to deploy?\n");console.log(" 1. dvmkit Cloud (recommended)");console.log(" 2. Self-host (generates Dockerfile)\n");rl.question(" Choice [1]: ",a=>{rl.close();res(a.trim())})});return answer==="2"?"self-host":"cloud"}init_output();async function deployStatus(deployId,opts){const{token,platformUrl}=requireAuth();const{deploy:deploy2,dvm,recovery}=await getDeployStatus(platformUrl,token,deployId);if(opts.human){info(` Deploy: ${deploy2.id}`);info(` Status: ${deploy2.status}`);info(` Slug: ${dvm.slug}`);info(` URL: ${dvm.url??"\u2014"}`);if(dvm.dvmkitUrl)info(` Public: ${dvm.dvmkitUrl}`);info(` Started: ${fmtDate2(deploy2.startedAt)}`);if(deploy2.endedAt)info(` Ended: ${fmtDate2(deploy2.endedAt)}`);if(deploy2.error)info(` Error: ${deploy2.error}`);if(recovery){info(` Recovery: ${recovery.status} (${recovery.deployId})`);if(recovery.error)info(` Recovery error: ${recovery.error}`)}}else{json({status:deploy2.status,url:dvm.url,dvmkitUrl:dvm.dvmkitUrl,slug:dvm.slug,dvmId:deploy2.dvmId,deployId:deploy2.id,startedAt:deploy2.startedAt,endedAt:deploy2.endedAt,error:deploy2.error,...deploy2.releaseAcceptedAt!=null?{releaseAccepted:true}:{},...recovery?{recovery}:{}})}}function fmtDate2(epoch){return new Date(epoch).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}import{createInterface as createInterface3}from"readline";import{DvmError as DvmError20}from"@dvmkit/sdk/internal";init_output();async function destroy(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const keepDb=opts.keepDb??false;if(opts.human){const prompt=keepDb?`This will destroy the compute app for "${slug}" (${dvmId}). Its database will be preserved and can be re-attached on redeploy. Type the DVM ID to confirm: `:`This will permanently delete "${slug}" (${dvmId}) and its database. This cannot be undone. Type the DVM ID to confirm: `;const rl=createInterface3({input:process.stdin,output:process.stderr});const answer=await new Promise(resolve10=>{rl.question(prompt,a=>{rl.close();resolve10(a.trim())})});if(answer!==dvmId){throw new DvmError20("cancelled","Destroy cancelled.")}}else if(!opts.confirm){throw new DvmError20("confirmation_required","Pass --confirm to destroy in non-interactive mode.","Use: dvmctl destroy "+slug+" --confirm")}else if(!keepDb){info(`Note: --keep-db not passed; "${slug}"'s database will be destroyed. (Default changed: pass --keep-db to preserve the cluster for re-attachment.)`)}await destroyDvm(platformUrl,token,dvmId,{keepDb});if(opts.human){if(keepDb){info(`Destroyed "${slug}". Database has been preserved.`)}else{info(`Destroyed "${slug}". Fly app and database have been removed.`)}}else{json({status:"destroyed",dvmId,slug,keptDb:keepDb})}}init_dev_environment();import{execFile}from"child_process";import{tmpdir as tmpdir2}from"os";import{isAbsolute,resolve as resolve7,sep}from"path";import{promisify}from"util";import{readdirSync,statSync}from"fs";import{basename as basename3,dirname as dirname3,join as join7}from"path";function findMnemonicBackups(mnemonicFile,nowMs=Date.now()){const dir=dirname3(mnemonicFile);const prefix=`${basename3(mnemonicFile)}.`;let names;try{names=readdirSync(dir)}catch(err){if(err.code==="ENOENT")return[];throw err}return names.filter(name=>name.startsWith(prefix)&&name.endsWith(".bak")).map(name=>{const path=join7(dir,name);const stat=statSync(path);if(!stat.isFile())return null;const ageMs=Math.max(0,nowMs-stat.mtimeMs);return{path,modifiedAt:stat.mtime.toISOString(),ageMs,ageDays:Math.floor(ageMs/(24*60*60*1e3)),age:formatMnemonicBackupAge(ageMs)}}).filter(backup=>backup!==null).sort((a,b2)=>a.modifiedAt.localeCompare(b2.modifiedAt))}function describeMnemonicBackups(mnemonicFiles,nowMs=Date.now()){const files=[...new Set(typeof mnemonicFiles==="string"?[mnemonicFiles]:mnemonicFiles)];const backups=files.flatMap(mnemonicFile=>findMnemonicBackups(mnemonicFile,nowMs)).sort((a,b2)=>a.modifiedAt.localeCompare(b2.modifiedAt));if(backups.length===0)return null;const listed=backups.map(backup=>`${backup.path} (${backup.age})`).join("; ");const single=backups.length===1;return{display:`${backups.length} plaintext builder-mnemonic backup${single?"":"s"} remain${single?"s":""} on disk: ${listed}.`,hint:`Each file contains older recovery words. Deleting ${single?"it is":"them is"} safe once your password-manager and offline backups are refreshed; until then ${single?"it is a rescue copy":"they are rescue copies"} of an earlier derivation root.`,details:{count:backups.length,paths:backups.map(backup=>backup.path),backups}}}function formatMnemonicBackupAge(ageMs){const minutes2=Math.floor(ageMs/6e4);if(minutes2<1)return"less than a minute old";if(minutes2<60)return`${minutes2} minute${minutes2===1?"":"s"} old`;const hours2=Math.floor(minutes2/60);if(hours2<24)return`${hours2} hour${hours2===1?"":"s"} old`;const days2=Math.floor(hours2/24);return`${days2} day${days2===1?"":"s"} old`}init_defaults();init_output();var execFileAsync=promisify(execFile);var defaultDeps={async dockerVersion(){const result=await execFileAsync("docker",["version","--format","{{.Server.Version}}"],{timeout:3e3});return result.stdout.trim()},async probeMint(url2){const response=await fetch(new URL("/v1/info",ensureTrailingSlash(url2)),{signal:AbortSignal.timeout(3e3)});if(!response.ok)throw new Error(`HTTP ${response.status}`)}};async function builderDoctor(opts,deps=defaultDeps){const checks=[nodeCheck(),callerConfigCheck()];try{const warning=describeMnemonicBackups([BUILDER_MNEMONIC_FILE,LEGACY_BUILDER_MNEMONIC_FILE,RECOVERY_MNEMONIC_FILE]);if(warning){checks.push({name:"mnemonic_backups",group:"files",status:"warn",...warning})}}catch(err){checks.push({name:"mnemonic_backups",group:"files",status:"fail",display:"Could not check the current or legacy builder mnemonic locations for plaintext backups.",hint:`Check that ${BUILDER_CONFIG_DIR} and the directory containing ${RECOVERY_MNEMONIC_FILE} are readable.`,details:{error:message(err)}})}try{const version4=await deps.dockerVersion();checks.push({name:"docker",group:"runtime",status:"ok",display:`Docker server ${version4||"is reachable"}.`,hint:"Docker is used by deploy --dry-run and container-backed tests."})}catch(err){checks.push({name:"docker",group:"runtime",status:"warn",display:"Docker is unavailable; Docker-free paid dev still works.",hint:"Start Docker only for deploy --dry-run, container builds, or container-backed tests.",details:{error:message(err)}})}for(const mint of configuredMints()){try{await deps.probeMint(mint);checks.push({name:`cashu_mint:${mint}`,group:"network",status:"ok",display:`Cashu mint reachable: ${mint}.`})}catch(err){checks.push({name:`cashu_mint:${mint}`,group:"network",status:"fail",display:`Cashu mint is not reachable: ${mint}.`,hint:"Check this mint URL or remove it from DVMKIT_CASHU_MINTS before starting paid dev.",details:{error:message(err),mint}})}}const summary=countSummary(checks);const report={checks,summary,configDir:BUILDER_CONFIG_DIR,cliVersion:CLI_VERSION,nodeVersion:process.version};if(opts.human)renderHuman(report);else json(report);if(summary.fail>0)process.exitCode=1}function nodeCheck(){const major=Number(process.versions.node.split(".")[0]);return major>=22?{name:"node",group:"runtime",status:"ok",display:`Node ${process.versions.node} is supported.`}:{name:"node",group:"runtime",status:"fail",display:`Node ${process.versions.node} is unsupported; Node 22 or newer is required.`,hint:"Install Node 22, then re-run dvmctl doctor."}}function callerConfigCheck(){const dir=process.env.DVM_CONFIG_DIR;const scratchRoot=`${resolve7(tmpdir2())}${sep}`;const resolved=dir&&isAbsolute(dir)?resolve7(dir):void 0;if(resolved?.startsWith(scratchRoot)){return{name:"caller_config",group:"files",status:"ok",display:`Caller state uses checked scratch location ${resolved}.`}}return{name:"caller_config",group:"files",status:"warn",display:dir?`Caller state location is ${dir}; it is not a checked scratch directory.`:"DVM_CONFIG_DIR is not set; paid tests could use the caller's normal wallet.",hint:"Set DVM_CONFIG_DIR to a new absolute temporary directory before a local paid test."}}function configuredMints(){const env2=loadDevEnvironment();const raw2=Object.hasOwn(env2,"DVMKIT_CASHU_MINTS")?env2.DVMKIT_CASHU_MINTS:"";return[...new Set(raw2.split(",").map(mint=>mint.trim()).filter(Boolean))]}function ensureTrailingSlash(value){return value.endsWith("/")?value:`${value}/`}function message(err){return err instanceof Error?err.message:String(err)}function countSummary(checks){const summary={ok:0,warn:0,fail:0};for(const check2 of checks)summary[check2.status]++;return summary}function renderHuman(report){const{summary}=report;info(`Doctor \u2014 OK ${summary.ok} WARN ${summary.warn} FAIL ${summary.fail}`);info(`configDir: ${report.configDir}`);info(`cli: ${report.cliVersion} node: ${report.nodeVersion}`);for(const check2 of report.checks){const badge=check2.status==="ok"?"OK ":check2.status==="warn"?"WARN":"FAIL";info(` ${badge} ${check2.display}`);if(check2.hint)info(` \u21B3 ${check2.hint}`)}}import{DvmError as DvmError21}from"@dvmkit/sdk/internal";init_output();async function domains(action,slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);switch(action){case"add":{if(!opts.domain)throw new DvmError21("bad_request","Domain is required.");const result=await addDomain(platformUrl,token,dvmId,opts.domain);if(opts.human){info(`Domain "${opts.domain}" added to ${slug}.`);if(result.hint)info(result.hint)}else{json({status:"added",dvmId,slug,domain:opts.domain})}break}case"remove":{if(!opts.domain)throw new DvmError21("bad_request","Domain is required.");await removeDomain(platformUrl,token,dvmId,opts.domain);if(opts.human){info(`Domain "${opts.domain}" removed from ${slug}.`)}else{json({status:"removed",dvmId,slug,domain:opts.domain})}break}case"verify":{if(!opts.domain)throw new DvmError21("bad_request","Domain is required.");await verifyDomain(platformUrl,token,dvmId,opts.domain);if(opts.human){info(`Domain "${opts.domain}" verified and TLS certificate provisioned.`)}else{json({status:"verified",dvmId,slug,domain:opts.domain})}break}case"list":{const result=await listDomains(platformUrl,token,dvmId);if(opts.human){if(result.length===0){info("No custom domains configured.")}else{for(const d of result){info(` ${d.domain} (${d.status})`)}}}else{json({dvmId,slug,domains:result})}break}}}import{DvmError as DvmError22}from"@dvmkit/sdk/internal";init_output();async function env(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const hasSet=opts.set&&opts.set.length>0;const hasUnset=opts.unset&&opts.unset.length>0;if(!hasSet&&!hasUnset){const names=await getEnv(platformUrl,token,dvmId);if(opts.human){if(names.length===0){info("No environment variables set.")}else{for(const name of names){info(` ${name}`)}}}else{json({dvmId,slug,env:names})}return}const setMap={};if(hasSet){for(const entry of opts.set??[]){const eqIdx=entry.indexOf("=");if(eqIdx===-1){throw new DvmError22("bad_request",`Invalid format: "${entry}". Use KEY=value.`,"Example: --set API_KEY=abc123")}setMap[entry.slice(0,eqIdx)]=entry.slice(eqIdx+1)}}await setEnv(platformUrl,token,dvmId,{set:hasSet?setMap:void 0,unset:hasUnset?opts.unset:void 0});if(opts.human){const parts=[];if(hasSet)parts.push(`set ${Object.keys(setMap).join(", ")}`);if(hasUnset)parts.push(`unset ${(opts.unset??[]).join(", ")}`);info(`Environment updated: ${parts.join("; ")}.`)}else{json({dvmId,slug,updated:hasSet?Object.keys(setMap):[],removed:hasUnset?opts.unset:[]})}}function parseDurationMs(input){const match=/^(\d+)(s|m|h|d)$/.exec(input.trim());if(!match){throw new Error(`Invalid duration "${input}"; use e.g. 30s, 5m, 2h, 1d`)}const count=Number(match[1]);const unitMs={s:1e3,m:6e4,h:36e5,d:864e5};return count*unitMs[match[2]]}init_output();async function events(slug,opts){if(opts.since)parseDurationMs(opts.since);const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await getEvents(platformUrl,token,dvmId,{since:opts.since});if(opts.human){info(` Events for ${result.slug} (last ${result.since}):`);if(result.events.length===0){info(" (none)")}else{for(const e17 of result.events){info(` ${fmtDate3(e17.timestamp)} ${e17.type.padEnd(16)} ${summarise(e17)}`)}}for(const w of result.warnings??[]){info(` ! ${w}`)}}else{json({...result,dvmId,slug})}}function str(v){if(v==null)return"";if(typeof v==="string")return v;if(typeof v==="number"||typeof v==="boolean")return String(v);return JSON.stringify(v)}function summarise(e17){const d=e17.details;switch(e17.source){case"deploy":{const parts=[str(d.status)];if(d.trigger)parts.push(`via ${str(d.trigger)}`);if(typeof d.durationMs==="number")parts.push(`in ${fmtDuration(d.durationMs)}`);if(d.error)parts.push(`\u2014 ${str(d.error)}`);return parts.filter(Boolean).join(" ")}case"machine":return`${str(d.machineId)}${d.status?` (${str(d.status)})`:""}`;case"audit":return summariseAudit(e17.type,d,e17.actor)}}function summariseAudit(type,d,actor){const by=actor?` by ${actor}`:"";switch(type){case"scale":{const before=d.before;const after=d.after;const bits=[];if(before?.maxMachines!==after?.maxMachines){bits.push(`count ${before?.maxMachines}\u2192${after?.maxMachines}`)}if(before?.memoryMb!==after?.memoryMb||before?.cpuCount!==after?.cpuCount){bits.push(`size ${before?.cpuCount}cpu/${before?.memoryMb}mb\u2192${after?.cpuCount}cpu/${after?.memoryMb}mb`)}return`${bits.join(", ")||"no change"}${by}`}case"env_set":case"env_unset":return`${(d.keys??[]).join(", ")}${by}`;case"restart":return`${(d.machines??[]).length} machine(s)${by}`;case"pause":return`${(d.machines??[]).length} machine(s) stopped${by}`;case"resume":return`${(d.machines??[]).length} machine(s) started${by}`;case"visibility":return`hidden=${str(d.hidden)}${by}`;default:return by.trim()}}function fmtDate3(epoch){return new Date(epoch).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}function fmtDuration(ms){const s=Math.round(ms/1e3);if(s<60)return`${s}s`;const m=Math.floor(s/60);const rem=s%60;return rem>0?`${m}m ${rem}s`:`${m}m`}function parseSince(since){const trimmed=since.trim();const relMatch=/^(\d+)\s*(s|m|h|d)$/.exec(trimmed);if(relMatch){const n=parseInt(relMatch[1],10);const unit=relMatch[2];const multipliers={s:1e3,m:6e4,h:36e5,d:864e5};return Date.now()-n*multipliers[unit]}const parsed=Date.parse(trimmed);if(Number.isNaN(parsed)){throw new Error(`Invalid --since value "${since}". Use a relative window (e.g. "24h", "7d") or an ISO 8601 timestamp.`)}return parsed}init_output();async function feedbackList(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const sinceMs=opts.since!==void 0?parseSince(opts.since):void 0;const limit=opts.limit?parseInt(opts.limit,10):void 0;const result=await listBuilderFeedback(platformUrl,token,{dvmId,sinceMs,cursor:opts.cursor,limit,org:resolveOrgScope(opts)});if(opts.human){info(`Org: ${scopeLabel(result.org)}`);if(result.feedback.length===0){info(`No feedback found for '${slug}' in ${scopeLabel(result.org)}.`);return}info(`${result.feedback.length} feedback row(s):
|
|
2424
|
+
`)}else{console.log(JSON.stringify({status:"ready",file:"Dockerfile",target:"self-host",attestation_env:envVars}))}}function readVmConfig(cwd){const pkg=readPackageJson(cwd);if(pkg?.dvmkit==null)return null;try{return parseVmConfig(pkg.dvmkit)}catch(err){if(err instanceof VmConfigError){throw new DvmError20("invalid_dvmkit_config",`Invalid \`dvmkit\` field in package.json: ${err.message}`,"Check your package.json and try again.")}throw err}}function readInheritSecrets(cwd){const pkg=readPackageJson(cwd);const dvmkit=pkg?.dvmkit;if(dvmkit==null||typeof dvmkit!=="object")return[];const raw2=dvmkit.inheritSecrets;try{return parseInheritSecrets(raw2)}catch(err){if(err instanceof InheritSecretsError){throw new DvmError20("invalid_dvmkit_config",`Invalid \`dvmkit.inheritSecrets\` in package.json: ${err.message}`,"Check your package.json and try again.")}throw err}}function readFeatures(cwd){const pkg=readPackageJson(cwd);const dvmkit=pkg?.dvmkit;if(dvmkit==null||typeof dvmkit!=="object")return{};const raw2=dvmkit.features;try{return parseFeatures(raw2)}catch(err){if(err instanceof FeatureManifestError){throw new DvmError20("invalid_dvmkit_config",`Invalid \`dvmkit.features\` in package.json: ${err.message}`,"Check your package.json and try again.")}throw err}}function readDvmName2(cwd){return readPackageJson(cwd)?.name??null}function findContextRoot(cwd){let dir=cwd;let parent=dirname2(dir);while(parent!==dir){if(existsSync7(resolve6(dir,"package-lock.json")))return dir;dir=parent;parent=dirname2(dir)}if(existsSync7(resolve6(dir,"package-lock.json")))return dir;return cwd}var TARBALL_EXCLUDES=["node_modules",".git","dist",".env",".env.*",".vercel",".next",".turbo","coverage","*.tsbuildinfo",".cache",".verify-logs","*.spec.*-snapshots","*.test.*-snapshots",".claude",".codex"];function createTarball(cwd){return execFileSync("tar",["czf","-",...TARBALL_EXCLUDES.map(e17=>`--exclude=${e17}`),"."],{cwd,maxBuffer:50*1024*1024})}function withDeployBuildContext(cwd,build){const workspaceDir=mkdtempSync(join6(tmpdir(),"dvmkit-deploy-context-"));const contextDir=join6(workspaceDir,"context");const archivePath=join6(workspaceDir,"input.tar.gz");try{mkdirSync5(contextDir);writeFileSync5(archivePath,createTarball(cwd));execFileSync("tar",["xzf",archivePath,"-C",contextDir],{stdio:["ignore","ignore","ignore"]});rmSync(archivePath,{force:true});return build(contextDir)}finally{rmSync(workspaceDir,{recursive:true,force:true})}}function isPackagedTreeDirty(packagedRoot){return packagedTreeDirtyPaths(packagedRoot).length>0}function packagedTreeDirtyPaths(packagedRoot){let raw2;try{raw2=execFileSync("git",["status","--porcelain","-z","--","."],{cwd:packagedRoot,stdio:["ignore","pipe","ignore"],maxBuffer:16*1024*1024}).toString("utf8")}catch{return[]}return raw2.split("\0").filter(Boolean).map(statusEntryPath).filter(isPackaged).sort()}function readGitHead(cwd,packagedRoot){const run=args=>{try{return execFileSync("git",args,{cwd,stdio:["ignore","pipe","ignore"]}).toString("utf8").trim()}catch{return null}};const sha=run(["rev-parse","HEAD"]);if(!sha)return null;const message2=run(["log","-1","--pretty=format:%s","HEAD"]);if(!message2)return null;const ref=run(["symbolic-ref","--short","-q","HEAD"])??"HEAD";const authorName=run(["log","-1","--pretty=format:%an","HEAD"]);const dirty=packagedRoot!=null&&isPackagedTreeDirty(packagedRoot);return{sha:dirty?`${sha}${DIRTY_SUFFIX}`:sha,ref,message:message2,authorName:authorName&&authorName.length>0?authorName:null}}function statusEntryPath(field){return/^[ MADRCU?!][ MADRCU?!] /.test(field)?field.slice(3):field}function isPackaged(path){const segments=path.split("/").filter(Boolean);return!segments.some(segment=>TARBALL_EXCLUDES.some(pattern=>matchesExclude(segment,pattern)))}function matchesExclude(segment,pattern){if(!pattern.includes("*"))return segment===pattern;const source=pattern.split("*").map(part=>part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${source}$`).test(segment)}function fmtElapsed(ms){const total=Math.floor(ms/1e3);const m=Math.floor(total/60);const s=total%60;return`${m}:${s.toString().padStart(2,"0")}`}async function pickTarget(){if(!process.stdin.isTTY){return"cloud"}const rl=createInterface2({input:process.stdin,output:process.stdout});const answer=await new Promise(res=>{console.log("\n Where do you want to deploy?\n");console.log(" 1. dvmkit Cloud (recommended)");console.log(" 2. Self-host (generates Dockerfile)\n");rl.question(" Choice [1]: ",a=>{rl.close();res(a.trim())})});return answer==="2"?"self-host":"cloud"}init_output();async function deployStatus(deployId,opts){const{token,platformUrl}=requireAuth();const{deploy:deploy2,dvm,recovery}=await getDeployStatus(platformUrl,token,deployId);if(opts.human){info(` Deploy: ${deploy2.id}`);info(` Status: ${deploy2.status}`);info(` Slug: ${dvm.slug}`);info(` URL: ${dvm.url??"\u2014"}`);if(dvm.dvmkitUrl)info(` Public: ${dvm.dvmkitUrl}`);info(` Started: ${fmtDate2(deploy2.startedAt)}`);if(deploy2.endedAt)info(` Ended: ${fmtDate2(deploy2.endedAt)}`);if(deploy2.error)info(` Error: ${deploy2.error}`);if(recovery){info(` Recovery: ${recovery.status} (${recovery.deployId})`);if(recovery.error)info(` Recovery error: ${recovery.error}`)}}else{json({status:deploy2.status,url:dvm.url,dvmkitUrl:dvm.dvmkitUrl,slug:dvm.slug,dvmId:deploy2.dvmId,deployId:deploy2.id,startedAt:deploy2.startedAt,endedAt:deploy2.endedAt,error:deploy2.error,...deploy2.releaseAcceptedAt!=null?{releaseAccepted:true}:{},...recovery?{recovery}:{}})}}function fmtDate2(epoch){return new Date(epoch).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}import{createInterface as createInterface3}from"readline";import{DvmError as DvmError21}from"@dvmkit/sdk/internal";init_output();async function destroy(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const keepDb=opts.keepDb??false;if(opts.human){const prompt=keepDb?`This will destroy the compute app for "${slug}" (${dvmId}). Its database will be preserved and can be re-attached on redeploy. Type the DVM ID to confirm: `:`This will permanently delete "${slug}" (${dvmId}) and its database. This cannot be undone. Type the DVM ID to confirm: `;const rl=createInterface3({input:process.stdin,output:process.stderr});const answer=await new Promise(resolve10=>{rl.question(prompt,a=>{rl.close();resolve10(a.trim())})});if(answer!==dvmId){throw new DvmError21("cancelled","Destroy cancelled.")}}else if(!opts.confirm){throw new DvmError21("confirmation_required","Pass --confirm to destroy in non-interactive mode.","Use: dvmctl destroy "+slug+" --confirm")}else if(!keepDb){info(`Note: --keep-db not passed; "${slug}"'s database will be destroyed. (Default changed: pass --keep-db to preserve the cluster for re-attachment.)`)}await destroyDvm(platformUrl,token,dvmId,{keepDb});if(opts.human){if(keepDb){info(`Destroyed "${slug}". Database has been preserved.`)}else{info(`Destroyed "${slug}". Fly app and database have been removed.`)}}else{json({status:"destroyed",dvmId,slug,keptDb:keepDb})}}init_dev_environment();import{execFile}from"child_process";import{tmpdir as tmpdir2}from"os";import{isAbsolute,resolve as resolve7,sep}from"path";import{promisify}from"util";import{readdirSync,statSync}from"fs";import{basename as basename3,dirname as dirname3,join as join7}from"path";function findMnemonicBackups(mnemonicFile,nowMs=Date.now()){const dir=dirname3(mnemonicFile);const prefix=`${basename3(mnemonicFile)}.`;let names;try{names=readdirSync(dir)}catch(err){if(err.code==="ENOENT")return[];throw err}return names.filter(name=>name.startsWith(prefix)&&name.endsWith(".bak")).map(name=>{const path=join7(dir,name);const stat=statSync(path);if(!stat.isFile())return null;const ageMs=Math.max(0,nowMs-stat.mtimeMs);return{path,modifiedAt:stat.mtime.toISOString(),ageMs,ageDays:Math.floor(ageMs/(24*60*60*1e3)),age:formatMnemonicBackupAge(ageMs)}}).filter(backup=>backup!==null).sort((a,b2)=>a.modifiedAt.localeCompare(b2.modifiedAt))}function describeMnemonicBackups(mnemonicFiles,nowMs=Date.now()){const files=[...new Set(typeof mnemonicFiles==="string"?[mnemonicFiles]:mnemonicFiles)];const backups=files.flatMap(mnemonicFile=>findMnemonicBackups(mnemonicFile,nowMs)).sort((a,b2)=>a.modifiedAt.localeCompare(b2.modifiedAt));if(backups.length===0)return null;const listed=backups.map(backup=>`${backup.path} (${backup.age})`).join("; ");const single=backups.length===1;return{display:`${backups.length} plaintext builder-mnemonic backup${single?"":"s"} remain${single?"s":""} on disk: ${listed}.`,hint:`Each file contains older recovery words. Deleting ${single?"it is":"them is"} safe once your password-manager and offline backups are refreshed; until then ${single?"it is a rescue copy":"they are rescue copies"} of an earlier derivation root.`,details:{count:backups.length,paths:backups.map(backup=>backup.path),backups}}}function formatMnemonicBackupAge(ageMs){const minutes2=Math.floor(ageMs/6e4);if(minutes2<1)return"less than a minute old";if(minutes2<60)return`${minutes2} minute${minutes2===1?"":"s"} old`;const hours2=Math.floor(minutes2/60);if(hours2<24)return`${hours2} hour${hours2===1?"":"s"} old`;const days2=Math.floor(hours2/24);return`${days2} day${days2===1?"":"s"} old`}init_defaults();init_output();var execFileAsync=promisify(execFile);var defaultDeps={async dockerVersion(){const result=await execFileAsync("docker",["version","--format","{{.Server.Version}}"],{timeout:3e3});return result.stdout.trim()},async probeMint(url2){const response=await fetch(new URL("/v1/info",ensureTrailingSlash(url2)),{signal:AbortSignal.timeout(3e3)});if(!response.ok)throw new Error(`HTTP ${response.status}`)}};async function builderDoctor(opts,deps=defaultDeps){const checks=[nodeCheck(),callerConfigCheck()];try{const warning=describeMnemonicBackups([BUILDER_MNEMONIC_FILE,LEGACY_BUILDER_MNEMONIC_FILE,RECOVERY_MNEMONIC_FILE]);if(warning){checks.push({name:"mnemonic_backups",group:"files",status:"warn",...warning})}}catch(err){checks.push({name:"mnemonic_backups",group:"files",status:"fail",display:"Could not check the current or legacy builder mnemonic locations for plaintext backups.",hint:`Check that ${BUILDER_CONFIG_DIR} and the directory containing ${RECOVERY_MNEMONIC_FILE} are readable.`,details:{error:message(err)}})}try{const version4=await deps.dockerVersion();checks.push({name:"docker",group:"runtime",status:"ok",display:`Docker server ${version4||"is reachable"}.`,hint:"Docker is used by deploy --dry-run and container-backed tests."})}catch(err){checks.push({name:"docker",group:"runtime",status:"warn",display:"Docker is unavailable; Docker-free paid dev still works.",hint:"Start Docker only for deploy --dry-run, container builds, or container-backed tests.",details:{error:message(err)}})}for(const mint of configuredMints()){try{await deps.probeMint(mint);checks.push({name:`cashu_mint:${mint}`,group:"network",status:"ok",display:`Cashu mint reachable: ${mint}.`})}catch(err){checks.push({name:`cashu_mint:${mint}`,group:"network",status:"fail",display:`Cashu mint is not reachable: ${mint}.`,hint:"Check this mint URL or remove it from DVMKIT_CASHU_MINTS before starting paid dev.",details:{error:message(err),mint}})}}const summary=countSummary(checks);const report={checks,summary,configDir:BUILDER_CONFIG_DIR,cliVersion:CLI_VERSION,nodeVersion:process.version};if(opts.human)renderHuman(report);else json(report);if(summary.fail>0)process.exitCode=1}function nodeCheck(){const major=Number(process.versions.node.split(".")[0]);return major>=22?{name:"node",group:"runtime",status:"ok",display:`Node ${process.versions.node} is supported.`}:{name:"node",group:"runtime",status:"fail",display:`Node ${process.versions.node} is unsupported; Node 22 or newer is required.`,hint:"Install Node 22, then re-run dvmctl doctor."}}function callerConfigCheck(){const dir=process.env.DVM_CONFIG_DIR;const scratchRoot=`${resolve7(tmpdir2())}${sep}`;const resolved=dir&&isAbsolute(dir)?resolve7(dir):void 0;if(resolved?.startsWith(scratchRoot)){return{name:"caller_config",group:"files",status:"ok",display:`Caller state uses checked scratch location ${resolved}.`}}return{name:"caller_config",group:"files",status:"warn",display:dir?`Caller state location is ${dir}; it is not a checked scratch directory.`:"DVM_CONFIG_DIR is not set; paid tests could use the caller's normal wallet.",hint:"Set DVM_CONFIG_DIR to a new absolute temporary directory before a local paid test."}}function configuredMints(){const env2=mergeProjectEnvironment(process.env,loadProjectEnvironment());const raw2=Object.hasOwn(env2,"DVMKIT_CASHU_MINTS")?env2.DVMKIT_CASHU_MINTS:"";return[...new Set(raw2.split(",").map(mint=>mint.trim()).filter(Boolean))]}function ensureTrailingSlash(value){return value.endsWith("/")?value:`${value}/`}function message(err){return err instanceof Error?err.message:String(err)}function countSummary(checks){const summary={ok:0,warn:0,fail:0};for(const check2 of checks)summary[check2.status]++;return summary}function renderHuman(report){const{summary}=report;info(`Doctor \u2014 OK ${summary.ok} WARN ${summary.warn} FAIL ${summary.fail}`);info(`configDir: ${report.configDir}`);info(`cli: ${report.cliVersion} node: ${report.nodeVersion}`);for(const check2 of report.checks){const badge=check2.status==="ok"?"OK ":check2.status==="warn"?"WARN":"FAIL";info(` ${badge} ${check2.display}`);if(check2.hint)info(` \u21B3 ${check2.hint}`)}}import{DvmError as DvmError22}from"@dvmkit/sdk/internal";init_output();async function domains(action,slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);switch(action){case"add":{if(!opts.domain)throw new DvmError22("bad_request","Domain is required.");const result=await addDomain(platformUrl,token,dvmId,opts.domain);if(opts.human){info(`Domain "${opts.domain}" added to ${slug}.`);if(result.hint)info(result.hint)}else{json({status:"added",dvmId,slug,domain:opts.domain})}break}case"remove":{if(!opts.domain)throw new DvmError22("bad_request","Domain is required.");await removeDomain(platformUrl,token,dvmId,opts.domain);if(opts.human){info(`Domain "${opts.domain}" removed from ${slug}.`)}else{json({status:"removed",dvmId,slug,domain:opts.domain})}break}case"verify":{if(!opts.domain)throw new DvmError22("bad_request","Domain is required.");await verifyDomain(platformUrl,token,dvmId,opts.domain);if(opts.human){info(`Domain "${opts.domain}" verified and TLS certificate provisioned.`)}else{json({status:"verified",dvmId,slug,domain:opts.domain})}break}case"list":{const result=await listDomains(platformUrl,token,dvmId);if(opts.human){if(result.length===0){info("No custom domains configured.")}else{for(const d of result){info(` ${d.domain} (${d.status})`)}}}else{json({dvmId,slug,domains:result})}break}}}import{DvmError as DvmError23}from"@dvmkit/sdk/internal";init_output();async function env(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const hasSet=opts.set&&opts.set.length>0;const hasUnset=opts.unset&&opts.unset.length>0;if(!hasSet&&!hasUnset){const names=await getEnv(platformUrl,token,dvmId);if(opts.human){if(names.length===0){info("No environment variables set.")}else{for(const name of names){info(` ${name}`)}}}else{json({dvmId,slug,env:names})}return}const setMap={};if(hasSet){for(const entry of opts.set??[]){const eqIdx=entry.indexOf("=");if(eqIdx===-1){throw new DvmError23("bad_request",`Invalid format: "${entry}". Use KEY=value.`,"Example: --set API_KEY=abc123")}setMap[entry.slice(0,eqIdx)]=entry.slice(eqIdx+1)}}await setEnv(platformUrl,token,dvmId,{set:hasSet?setMap:void 0,unset:hasUnset?opts.unset:void 0});if(opts.human){const parts=[];if(hasSet)parts.push(`set ${Object.keys(setMap).join(", ")}`);if(hasUnset)parts.push(`unset ${(opts.unset??[]).join(", ")}`);info(`Environment updated: ${parts.join("; ")}.`)}else{json({dvmId,slug,updated:hasSet?Object.keys(setMap):[],removed:hasUnset?opts.unset:[]})}}function parseDurationMs(input){const match=/^(\d+)(s|m|h|d)$/.exec(input.trim());if(!match){throw new Error(`Invalid duration "${input}"; use e.g. 30s, 5m, 2h, 1d`)}const count=Number(match[1]);const unitMs={s:1e3,m:6e4,h:36e5,d:864e5};return count*unitMs[match[2]]}init_output();async function events(slug,opts){if(opts.since)parseDurationMs(opts.since);const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await getEvents(platformUrl,token,dvmId,{since:opts.since});if(opts.human){info(` Events for ${result.slug} (last ${result.since}):`);if(result.events.length===0){info(" (none)")}else{for(const e17 of result.events){info(` ${fmtDate3(e17.timestamp)} ${e17.type.padEnd(16)} ${summarise(e17)}`)}}for(const w of result.warnings??[]){info(` ! ${w}`)}}else{json({...result,dvmId,slug})}}function str(v){if(v==null)return"";if(typeof v==="string")return v;if(typeof v==="number"||typeof v==="boolean")return String(v);return JSON.stringify(v)}function summarise(e17){const d=e17.details;switch(e17.source){case"deploy":{const parts=[str(d.status)];if(d.trigger)parts.push(`via ${str(d.trigger)}`);if(typeof d.durationMs==="number")parts.push(`in ${fmtDuration(d.durationMs)}`);if(d.error)parts.push(`\u2014 ${str(d.error)}`);return parts.filter(Boolean).join(" ")}case"machine":return`${str(d.machineId)}${d.status?` (${str(d.status)})`:""}`;case"audit":return summariseAudit(e17.type,d,e17.actor)}}function summariseAudit(type,d,actor){const by=actor?` by ${actor}`:"";switch(type){case"scale":{const before=d.before;const after=d.after;const bits=[];if(before?.maxMachines!==after?.maxMachines){bits.push(`count ${before?.maxMachines}\u2192${after?.maxMachines}`)}if(before?.memoryMb!==after?.memoryMb||before?.cpuCount!==after?.cpuCount){bits.push(`size ${before?.cpuCount}cpu/${before?.memoryMb}mb\u2192${after?.cpuCount}cpu/${after?.memoryMb}mb`)}return`${bits.join(", ")||"no change"}${by}`}case"env_set":case"env_unset":return`${(d.keys??[]).join(", ")}${by}`;case"restart":return`${(d.machines??[]).length} machine(s)${by}`;case"pause":return`${(d.machines??[]).length} machine(s) stopped${by}`;case"resume":return`${(d.machines??[]).length} machine(s) started${by}`;case"visibility":return`hidden=${str(d.hidden)}${by}`;default:return by.trim()}}function fmtDate3(epoch){return new Date(epoch).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}function fmtDuration(ms){const s=Math.round(ms/1e3);if(s<60)return`${s}s`;const m=Math.floor(s/60);const rem=s%60;return rem>0?`${m}m ${rem}s`:`${m}m`}function parseSince(since){const trimmed=since.trim();const relMatch=/^(\d+)\s*(s|m|h|d)$/.exec(trimmed);if(relMatch){const n=parseInt(relMatch[1],10);const unit=relMatch[2];const multipliers={s:1e3,m:6e4,h:36e5,d:864e5};return Date.now()-n*multipliers[unit]}const parsed=Date.parse(trimmed);if(Number.isNaN(parsed)){throw new Error(`Invalid --since value "${since}". Use a relative window (e.g. "24h", "7d") or an ISO 8601 timestamp.`)}return parsed}init_output();async function feedbackList(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const sinceMs=opts.since!==void 0?parseSince(opts.since):void 0;const limit=opts.limit?parseInt(opts.limit,10):void 0;const result=await listBuilderFeedback(platformUrl,token,{dvmId,sinceMs,cursor:opts.cursor,limit,org:resolveOrgScope(opts)});if(opts.human){info(`Org: ${scopeLabel(result.org)}`);if(result.feedback.length===0){info(`No feedback found for '${slug}' in ${scopeLabel(result.org)}.`);return}info(`${result.feedback.length} feedback row(s):
|
|
2425
2425
|
`);const idW=8;const tsW=20;const slugW=Math.max(4,...result.feedback.map(r=>(r.slug??"(platform)").length));const pkW=12;const traceW=12;info(` ${"ID".padEnd(idW)} ${"CREATED".padEnd(tsW)} ${"SLUG".padEnd(slugW)} ${"CALLER".padEnd(pkW)} ${"TRACE".padEnd(traceW)} BODY`);for(const r of result.feedback){const ts=r.created_at.replace("T"," ").slice(0,19);const s=r.slug??"(platform)";const caller=r.caller_pubkey.slice(0,pkW);const trace=(r.trace_id??"-").slice(0,traceW);const body=r.body.length>60?`${r.body.slice(0,57)}\u2026`:r.body;info(` ${r.id.slice(0,idW).padEnd(idW)} ${ts.padEnd(tsW)} ${s.padEnd(slugW)} ${caller.padEnd(pkW)} ${trace.padEnd(traceW)} ${body}`)}if(result.next_cursor){info(`
|
|
2426
|
-
More results available \u2014 re-run with --cursor ${result.next_cursor}`)}}else{json({dvmId,slug,feedback:result.feedback,next_cursor:result.next_cursor,org:result.org})}}async function feedbackEnable(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await updateDvmSettings(platformUrl,token,dvmId,{feedback_enabled:true});if(opts.human){info(`Feedback collection enabled for '${slug}'.`)}else{json({...result,dvmId,slug})}}async function feedbackDisable(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await updateDvmSettings(platformUrl,token,dvmId,{feedback_enabled:false});if(opts.human){info(`Feedback collection disabled for '${slug}'.`)}else{json({...result,dvmId,slug})}}import{DvmError as DvmError23}from"@dvmkit/sdk/internal";init_output();async function handle(h,opts){const creds=resolveAuth();if(!creds){throw new DvmError23("auth_required","Not authenticated.","Set DVMKIT_API_KEY or run `dvmctl auth`.")}const platformUrl=process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev";await setHandle(platformUrl,creds.token,h);if(opts.human){info(`Handle set to "${h}". Your DVMs will be accessible at ${h}--<slug>.dvmkit.ai`)}else{json({status:"ok",handle:h})}}async function handleCheck(h,opts){const platformUrl=process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev";const result=await checkHandle(platformUrl,h);if(opts.human){info(result.available?`"${h}" is available.`:`"${h}" is taken.`)}else{json({handle:h,available:result.available})}}init_output();async function dvmInfo(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const{dvm,deploys,domains:domains2}=await getDvm(platformUrl,token,dvmId);if(opts.human){const suspension=dvm.status==="suspended"?dvm.suspensionReason==="builder_pause"?" (paused \u2014 run `dvmctl resume` to bring it back)":dvm.suspensionReason==="free_tier_idle"?" (idle \u2014 run `dvmctl resume` to bring it back)":` (${dvm.suspensionReason??"suspended by the operator"}${dvm.pausedAt!=null?"; you had also paused it":""})`:"";info(` Name: ${dvm.name}`);info(` Slug: ${dvm.slug}`);info(` Org: ${dvm.orgHandle??"personal"}`);info(` Status: ${dvm.status}${suspension}`);info(` Public URL: ${dvm.dvmkitUrl??"\u2014 (set a handle with `dvmctl handle set <handle>` to get one)"}`);info(` Origin: ${dvm.url??"\u2014"}`);info(` Region: ${dvm.region}`);info(` Created: ${fmtDate4(dvm.createdAt)}`);info(` Updated: ${fmtDate4(dvm.updatedAt)}`);if(deploys.length>0){info("");info(" Recent deploys:");for(const d of deploys.slice(0,5)){const duration3=d.endedAt?` (${fmtDuration2(d.endedAt-d.startedAt)})`:"";info(` #${d.id.slice(0,8)} ${d.status} ${fmtDate4(d.startedAt)}${duration3}`)}}if(domains2.length>0){info("");info(" Domains:");for(const d of domains2){info(` ${d.domain} ${d.status}`)}}}else{json({dvmId,slug,dvm,deploys,domains:domains2})}}function fmtDate4(epoch){return new Date(epoch).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}function fmtDuration2(ms){const s=Math.round(ms/1e3);if(s<60)return`${s}s`;const m=Math.floor(s/60);const rem=s%60;return rem>0?`${m}m ${rem}s`:`${m}m`}init_builder_store();init_output();import{randomUUID}from"crypto";import{DvmError as DvmError24}from"@dvmkit/sdk/internal";function init(handle2,opts){if(!opts.selfHosted){throw new DvmError24("init_requires_self_hosted","`dvmctl init` only applies to self-hosted DVMs.","Platform-hosted DVMs get their canonical_dvm_id from the platform at deploy time. Re-run with --self-hosted if this DVM runs outside dvmkit infrastructure.")}if(!/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(handle2)){throw new DvmError24("invalid_handle",`Handle "${handle2}" is not a valid DVM slug.`,"Handles are 3-40 lowercase alphanumeric characters or hyphens.")}const matches2=findBuilderDvmsByHandle(handle2);if(matches2.length>0){const existing=matches2[0];throw new DvmError24("already_initialized",existing.self_hosted?`Handle "${handle2}" is already initialized with canonical_dvm_id=${existing.canonical_dvm_id}.`:`Handle "${handle2}" already belongs to a deployed DVM (canonical_dvm_id=${existing.canonical_dvm_id}).`,`Initializing over it would mint a second canonical_dvm_id for the same handle, and the Cashu lock keys derive from that ID \u2014 every proof already locked under ${matches2.map(entry=>entry.canonical_dvm_id).join(", ")} would become underivable. If you genuinely want a new identity, melt or write off what is locked to the old one first, then remove that entry from ~/.dvmkit/builder.json by hand.`)}const canonicalDvmId=randomUUID();upsertBuilderDvm(canonicalDvmId,{handle:handle2,canonical_dvm_id:canonicalDvmId,current_rotation_index:0,self_hosted:true});if(opts.human){info(`Initialized self-hosted DVM "${handle2}".`);info(` canonical_dvm_id: ${canonicalDvmId}`);info(" rotation_index: 0");info("");info("Advertise this canonical_dvm_id on /v1/info via the SDK's");info("DVMKIT_CANONICAL_DVM_ID env var (or DVMKIT_DVM_ID for compatibility).")}else{json({status:"initialized",handle:handle2,canonical_dvm_id:canonicalDvmId,current_rotation_index:0,self_hosted:true})}}init_output();async function list(opts){const{token,platformUrl}=requireAuth();const{dvms,org}=await listDvms(platformUrl,token,{org:resolveOrgScope(opts)});if(opts.human){info(`Org: ${scopeLabel(org)}`);if(dvms.length===0){info(`No DVMs found in ${scopeLabel(org)}.`);return}const slugW=Math.max(4,...dvms.map(d=>d.slug.length));const nameW=Math.max(4,...dvms.map(d=>d.name.length));const statusW=Math.max(6,...dvms.map(d=>d.status.length));const regionW=Math.max(6,...dvms.map(d=>d.region.length));const header=` ${"SLUG".padEnd(slugW)} ${"NAME".padEnd(nameW)} ${"STATUS".padEnd(statusW)} ${"REGION".padEnd(regionW)} URL`;info(header);for(const d of dvms){const url2=d.dvmkitUrl??d.url??"\u2014";info(` ${d.slug.padEnd(slugW)} ${d.name.padEnd(nameW)} ${d.status.padEnd(statusW)} ${d.region.padEnd(regionW)} ${url2}`)}}else{json({dvms,org})}}init_builder_mnemonic();init_defaults();init_output();import{DvmError as DvmError25}from"@dvmkit/sdk/internal";function lockCreate(opts){const existing=readBuilderMnemonic();if(existing&&!opts.import&&!opts.force){if(opts.human){info("Builder mnemonic already exists.");info(`Mnemonic stored at: ${BUILDER_MNEMONIC_FILE}`);info("\nTo replace it, re-run with --force (fresh words) or --import <words>");info("(known words). Either way the current mnemonic is copied to a");info("timestamped .bak sibling first.");info("\n\u26A0 Proofs locked to lock pubkeys derived from the current words stop");info(" being spendable once you replace them \u2014 re-run `dvmctl deploy` for");info(" every DVM afterwards.")}else{json({status:"already_exists",mnemonicFile:BUILDER_MNEMONIC_FILE,hint:`A builder mnemonic already exists, so nothing was written. Re-run with --force to generate fresh words, or --import <words> to restore a known mnemonic; either way the current mnemonic is copied to a timestamped .bak sibling (mode 0600) first. Replacing it makes proofs locked to lock pubkeys derived from the current words unspendable, so \`dvmctl deploy\` has to be re-run for every DVM afterwards.`})}return}let mnemonic;if(opts.import){const words=opts.import.trim();if(!isValidMnemonic(words)){throw new DvmError25("invalid_mnemonic","The provided mnemonic is not a valid 12-word BIP-39 phrase.","Check that all 12 words are correct and separated by spaces.")}mnemonic=words}else{mnemonic=generateRecoveryMnemonic()}const{backupFile}=writeBuilderMnemonic(mnemonic,{force:Boolean(opts.import)||Boolean(opts.force)});if(opts.human){if(!opts.import){info("Builder mnemonic generated.\n");info("\u26A0 Write down these 12 words \u2014 they are the ONLY way to recover");info(" Cashu proofs locked to your DVMs. We never see them.\n");const words=mnemonic.split(" ");for(let i=0;i<words.length;i++){info(` ${String(i+1).padStart(2)}. ${words[i]}`)}info("")}else{info("Builder mnemonic imported.\n")}info(`Mnemonic stored at: ${BUILDER_MNEMONIC_FILE}`);if(backupFile){info(`Previous mnemonic backed up to: ${backupFile}`);info("\u26A0 Proofs locked to lock pubkeys derived from the previous mnemonic\n are no longer spendable with this one. Re-run `dvmctl deploy` for\n every DVM so it advertises a lock pubkey you can still derive.")}info("\nThe per-DVM lock pubkey is registered automatically on `dvmctl deploy`.")}else{json({status:opts.import?"imported":"generated",mnemonicFile:BUILDER_MNEMONIC_FILE,...backupFile?{backupFile,hint:`The mnemonic this replaced was copied to ${backupFile} (mode 0600). Proofs locked to lock pubkeys derived from it are not spendable with the new mnemonic \u2014 re-run \`dvmctl deploy\` for every DVM, or restore with \`dvmctl lock create --import\` from the backup.`}:{}})}}init_output();async function logs(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);if(opts.since)parseDurationMs(opts.since);if(opts.tail){const handle2=await streamLogs(platformUrl,token,dvmId,{since:opts.since},line=>{raw(line)});process.on("SIGINT",()=>{handle2.stop();process.exit(0)});await new Promise(()=>{});return}const lineCount=opts.lines?Number(opts.lines):100;const logLines=await getLogs(platformUrl,token,dvmId,{lines:lineCount,since:opts.since});for(const line of logLines){raw(line)}}init_output();import{DvmError as DvmError26}from"@dvmkit/sdk/internal";async function drainsOwed(handle2,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.getPendingDrains());const now=Date.now();const owed=res.drains.filter(d=>d.settlement==="manual").sort((a,b2)=>a.created_at-b2.created_at).map(d=>({...d,age_ms:Math.max(0,now-d.created_at)}));const totals=totalsByCurrency(owed);if(opts.human){if(owed.length===0){info("No stablecoin refunds are waiting on you. Nothing to settle by hand.");return}for(const drain of owed){raw(`${drain.credit_id} ${drain.drain_id} ${drain.method} ${formatOwed(drain)} to=${payoutAddress(drain)} ${formatAge(drain.age_ms)} old`)}info(`${owed.length} refund(s) owed: ${totals.map(t2=>formatMicro2(t2.amount_micro,t2.currency)).join(", ")}. Record one with \`dvmctl credit drain-settle ${handle2} <credit-id> <drain-id> --tx <hash>\`.`);return}json({op:"credit_drains_owed",handle:handle2,dvmId,slug:handle2,drains:owed,owed_count:owed.length,owed_totals:totals,display:owed.length===0?"This DVM owes no stablecoin refunds that a person has to settle.":`${owed.length} stablecoin refund(s) are owed to callers and no job will pay them: ${totals.map(t2=>formatMicro2(t2.amount_micro,t2.currency)).join(", ")}. Each one was debited from the caller's balance already, so the money is owed whether or not it is sent.`,hint:"Send each payout on its own rail (`method` names it, `payout.address` is the destination, `amount_native` is the figure in the token's own units), then record it with `dvmctl credit drain-settle <handle> <credit-id> <drain-id> --tx <hash>`."})}async function drainSettle(handle2,creditId,drainId,opts){const transaction=opts.tx?.trim();if(!transaction){throw new DvmError26("missing_transaction","No settlement transaction named.","Pass `--tx <hash>` \u2014 the on-chain transaction that paid the refund. It is the only evidence this row will ever carry, and `dvmctl credit drains-owed` lists the credit and drain ids to go with it.")}const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.markDrainSent({credit_id:creditId,drain_id:drainId,sent_ref:{transaction,settled_by:"operator",...opts.note===void 0?{}:{note:opts.note}}}));if(opts.human){info(res.replayed?`Drain ${drainId} was already recorded as sent \u2014 nothing changed, and your transaction was not recorded over the one on file.`:`Recorded ${transaction} against drain ${drainId} on ${creditId}.`);return}json({op:"credit_drain_settle",handle:handle2,dvmId,slug:handle2,credit_id:res.credit_id,drain_id:res.drain_id,transaction,replayed:res.replayed,display:res.replayed?`This refund was already recorded as sent, so nothing changed and the settlement reference on file was left alone. If you just sent the payout, check the recorded transaction before sending another \u2014 it may already have been paid.`:`Recorded the payout for drain ${drainId} on ${creditId}. The caller's next reclaim poll sees it settled, with a countersigned receipt.`,hint:"The reclaim is reported to the platform inside the same transaction as this transition, so its liability view catches up without another command \u2014 and exactly once, however many times this runs."})}function totalsByCurrency(drains){const byCurrency=new Map;for(const drain of drains){const total=byCurrency.get(drain.currency)??{currency:drain.currency,amount_micro:0,count:0};total.amount_micro+=drain.amount_micro;total.count++;byCurrency.set(drain.currency,total)}return[...byCurrency.values()].sort((a,b2)=>a.currency.localeCompare(b2.currency))}function payoutAddress(drain){const payout=drain.payout;return payout.address??"-"}function formatOwed(drain){const fiat=formatMicro2(drain.amount_micro,drain.currency);return drain.amount_native===null?fiat:`${fiat} (${drain.amount_native} native)`}function formatMicro2(amountMicro,currency){return`${(amountMicro/1e6).toFixed(6)} ${currency.toUpperCase()}`}function formatAge(ms){const seconds2=Math.floor(ms/1e3);if(seconds2<60)return`${seconds2}s`;if(seconds2<3600)return`${Math.round(seconds2/60)}m`;if(seconds2<86400)return`${Math.round(seconds2/3600)}h`;return`${Math.round(seconds2/86400)}d`}import{checkMeltQuoteState,DvmError as DvmError27,fetchLnurlPayInvoice,fetchMeltQuote,getInputFeesForProofs,makeInvoice,missingDleqRecoveryDiagnostic as missingDleqRecoveryDiagnostic2,parseNwcUri as parseNwcUri2,toLockPubkey as toLockPubkey3}from"@dvmkit/sdk/internal";init_builder_lock_identity();init_defaults();import{chmodSync as chmodSync3,existsSync as existsSync8,mkdirSync as mkdirSync6,readFileSync as readFileSync9,writeFileSync as writeFileSync6}from"fs";function recordDrainState(dvmId,known,nowMs=Date.now()){const state=readState();if(known){if(!state.has(dvmId))return null;state.delete(dvmId);writeState(state);return null}const existing=state.get(dvmId)?.unknown_since;if(existing)return existing;const since=new Date(nowMs).toISOString();state.set(dvmId,{unknown_since:since});writeState(state);return since}function drainHoldElapsedMs(unknownSince,nowMs=Date.now()){if(!unknownSince)return null;const startedMs=Date.parse(unknownSince);if(Number.isNaN(startedMs))return null;return Math.max(0,nowMs-startedMs)}function readState(){const state=new Map;if(!existsSync8(DRAIN_HOLD_STATE_FILE))return state;try{const parsed=JSON.parse(readFileSync9(DRAIN_HOLD_STATE_FILE,"utf-8"));if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return state;for(const[dvmId,entry]of Object.entries(parsed)){const since=entry?.unknown_since;if(typeof since==="string")state.set(dvmId,{unknown_since:since})}return state}catch{return new Map}}function writeState(state){try{if(!existsSync8(BUILDER_CONFIG_DIR)){mkdirSync6(BUILDER_CONFIG_DIR,{recursive:true,mode:448})}writeFileSync6(DRAIN_HOLD_STATE_FILE,JSON.stringify(Object.fromEntries(state)),{mode:384});chmodSync3(DRAIN_HOLD_STATE_FILE,384)}catch{}}init_defaults();import{appendFileSync,chmodSync as chmodSync4,existsSync as existsSync9,mkdirSync as mkdirSync7,readFileSync as readFileSync10,writeFileSync as writeFileSync7}from"fs";function appendPreMelt(entry){appendEntry({...entry,kind:"pre_melt",ts:Date.now()})}function appendPostMelt(entry){appendEntry({...entry,kind:"post_melt",ts:Date.now()})}function readInFlight(dvmId){if(!existsSync9(MELT_PENDING_LOG_FILE))return[];const raw2=readFileSync10(MELT_PENDING_LOG_FILE,"utf-8");const pre=new Map;const done=new Set;for(const line of raw2.split("\n")){if(!line)continue;let entry;try{entry=JSON.parse(line)}catch{continue}if(entry.dvm_id!==dvmId)continue;const key=`${entry.dvm_id}|${entry.quote_id}`;if(entry.kind==="pre_melt"){pre.set(key,entry)}else{done.add(key)}}const out=[];for(const[key,entry]of pre){if(done.has(key))continue;out.push({ts:entry.ts,dvmId:entry.dvm_id,rowIds:entry.row_ids,mintUrl:entry.mint_url,quoteId:entry.quote_id,lockPubkey:entry.lock_pubkey,totalSats:entry.total_sats})}return out}function appendEntry(entry){ensureLogFile();appendFileSync(MELT_PENDING_LOG_FILE,JSON.stringify(entry)+"\n")}function ensureLogFile(){if(!existsSync9(BUILDER_CONFIG_DIR)){mkdirSync7(BUILDER_CONFIG_DIR,{recursive:true,mode:448})}if(!existsSync9(MELT_PENDING_LOG_FILE)){writeFileSync7(MELT_PENDING_LOG_FILE,"",{mode:384})}else{chmodSync4(MELT_PENDING_LOG_FILE,384)}}init_defaults();import{chmodSync as chmodSync5,existsSync as existsSync10,mkdirSync as mkdirSync8,readFileSync as readFileSync11,writeFileSync as writeFileSync8}from"fs";function recordMeltSuccess(dvmId,mode,run,nowMs=Date.now()){const state=readState2();const existing=state.get(dvmId)??{sweep:null,drains_only:null};state.set(dvmId,{...existing,[mode]:{...run,at:new Date(nowMs).toISOString()}});writeState2(state)}function readMeltSuccesses(){return readState2()}function meltRunAgeMs(run,nowMs=Date.now()){if(!run)return null;const atMs=Date.parse(run.at);if(Number.isNaN(atMs))return null;if(atMs>nowMs)return null;return nowMs-atMs}function readState2(){const state=new Map;if(!existsSync10(MELT_SUCCESS_FILE))return state;try{const parsed=JSON.parse(readFileSync11(MELT_SUCCESS_FILE,"utf-8"));if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return state;for(const[dvmId,entry]of Object.entries(parsed)){const record2=coerce(entry);if(record2)state.set(dvmId,record2)}return state}catch{return new Map}}function coerce(entry){if(!entry||typeof entry!=="object"||Array.isArray(entry))return null;const candidate=entry;const sweep=coerceRun(candidate.sweep);const drainsOnly=coerceRun(candidate.drains_only);if(!sweep&&!drainsOnly)return null;return{sweep,drains_only:drainsOnly}}function coerceRun(run){if(!run||typeof run!=="object"||Array.isArray(run))return null;const candidate=run;if(typeof candidate.at!=="string")return null;return{at:candidate.at,handle:typeof candidate.handle==="string"?candidate.handle:"",batches_melted:numberOr(candidate.batches_melted),sats_melted:numberOr(candidate.sats_melted),drains_parked:numberOr(candidate.drains_parked)}}function numberOr(value){return typeof value==="number"&&Number.isFinite(value)?value:0}function writeState2(state){try{if(!existsSync10(BUILDER_CONFIG_DIR)){mkdirSync8(BUILDER_CONFIG_DIR,{recursive:true,mode:448})}writeFileSync8(MELT_SUCCESS_FILE,JSON.stringify(Object.fromEntries(state)),{mode:384});chmodSync5(MELT_SUCCESS_FILE,384)}catch{}}init_builder_store();init_output();var U32_MASK643=(()=>BigInt(2**32-1))();var _32n3=BigInt(32);function fromBig3(n,le=false){if(le)return{h:Number(n&U32_MASK643),l:Number(n>>_32n3&U32_MASK643)};return{h:Number(n>>_32n3&U32_MASK643)|0,l:Number(n&U32_MASK643)|0}}function split3(lst,le=false){const len=lst.length;let Ah=new Uint32Array(len);let Al=new Uint32Array(len);for(let i=0;i<len;i++){const{h,l}=fromBig3(lst[i],le);[Ah[i],Al[i]]=[h,l]}return[Ah,Al]}var fromNumH=n=>n/2**32|0;var fromNumL=n=>n>>>0;function setU64FromNum(view,byteOffset,n,isLE3){const h=fromNumH(n);const l=fromNumL(n);view.setUint32(byteOffset,isLE3?l:h,isLE3);view.setUint32(byteOffset+4,isLE3?h:l,isLE3)}var shrSH=(h,_l,s)=>h>>>s;var shrSL=(h,l,s)=>h<<32-s|l>>>s;var rotrSH=(h,l,s)=>h>>>s|l<<32-s;var rotrSL=(h,l,s)=>h<<32-s|l>>>s;var rotrBH=(h,l,s)=>h<<64-s|l>>>s-32;var rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:l|0}}var add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0);var add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0;var add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0);var add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0;var add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0);var add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0;function isBytes5(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}var atitle=title=>title?`"${title}" `:"";function anumber5(n,title=""){if(typeof n!=="number")throw new TypeError(atitle(title)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(atitle(title)+"expected integer >= 0, got "+n);return n}function abytes4(value,length,title=""){if(isBytes5(value)&&(length===void 0||value.length===length))return value;if(length!==void 0)anumber5(length,"length");const bytes=isBytes5(value);const ofLen=length!==void 0?` of length ${length}`:"";const got=bytes?`length=${value.length}`:`type=${typeof value}`;const message2=atitle(title)+"expected Uint8Array"+ofLen+", got "+got;if(!bytes)throw new TypeError(message2);throw new RangeError(message2)}function ahash2(h){if(typeof h!=="function"||typeof h.create!=="function")throw new TypeError("expected hash wrapped by utils.createHasher");anumber5(h.outputLen);anumber5(h.blockLen);if(h.outputLen<1||h.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var aobject=(value,label)=>{if(value===null||typeof value!=="object"||Array.isArray(value))throw new TypeError((label==="object"?"":`"${label}" `)+"expected object, got type="+typeof value)};var aopts=(value,label)=>{aobject(value,label);const proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)throw new TypeError(`"${label}" expected plain object`);if(Object.hasOwn(value,"__proto__"))throw new TypeError(`"${label}.__proto__" is not allowed`)};function aexists4(instance,checkFinished=true){if(instance.destroyed)throw new Error("hash was destroyed");if(checkFinished&&instance.finished)throw new Error("digest() was already called")}function aoutput4(out,instance){abytes4(out,void 0,"output");const min=instance.outputLen;if(!(out.length>=min)){throw new RangeError('"output" expected length >= '+min)}}function clean4(...arrays){for(let i=0;i<arrays.length;i++){arrays[i].fill(0)}}function createView3(arr){return new DataView(arr.buffer,arr.byteOffset,arr.byteLength)}function rotr3(word,shift){return word<<32-shift|word>>>shift}function rotl2(word,shift){return word<<shift|word>>>32-shift>>>0}var hasHexBuiltin2=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")();var hexes3=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));function bytesToHex2(bytes){abytes4(bytes);if(hasHexBuiltin2)return bytes.toHex();let hex3="";for(let i=0;i<bytes.length;i++){hex3+=hexes3[bytes[i]]}return hex3}function asciiToBase16(ch){return ch>=48&&ch<=57?ch-48:ch>=65&&ch<=70?ch-(65-10):ch>=97&&ch<=102?ch-(97-10):void 0}function hexToBytes2(hex3){if(typeof hex3!=="string")throw new TypeError("hex string expected, got "+typeof hex3);if(hasHexBuiltin2){try{return Uint8Array.fromHex(hex3)}catch(error51){if(error51 instanceof SyntaxError)throw new RangeError(error51.message);throw error51}}const hl=hex3.length;const al=hl/2;if(hl%2)throw new RangeError("hex string expected, got unpadded hex of length "+hl);const array2=new Uint8Array(al);for(let ai=0,hi=0;ai<al;ai++,hi+=2){const n1=asciiToBase16(hex3.charCodeAt(hi));const n2=asciiToBase16(hex3.charCodeAt(hi+1));if(n1===void 0||n2===void 0){const char=hex3[hi]+hex3[hi+1];throw new RangeError('hex string expected, got non-hex character "'+char+'" at index '+hi)}array2[ai]=n1*16+n2}return array2}function utf8ToBytes3(str2){if(typeof str2!=="string")throw new TypeError("string expected");const encoded=new TextEncoder().encode(str2);try{return new Uint8Array(encoded)}finally{clean4(encoded)}}function concatBytes(...arrays){let sum2=0;for(let i=0;i<arrays.length;i++){const a=arrays[i];abytes4(a);sum2+=a.length}const res=new Uint8Array(sum2);for(let i=0,pad4=0;i<arrays.length;i++){const a=arrays[i];res.set(a,pad4);pad4+=a.length}return res}function checkOpts(defaults,opts,title="opts"){aopts(defaults,"defaults");if(opts!==void 0)aopts(opts,title);const merged=Object.assign(Object.create(null),defaults,opts);return merged}function createHasher4(hashCons,info2={}){if(typeof hashCons!=="function")throw new TypeError('"hashCons" expected function, got type='+typeof hashCons);info2=checkOpts({},info2,"info");const hashC=(msg,opts)=>hashCons(opts).update(msg).digest();const tmp=hashCons(void 0);hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.canXOF=tmp.canXOF;hashC.create=opts=>hashCons(opts);Object.assign(hashC,info2);return Object.freeze(hashC)}function randomBytes3(bytesLength=32){anumber5(bytesLength,"bytesLength");const cr=typeof globalThis==="object"?globalThis.crypto:null;if(typeof cr?.getRandomValues!=="function")throw new Error("crypto.getRandomValues must be defined");if(bytesLength>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);return cr.getRandomValues(new Uint8Array(bytesLength))}var oidNist2=suffix=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,suffix])});function Chi3(a,b2,c){return a&b2^~a&c}function Maj3(a,b2,c){return a&b2^a&c^b2&c}var HashMD3=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(blockLen,outputLen,padOffset,isLE3){this.blockLen=blockLen;this.outputLen=outputLen;this.padOffset=padOffset;this.isLE=isLE3;this.buffer=new Uint8Array(blockLen);this.view=createView3(this.buffer)}update(data){aexists4(this);abytes4(data);const{view,buffer,blockLen}=this;const len=data.length;let processed=false;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){const dataView=createView3(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);processed=true;continue}buffer.set(pos===0&&take===len?data:data.subarray(pos,pos+take),this.pos);this.pos+=take;pos+=take;if(this.pos===blockLen){this.process(view,0);this.pos=0;processed=true}}this.length+=data.length;if(processed)this.roundClean();return this}digestInto(out){aexists4(this);aoutput4(out,this);this.finished=true;const{buffer,view,blockLen,isLE:isLE3}=this;let{pos}=this;buffer[pos++]=128;buffer.fill(0,pos);if(this.padOffset>blockLen-pos){this.process(view,0);buffer.fill(0)}setU64FromNum(view,blockLen-8,this.length*8,isLE3);this.process(view,0);this.roundClean();const oview=out===buffer?view:createView3(out);const len=this.outputLen;const outLen=len/4;const state=this.get();if(len%4||outLen>state.length)throw new Error("invalid outputLen");for(let i=0;i<outLen;i++)oview.setUint32(4*i,state[i],isLE3)}digest(){const{buffer,outputLen}=this;this.digestInto(buffer);const res=buffer.slice(0,outputLen);this.destroy();return res}_cloneIntoMeta(to){const{buffer,length,finished,destroyed,pos}=this;to.destroyed=destroyed;to.finished=finished;to.length=length;to.pos=pos;if(pos)to.buffer.set(buffer);return to}clone(){return this._cloneInto()}};var SHA256_IV3=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var SHA512_IV3=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var SHA256_K3=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]);var SHA256_W3=new Uint32Array(64);var SHA2_32B2=class extends HashMD3{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(outputLen,IV){super(64,outputLen,8,false);this.A=IV[0]|0;this.B=IV[1]|0;this.C=IV[2]|0;this.D=IV[3]|0;this.E=IV[4]|0;this.F=IV[5]|0;this.G=IV[6]|0;this.H=IV[7]|0}get(){const{A:A2,B:B2,C,D:D2,E:E2,F,G:G2,H:H2}=this;return[A2,B2,C,D2,E2,F,G2,H2]}set(A2,B2,C,D2,E2,F,G2,H2){this.A=A2|0;this.B=B2|0;this.C=C|0;this.D=D2|0;this.E=E2|0;this.F=F|0;this.G=G2|0;this.H=H2|0}_cloneInto(to){(to||=new this.constructor).set(...this.get());return this._cloneIntoMeta(to)}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W3[i]=view.getUint32(offset,false);for(let i=16;i<64;i++){const W15=SHA256_W3[i-15];const W2=SHA256_W3[i-2];const s0=rotr3(W15,7)^rotr3(W15,18)^W15>>>3;const s1=rotr3(W2,17)^rotr3(W2,19)^W2>>>10;SHA256_W3[i]=s1+SHA256_W3[i-7]+s0+SHA256_W3[i-16]|0}let{A:A2,B:B2,C,D:D2,E:E2,F,G:G2,H:H2}=this;for(let i=0;i<64;i++){const sigma1=rotr3(E2,6)^rotr3(E2,11)^rotr3(E2,25);const T12=H2+sigma1+Chi3(E2,F,G2)+SHA256_K3[i]+SHA256_W3[i]|0;const sigma0=rotr3(A2,2)^rotr3(A2,13)^rotr3(A2,22);const T2=sigma0+Maj3(A2,B2,C)|0;H2=G2;G2=F;F=E2;E2=D2+T12|0;D2=C;C=B2;B2=A2;A2=T12+T2|0}A2=A2+this.A|0;B2=B2+this.B|0;C=C+this.C|0;D2=D2+this.D|0;E2=E2+this.E|0;F=F+this.F|0;G2=G2+this.G|0;H2=H2+this.H|0;this.set(A2,B2,C,D2,E2,F,G2,H2)}roundClean(){clean4(SHA256_W3)}destroy(){this.destroyed=true;this.set(0,0,0,0,0,0,0,0);clean4(this.buffer)}};var _SHA2562=class extends SHA2_32B2{constructor(){super(32,SHA256_IV3)}};var K512=(()=>split3(["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(n=>BigInt(n))))();var SHA512_Kh=(()=>K512[0])();var SHA512_Kl=(()=>K512[1])();var SHA512_W_H=new Uint32Array(80);var SHA512_W_L=new Uint32Array(80);var SHA2_64B=class extends HashMD3{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(outputLen,IV){super(128,outputLen,16,false);this.Ah=IV[0]|0;this.Al=IV[1]|0;this.Bh=IV[2]|0;this.Bl=IV[3]|0;this.Ch=IV[4]|0;this.Cl=IV[5]|0;this.Dh=IV[6]|0;this.Dl=IV[7]|0;this.Eh=IV[8]|0;this.El=IV[9]|0;this.Fh=IV[10]|0;this.Fl=IV[11]|0;this.Gh=IV[12]|0;this.Gl=IV[13]|0;this.Hh=IV[14]|0;this.Hl=IV[15]|0}get(){const{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0;this.Al=Al|0;this.Bh=Bh|0;this.Bl=Bl|0;this.Ch=Ch|0;this.Cl=Cl|0;this.Dh=Dh|0;this.Dl=Dl|0;this.Eh=Eh|0;this.El=El|0;this.Fh=Fh|0;this.Fl=Fl|0;this.Gh=Gh|0;this.Gl=Gl|0;this.Hh=Hh|0;this.Hl=Hl|0}_cloneInto(to){(to||=new this.constructor).set(...this.get());return this._cloneIntoMeta(to)}process(view,offset){for(let i=0;i<16;i++,offset+=4){SHA512_W_H[i]=view.getUint32(offset);SHA512_W_L[i]=view.getUint32(offset+=4)}for(let i=16;i<80;i++){const W15h=SHA512_W_H[i-15]|0;const W15l=SHA512_W_L[i-15]|0;const s0h=rotrSH(W15h,W15l,1)^rotrSH(W15h,W15l,8)^shrSH(W15h,W15l,7);const s0l=rotrSL(W15h,W15l,1)^rotrSL(W15h,W15l,8)^shrSL(W15h,W15l,7);const W2h=SHA512_W_H[i-2]|0;const W2l=SHA512_W_L[i-2]|0;const s1h=rotrSH(W2h,W2l,19)^rotrBH(W2h,W2l,61)^shrSH(W2h,W2l,6);const s1l=rotrSL(W2h,W2l,19)^rotrBL(W2h,W2l,61)^shrSL(W2h,W2l,6);const SUMl=add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]);const SUMh=add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=SUMh|0;SHA512_W_L[i]=SUMl|0}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){const sigma1h=rotrSH(Eh,El,14)^rotrSH(Eh,El,18)^rotrBH(Eh,El,41);const sigma1l=rotrSL(Eh,El,14)^rotrSL(Eh,El,18)^rotrBL(Eh,El,41);const CHIh=Eh&Fh^~Eh&Gh;const CHIl=El&Fl^~El&Gl;const T1ll=add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]);const T1h=add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]);const T1l=T1ll|0;const sigma0h=rotrSH(Ah,Al,28)^rotrBH(Ah,Al,34)^rotrBH(Ah,Al,39);const sigma0l=rotrSL(Ah,Al,28)^rotrBL(Ah,Al,34)^rotrBL(Ah,Al,39);const MAJh=Ah&Bh^Ah&Ch^Bh&Ch;const MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0;Hl=Gl|0;Gh=Fh|0;Gl=Fl|0;Fh=Eh|0;Fl=El|0;({h:Eh,l:El}=add(Dh|0,Dl|0,T1h|0,T1l|0));Dh=Ch|0;Dl=Cl|0;Ch=Bh|0;Cl=Bl|0;Bh=Ah|0;Bl=Al|0;const All=add3L(T1l,sigma0l,MAJl);Ah=add3H(All,T1h,sigma0h,MAJh);Al=All|0}({h:Ah,l:Al}=add(this.Ah|0,this.Al|0,Ah|0,Al|0));({h:Bh,l:Bl}=add(this.Bh|0,this.Bl|0,Bh|0,Bl|0));({h:Ch,l:Cl}=add(this.Ch|0,this.Cl|0,Ch|0,Cl|0));({h:Dh,l:Dl}=add(this.Dh|0,this.Dl|0,Dh|0,Dl|0));({h:Eh,l:El}=add(this.Eh|0,this.El|0,Eh|0,El|0));({h:Fh,l:Fl}=add(this.Fh|0,this.Fl|0,Fh|0,Fl|0));({h:Gh,l:Gl}=add(this.Gh|0,this.Gl|0,Gh|0,Gl|0));({h:Hh,l:Hl}=add(this.Hh|0,this.Hl|0,Hh|0,Hl|0));this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){clean4(SHA512_W_H,SHA512_W_L)}destroy(){this.destroyed=true;clean4(this.buffer);this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var _SHA512=class extends SHA2_64B{constructor(){super(64,SHA512_IV3)}};var sha2565=createHasher4(()=>new _SHA2562,oidNist2(1));var sha5122=createHasher4(()=>new _SHA512,oidNist2(3));var freeze=fn=>Object.freeze(fn());function isBytes6(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}function abytes5(b2){if(!isBytes6(b2))throw new TypeError("Uint8Array expected")}function afn2(input){if(typeof input!=="function")throw new TypeError("function expected");return true}function astr2(label,input){if(typeof input!=="string")throw new TypeError(`${label}: string expected`);return true}function anumber6(n,title="number"){if(typeof n!=="number")throw new TypeError(`${title}: expected number, got ${typeof n}`);if(!Number.isSafeInteger(n))throw new RangeError(`${title}: expected safe integer, got ${n}`)}function chain2(...args){const id=a=>a;const wrap=(a,b2)=>c=>a(b2(c));const encode2=args.map(x2=>x2.encode).reduceRight(wrap,id);const decode2=args.map(x2=>x2.decode).reduce(wrap,id);return{encode:encode2,decode:decode2}}var powers2=(()=>{let res=[];for(let i=0;i<40;i++)res.push(2**i);return res})();var asciiDecoder=(()=>{try{const decoder3=new TextDecoder;return decoder3.decode(Uint8Array.of(65,48,43,127))==="A0+\x7F"?decoder3:void 0}catch(e17){return void 0}})();var B2S_CHUNK=8192;function charcodesToString(codes){const len=codes.length;if(asciiDecoder!==void 0&&len>=12)return asciiDecoder.decode(codes);if(len<=B2S_CHUNK)return String.fromCharCode.apply(null,codes);let res="";for(let i=0;i<len;i+=B2S_CHUNK)res+=String.fromCharCode.apply(null,codes.subarray(i,i+B2S_CHUNK));return res}function radix22(bits){anumber6(bits);if(bits<=0||bits>8)throw new RangeError("radix2: bits should be in (0..8]");const mask=powers2[bits]-1;return{encode:bytes=>{abytes5(bytes);const len=bytes.length;const res=new Uint8Array(Math.ceil(len*8/bits));let carry2=0;let pos=0;let j2=0;for(let i=0;i<len;){if(i+2<len){carry2=carry2<<24|bytes[i]<<16|bytes[i+1]<<8|bytes[i+2];pos+=24;i+=3}else{carry2=(carry2<<8|bytes[i])&65535;pos+=8;i++}for(;;){pos-=bits;res[j2++]=carry2>>pos&mask;if(pos<bits)break}}if(pos>0)res[j2]=carry2<<bits-pos&mask;return res},decode:digits=>{const len=digits.length;const res=new Uint8Array(Math.floor(len*bits/8));let carry2=0;let pos=0;let j2=0;for(let i=0;i<len;i++){carry2=(carry2<<bits|digits[i])&65535;pos+=bits;for(;pos>=8;pos-=8)res[j2++]=carry2>>pos-8&255}carry2=carry2<<8-pos&255;if(pos>=bits)throw new Error("Excess padding");if(carry2>0)throw new Error(`Non-zero padding: ${carry2}`);return res}}}function alphabet2(letters,aliases){const len=letters.length;if(len>128)throw new Error("alphabet: max 128 letters");const encTable=new Uint8Array(len);const decTable=new Int8Array(128).fill(-1);for(let i=0;i<len;i++){const code=letters.charCodeAt(i);if(letters.codePointAt(i)!==code||code>127)throw new Error("alphabet: single-char ASCII letters only");encTable[i]=code;decTable[code]=i}if(aliases!==void 0){for(const alias of Object.keys(aliases)){const code=alias.charCodeAt(0);const target=decTable[aliases[alias].charCodeAt(0)];if(alias.length!==1||code>127||target===void 0||target===-1)throw new Error(`alphabet: invalid alias ${alias}`);decTable[code]=target}}return{encode:digits=>{const codes=new Uint8Array(digits.length);for(let i=0;i<digits.length;i++){const d=digits[i];const code=encTable[d];if(code===void 0)throw new Error(`alphabet.encode: invalid digit ${d}`);codes[i]=code}return charcodesToString(codes)},decode:input=>{astr2("decode",input);const slen=input.length;const digits=new Uint8Array(slen);for(let i=0;i<slen;i++){const code=input.charCodeAt(i);const digit=code<128?decTable[code]:-1;if(digit===-1)throw new Error(`Unknown letter "${input[i]}". Allowed: ${letters}`);digits[i]=digit}return digits}}}function padding2(bits,chr="="){anumber6(bits);astr2("padding",chr);return{encode(data){while(data.length*bits%8)data+=chr;return data},decode(input){astr2("decode",input);let end=input.length;if(end*bits%8)throw new Error("padding: invalid length");for(;end>0&&input[end-1]===chr;end--){const byte=(end-1)*bits;if(byte%8===0)throw new Error("padding: excess padding")}return input.slice(0,end)}}}function checksum4(len,fn){anumber6(len);if(len<=0)throw new RangeError(`checksum length must be positive: ${len}`);afn2(fn);const _fn=fn;return{encode(data){abytes5(data);const sum2=_fn(data).slice(0,len);const res=new Uint8Array(data.length+len);res.set(data);res.set(sum2,data.length);return res},decode(data){abytes5(data);const payload=data.slice(0,-len);const oldChecksum=data.slice(-len);const newChecksum=_fn(payload).slice(0,len);for(let i=0;i<len;i++)if(newChecksum[i]!==oldChecksum[i])throw new Error("Invalid checksum");return payload}}}var hasBase64Builtin=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")();var ASCII_WHITESPACE=/[\t\n\f\r ]/;var decodeBase64Builtin=(s,isUrl)=>{astr2("base64",s);const alphabet3=isUrl?"base64url":"base64";if(s.length>0&&ASCII_WHITESPACE.test(s))throw new Error("invalid base64");return Uint8Array.fromBase64(s,{alphabet:alphabet3,lastChunkHandling:"strict"})};var base64Fallback=freeze(()=>chain2(radix22(6),alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding2(6)));var base64urlFallback=freeze(()=>chain2(radix22(6),alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),padding2(6)));var base643=freeze(()=>hasBase64Builtin?{encode(b2){abytes5(b2);return b2.toBase64()},decode(s){return decodeBase64Builtin(s,false)}}:base64Fallback);var base64nopad=freeze(()=>chain2(radix22(6),alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")));var base64url3=freeze(()=>hasBase64Builtin?{encode(b2){abytes5(b2);return b2.toBase64({alphabet:"base64url"})},decode(s){return decodeBase64Builtin(s,true)}}:base64urlFallback);var base64urlnopad=freeze(()=>chain2(radix22(6),alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")));var B58_GROUP=656356768;var RADIX_BASE_N_MAX_LENGTH=65536;var BASE_N_MAX_BYTES=2048;var BASE_N_MAX_CHARS=4096;var radixBaseN=(BASE,GROUP)=>({encode:bytes=>{abytes5(bytes);const blen=bytes.length;if(blen===0)return new Uint8Array(0);if(blen>=RADIX_BASE_N_MAX_LENGTH)throw new Error("invalid length");let zeros=0;while(zeros<blen-1&&bytes[zeros]===0)zeros++;const nlimbs=Math.ceil(blen/2);const limbs=new Uint16Array(nlimbs);const odd=blen&1;if(odd)limbs[0]=bytes[0];for(let i=odd,j3=odd;i<blen;i+=2,j3++)limbs[j3]=bytes[i]<<8|bytes[i+1];const groups=[];let pos=0;while(pos<nlimbs){let carry2=0;for(let i=pos;i<nlimbs;i++){const cur=carry2*65536+limbs[i];const q2=Math.floor(cur/GROUP);carry2=cur-q2*GROUP;limbs[i]=q2;if(q2===0&&i===pos)pos++}groups.push(carry2)}const top=groups.length-1;let sig=top*5;for(let v=groups[top];;v=Math.floor(v/BASE)){sig++;if(v<BASE)break}const res=new Uint8Array(zeros+sig);let j2=res.length-1;for(let g=0;g<top;g++){let v=groups[g];for(let k2=0;k2<5;k2++){res[j2--]=v%BASE;v=Math.floor(v/BASE)}}for(let v=groups[top];j2>=zeros;v=Math.floor(v/BASE))res[j2--]=v%BASE;return res},decode:digits=>{abytes5(digits);const dlen=digits.length;if(dlen===0)return new Uint8Array(0);if(dlen>=RADIX_BASE_N_MAX_LENGTH)throw new Error("invalid length");let zeros=0;while(zeros<dlen-1&&digits[zeros]===0)zeros++;const limbs=new Uint16Array(Math.ceil(dlen*6/16)+1);let used=0;let i=0;let group=dlen%5||5;while(i<dlen){let gval=0;let factor=1;for(const end=i+group;i<end;i++){const d=digits[i];if(d>=BASE)throw new Error(`invalid integer: ${d}`);gval=gval*BASE+d;factor*=BASE}group=5;let carry2=gval;for(let k2=0;k2<used;k2++){const cur=limbs[k2]*factor+carry2;carry2=Math.floor(cur/65536);limbs[k2]=cur-carry2*65536}for(;carry2>0;carry2=Math.floor(carry2/65536))limbs[used++]=carry2%65536}const valueBytes=used===0?1:used*2-(limbs[used-1]<256?1:0);const res=new Uint8Array(zeros+valueBytes);let j2=res.length-1;for(let k2=0;k2<used;k2++){const limb=limbs[k2];res[j2--]=limb&255;if(j2>=zeros)res[j2--]=limb>>8}return res}});var genBaseN=(radix3,abc)=>{const letters=alphabet2(abc);return{encode(bytes){abytes5(bytes);if(bytes.length>BASE_N_MAX_BYTES)throw new Error("invalid length");return letters.encode(radix3.encode(bytes))},decode(str2){astr2("baseN.decode",str2);if(str2.length>BASE_N_MAX_CHARS)throw new Error("invalid length");return radix3.decode(letters.decode(str2))}}};var radix58=radixBaseN(58,B58_GROUP);var genBase58=abc=>genBaseN(radix58,abc);var base58=freeze(()=>genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"));var createBase58check=sha2566=>{afn2(sha2566);const _sha256=sha2566;return chain2(checksum4(4,data=>_sha256(_sha256(data))),base58)};function aarray(item,title,inner=()=>{}){if(!Array.isArray(item))throw new TypeError(`"${title}" expected array, got type=${typeof item}`);for(let i=0;i<item.length;i++)inner(item[i],`${title}[${i}]`);return item}var abytes6=(value,length,title)=>abytes4(value,length,title);var anumber7=anumber5;function astring(value,title=""){if(typeof value!=="string"){const prefix=title&&`"${title}" `;throw new TypeError(prefix+"expected string, got type="+typeof value)}return value}function aobject2(value,title="object"){if(value===null||typeof value!=="object"||Array.isArray(value))throw new TypeError(title==="object"?"expected valid options object":`"${title}" expected object, got type=${typeof value}`);return value}function afunction(value,title){if(typeof value!=="function")throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);return value}var bytesToHex3=bytesToHex2;var concatBytes2=(...arrays)=>concatBytes(...arrays);var hexToBytes3=hex3=>hexToBytes2(hex3);var isBytes7=isBytes5;var randomBytes4=bytesLength=>randomBytes3(bytesLength);var _0n3=BigInt(0);var _1n3=BigInt(1);var atitle2=title=>title?`"${title}" `:"";function abool(value,title=""){if(typeof value!=="boolean")throw new TypeError(atitle2(title)+"expected boolean, got type="+typeof value);return value}function abignumber(n){if(typeof n==="bigint"){if(!isPosBig(n))throw new RangeError("positive bigint expected, got "+n)}else anumber7(n);return n}function asafenumber(value,title=""){if(typeof value!=="number"){const prefix=title&&`"${title}" `;throw new TypeError(prefix+"expected number, got type="+typeof value)}if(!Number.isSafeInteger(value)){const prefix=title&&`"${title}" `;throw new RangeError(prefix+"expected safe integer, got "+value)}}function numberToHexUnpadded(num){const hex3=abignumber(num).toString(16);return hex3.length&1?"0"+hex3:hex3}function hexToNumber(hex3){if(typeof hex3!=="string")throw new TypeError("hex string expected, got "+typeof hex3);return hex3===""?_0n3:BigInt("0x"+hex3)}function bytesToNumberBE(bytes){return hexToNumber(bytesToHex2(bytes))}function bytesToNumberLE(bytes){return hexToNumber(bytesToHex2(copyBytes(abytes4(bytes)).reverse()))}function numberToBytesBE(n,len){anumber5(len);if(len===0)throw new Error("zero output length is invalid");n=abignumber(n);const expectedLen=len*2;const hex3=n.toString(16);if(hex3.length>expectedLen)throw new RangeError("number is too large");return hexToBytes2(hex3.padStart(expectedLen,"0"))}function numberToBytesLE(n,len){return numberToBytesBE(n,len).reverse()}function equalBytes2(a,b2){a=abytes6(a);b2=abytes6(b2);if(a.length!==b2.length)return false;let diff=0;for(let i=0;i<a.length;i++)diff|=a[i]^b2[i];return diff===0}function copyBytes(bytes){return Uint8Array.from(abytes6(bytes))}function isPosBig(n){return typeof n==="bigint"&&_0n3<=n}function inRange(n,min,max){return isPosBig(n)&&isPosBig(min)&&isPosBig(max)&&min<=n&&n<max}function aInRange(title,n,min,max){if(!inRange(n,min,max))throw new RangeError("expected valid "+title+": "+min+" <= n < "+max+", got "+n)}function bitLen(n){if(n<_0n3)throw new Error("expected non-negative bigint, got "+n);return n===_0n3?0:n.toString(2).length}var bitMask=n=>{asafenumber(n,"n");return(_1n3<<BigInt(n))-_1n3};function createHmacDrbg(hashLen,qByteLen,hmacFn){anumber5(hashLen,"hashLen");anumber5(qByteLen,"qByteLen");if(typeof hmacFn!=="function")throw new TypeError("hmacFn must be a function");const u8n=len=>new Uint8Array(len);const NULL=Uint8Array.of();const byte0=Uint8Array.of(0);const byte1=Uint8Array.of(1);const _maxDrbgIters=1e3;let v=u8n(hashLen);let k2=u8n(hashLen);let i=0;const reset=()=>{v.fill(1);k2.fill(0);i=0};const h=(...msgs)=>hmacFn(k2,concatBytes2(v,...msgs));const reseed=(seed=NULL)=>{k2=h(byte0,seed);v=h();if(seed.length===0)return;k2=h(byte1,seed);v=h()};const gen3=()=>{if(i++>=_maxDrbgIters)throw new Error("drbg: tried max amount of iterations");let len=0;const out=[];while(len<qByteLen){v=h();const sl=v.slice();out.push(sl);len+=v.length}return concatBytes2(...out)};const genUntil=(seed,pred)=>{reset();reseed(seed);let res=void 0;while((res=pred(gen3()))===void 0)reseed();reset();return res};return genUntil}function validateObject(object2,fields={},optFields={},title="object"){aobject2(object2,title);aobject2(fields,"fields");aobject2(optFields,"optFields");function checkField(fieldName,expectedType,isOpt){const label=title==="object"?`param "${String(fieldName)}"`:`"${title}.${String(fieldName)}"`;const val=object2[fieldName];if(!Object.hasOwn(object2,fieldName)&&(isOpt?val!==void 0:expectedType!=="function")){throw new TypeError(`${label} is invalid: expected own property`)}if(isOpt&&val===void 0)return;const current=typeof val;if(current!==expectedType||val===null)throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`)}const iter=(f,isOpt)=>Object.entries(f).forEach(([k2,v])=>checkField(k2,v,isOpt));iter(fields,false);iter(optFields,true)}var _0n4=BigInt(0);var _1n4=BigInt(1);var _2n3=BigInt(2);var _3n=BigInt(3);var _4n=BigInt(4);var _5n=BigInt(5);var _7n3=BigInt(7);var _8n=BigInt(8);var _9n=BigInt(9);var _15n=BigInt(15);var _16n=BigInt(16);var POW_WINDOWED_MIN=BigInt("0x10000000000000000");function mod(a,b2){if(b2<=_0n4)throw new Error("mod: expected positive modulus, got "+b2);const result=a%b2;return result>=_0n4?result:b2+result}function pow(num,power,modulo){if(modulo<=_1n4)throw new Error("pow: expected modulus > 1, got "+modulo);if(typeof power!=="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof power);if(power<_0n4)throw new Error("invalid exponent, negatives unsupported");if(power===_0n4)return _1n4;if(power===_1n4)return num;let d=num%modulo;if(d<_0n4)d+=modulo;if(power<POW_WINDOWED_MIN){let p2=_1n4;while(power>_0n4){if(power&_1n4)p2=p2*d%modulo;d=d*d%modulo;power>>=_1n4}return p2}const digits=[];while(power>_0n4){digits.push(Number(power&_15n));power>>=_4n}const table=new Array(16);table[0]=_1n4;table[1]=d;for(let i=2;i<16;i++)table[i]=table[i-1]*d%modulo;let p=table[digits[digits.length-1]];for(let w=digits.length-2;w>=0;w--){p=p*p%modulo;p=p*p%modulo;p=p*p%modulo;p=p*p%modulo;const digit=digits[w];if(digit!==0)p=p*table[digit]%modulo}return p}function pow2(x2,power,modulo){if(modulo<=_1n4)throw new Error("pow2: expected modulus > 1, got "+modulo);if(power<_0n4)throw new Error("pow2: expected non-negative exponent, got "+power);let res=x2;while(power-- >_0n4){res*=res;res%=modulo}return res}function invert(number4,modulo){if(number4===_0n4)throw new Error("invert: expected non-zero number");if(modulo<=_1n4)throw new Error("invert: expected modulus > 1, got "+modulo);let a=mod(number4,modulo);let b2=modulo;let x2=_0n4,u=_1n4;while(a!==_0n4){const q2=b2/a;const r=b2-a*q2;const m=x2-u*q2;b2=a,a=r,x2=u,u=m}const gcd2=b2;if(gcd2!==_1n4)throw new Error("invert: does not exist");return mod(x2,modulo)}function invertCt(a,prime){if(prime<=_1n4)throw new Error("invertCt: expected prime modulus > 1, got "+prime);const an=mod(a,prime);if(an===_0n4)throw new Error("invertCt: expected non-zero number");const inverse=pow(an,prime-_2n3,prime);if(mod(an*inverse,prime)!==_1n4)throw new Error("invertCt: does not exist");return inverse}function assertIsSquare(Fp,root,n){const F=Fp;if(!F.eql(F.sqr(root),n))throw new Error("Cannot find square root")}function aoddModulus(order,fnName){if((order&_1n4)===_0n4)throw new Error(fnName+": expected odd modulus, got "+order)}function sqrt3mod4(Fp,n){const F=Fp;const p1div4=(F.ORDER+_1n4)/_4n;const root=F.pow(n,p1div4);assertIsSquare(F,root,n);return root}function sqrt5mod8(Fp,n){const F=Fp;const p5div8=(F.ORDER-_5n)/_8n;const n2=F.mul(n,_2n3);const v=F.pow(n2,p5div8);const nv=F.mul(n,v);const i=F.mul(F.mul(nv,_2n3),v);const root=F.mul(nv,F.sub(i,F.ONE));assertIsSquare(F,root,n);return root}function sqrt9mod16(P2){const Fp_=Field(P2);const tn=tonelliShanks(P2);const c1=tn(Fp_,Fp_.neg(Fp_.ONE));const c2=tn(Fp_,c1);const c3=tn(Fp_,Fp_.neg(c1));const c4=(P2+_7n3)/_16n;return((Fp,n)=>{const F=Fp;let tv1=F.pow(n,c4);let tv2=F.mul(tv1,c1);const tv3=F.mul(tv1,c2);const tv4=F.mul(tv1,c3);const e1=F.eql(F.sqr(tv2),n);const e22=F.eql(F.sqr(tv3),n);tv1=F.cmov(tv1,tv2,e1);tv2=F.cmov(tv4,tv3,e22);const e32=F.eql(F.sqr(tv2),n);const root=F.cmov(tv1,tv2,e32);assertIsSquare(F,root,n);return root})}function tonelliShanks(P2){if(P2<_3n)throw new Error("sqrt is not defined for small field");aoddModulus(P2,"tonelliShanks");let Q=P2-_1n4;let S2=0;while(Q%_2n3===_0n4){Q/=_2n3;S2++}let Z2=_2n3;const _Fp=Field(P2);while(FpLegendre(_Fp,Z2)===1){if(Z2++>1e3)throw new Error("Cannot find square root: probably non-prime P")}if(S2===1)return sqrt3mod4;let cc=_Fp.pow(Z2,Q);const Q1div2=(Q+_1n4)/_2n3;return function tonelliSlow(Fp,n){const F=Fp;if(F.is0(n))return n;if(FpLegendre(F,n)!==1)throw new Error("Cannot find square root");let M=S2;let c=F.mul(F.ONE,cc);let t2=F.pow(n,Q);let R=F.pow(n,Q1div2);while(!F.eql(t2,F.ONE)){if(F.is0(t2))throw new Error("Cannot find square root: probably non-prime P");let i=1;let t_tmp=F.sqr(t2);while(!F.eql(t_tmp,F.ONE)){i++;t_tmp=F.sqr(t_tmp);if(i===M)throw new Error("Cannot find square root")}const exponent=_1n4<<BigInt(M-i-1);const b2=F.pow(c,exponent);M=i;c=F.sqr(b2);t2=F.mul(t2,c);R=F.mul(R,b2)}return R}}function FpSqrt(P2){aoddModulus(P2,"Fp.sqrt");if(P2%_4n===_3n)return sqrt3mod4;if(P2%_8n===_5n)return sqrt5mod8;if(P2%_16n===_9n)return sqrt9mod16(P2);return tonelliShanks(P2)}var FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(field){aobject2(field,"field");if(typeof field.ORDER!=="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof field.ORDER);asafenumber(field.BYTES,"BYTES");asafenumber(field.BITS,"BITS");for(const name of FIELD_FIELDS)afunction(field[name],"field."+name);if(field.BYTES<1||field.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(field.ORDER<=_1n4)throw new Error("invalid field: expected ORDER > 1, got "+field.ORDER);return field}function FpInvertBatch(Fp,nums,passZero=false){validateField(Fp);aarray(nums,"nums");abool(passZero,"passZero");const F=Fp;const inverted=new Array(nums.length).fill(passZero?F.ZERO:void 0);const multipliedAcc=nums.reduce((acc,num,i)=>{if(F.is0(num))return acc;inverted[i]=acc;return F.mul(acc,num)},F.ONE);const invertedAcc=F.inv(multipliedAcc);nums.reduceRight((acc,num,i)=>{if(F.is0(num))return acc;inverted[i]=F.mul(acc,inverted[i]);return F.mul(acc,num)},invertedAcc);return inverted}function FpLegendre(Fp,n){validateField(Fp);const F=Fp;aoddModulus(F.ORDER,"FpLegendre");const p1mod2=(F.ORDER-_1n4)/_2n3;const powered=F.pow(n,p1mod2);const yes=F.eql(powered,F.ONE);const zero=F.eql(powered,F.ZERO);const no=F.eql(powered,F.neg(F.ONE));if(!yes&&!zero&&!no)throw new Error("invalid Legendre symbol result");return yes?1:zero?0:-1}function nLength(n,nBitLength){if(nBitLength!==void 0)anumber7(nBitLength);if(n<=_0n4)throw new Error("invalid n length: expected positive n, got "+n);if(nBitLength!==void 0&&nBitLength<1)throw new Error("invalid n length: expected positive bit length, got "+nBitLength);const bits=bitLen(n);if(nBitLength!==void 0&&nBitLength<bits)throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);const _nBitLength=nBitLength!==void 0?nBitLength:bits;const nByteLength=Math.ceil(_nBitLength/8);return{nBitLength:_nBitLength,nByteLength}}var FIELD_SQRT=new WeakMap;var _Field=class{ORDER;BITS;BYTES;isLE;ZERO=_0n4;ONE=_1n4;_lengths;_mod;constructor(ORDER,opts={}){if(ORDER<=_1n4)throw new Error("invalid field: expected ORDER > 1, got "+ORDER);let _nbitLength=void 0;this.isLE=false;if(opts!=null&&typeof opts==="object"){if(typeof opts.BITS==="number")_nbitLength=opts.BITS;if(typeof opts.sqrt==="function")Object.defineProperty(this,"sqrt",{value:opts.sqrt,enumerable:true});if(typeof opts.isLE==="boolean")this.isLE=opts.isLE;if(opts.allowedLengths)this._lengths=Object.freeze(opts.allowedLengths.slice());if(typeof opts.modFromBytes==="boolean")this._mod=opts.modFromBytes}const{nBitLength,nByteLength}=nLength(ORDER,_nbitLength);if(nByteLength>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=ORDER;this.BITS=nBitLength;this.BYTES=nByteLength;Object.freeze(this)}create(num){return mod(num,this.ORDER)}isValid(num){if(typeof num!=="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof num);return _0n4<=num&&num<this.ORDER}is0(num){return num===_0n4}isValidNot0(num){return!this.is0(num)&&this.isValid(num)}isOdd(num){return(num&_1n4)===_1n4}neg(num){return mod(-num,this.ORDER)}eql(lhs,rhs){return lhs===rhs}sqr(num){return mod(num*num,this.ORDER)}add(lhs,rhs){return mod(lhs+rhs,this.ORDER)}sub(lhs,rhs){return mod(lhs-rhs,this.ORDER)}mul(lhs,rhs){return mod(lhs*rhs,this.ORDER)}pow(num,power){return pow(num,power,this.ORDER)}div(lhs,rhs){return mod(lhs*invert(rhs,this.ORDER),this.ORDER)}sqrN(num){return num*num}addN(lhs,rhs){return lhs+rhs}subN(lhs,rhs){return lhs-rhs}mulN(lhs,rhs){return lhs*rhs}inv(num){return invert(num,this.ORDER)}sqrt(num){let sqrt=FIELD_SQRT.get(this);if(!sqrt)FIELD_SQRT.set(this,sqrt=FpSqrt(this.ORDER));return sqrt(this,num)}toBytes(num){return this.isLE?numberToBytesLE(num,this.BYTES):numberToBytesBE(num,this.BYTES)}fromBytes(bytes,skipValidation=false){abytes6(bytes);const{_lengths:allowedLengths,BYTES,isLE:isLE3,ORDER,_mod:modFromBytes}=this;if(allowedLengths){if(bytes.length<1||!allowedLengths.includes(bytes.length)||bytes.length>BYTES){throw new Error("Field.fromBytes: expected "+allowedLengths+" bytes, got "+bytes.length)}const padded=new Uint8Array(BYTES);padded.set(bytes,isLE3?0:padded.length-bytes.length);bytes=padded}if(bytes.length!==BYTES)throw new Error("Field.fromBytes: expected "+BYTES+" bytes, got "+bytes.length);let scalar=isLE3?bytesToNumberLE(bytes):bytesToNumberBE(bytes);if(modFromBytes)scalar=mod(scalar,ORDER);if(!skipValidation){if(!this.isValid(scalar))throw new Error("invalid field element: outside of range 0..ORDER")}return scalar}invertBatch(lst){return FpInvertBatch(this,lst,true)}cmov(a,b2,condition){abool(condition,"condition");return condition?b2:a}};function Field(ORDER,opts={}){Object.freeze(_Field.prototype);return new _Field(ORDER,opts)}function getFieldBytesLength(fieldOrder){if(typeof fieldOrder!=="bigint")throw new Error("field order must be bigint");if(fieldOrder<=_1n4)throw new Error("field order must be greater than 1");const bitLength=bitLen(fieldOrder-_1n4);return Math.ceil(bitLength/8)}function getMinHashLength(fieldOrder){const length=getFieldBytesLength(fieldOrder);return length+Math.ceil(length/2)}function mapHashToField(key,fieldOrder,isLE3=false){abytes6(key);const len=key.length;const fieldLen=getFieldBytesLength(fieldOrder);const minLen=Math.max(getMinHashLength(fieldOrder),16);if(len<minLen||len>1024)throw new Error("expected "+minLen+"-1024 bytes of input, got "+len);const num=isLE3?bytesToNumberLE(key):bytesToNumberBE(key);const reduced=mod(num,fieldOrder-_1n4)+_1n4;return isLE3?numberToBytesLE(reduced,fieldLen):numberToBytesBE(reduced,fieldLen)}var _0n5=BigInt(0);var _1n5=BigInt(1);var _4n2=BigInt(4);var BLIND_BYTES=16;var BLIND_BITS=128;var FW_WINDOW=5;var TABLE_BYTES_MAX=(()=>2**31)();function validatePointCons(Point2){const pc=Point2;if(typeof pc!=="function")throw new TypeError('"Point" expected constructor, got type='+typeof Point2);afunction(pc.fromAffine,"Point.fromAffine");afunction(pc.fromBytes,"Point.fromBytes");afunction(pc.fromHex,"Point.fromHex");aobject2(pc.BASE,"Point.BASE");aobject2(pc.ZERO,"Point.ZERO");validateField(pc.Fp);validateField(pc.Fn)}function normalizeZ(c,points){validatePointCons(c);validateMSMPoints(points,c);const invertedZs=FpInvertBatch(c.Fp,points.map(p=>p.Z));return points.map((p,i)=>c.fromAffine(p.toAffine(invertedZs[i])))}function validateW(W2,bits,min=1){if(!Number.isSafeInteger(W2)||W2<min||W2>bits)throw new Error("invalid window size, expected ["+min+".."+bits+"], got W="+W2)}function validateTableBytes(numPoints,fpBytes){const bytes=numPoints*(4*fpBytes+128);if(bytes>TABLE_BYTES_MAX)throw new Error("invalid window size: table would need ~"+Math.ceil(bytes/2**20)+" MiB, max "+TABLE_BYTES_MAX/2**20+" MiB")}function probeRandomBytes(randomBytes5,length){if(randomBytes5===void 0)return void 0;afunction(randomBytes5,"randomBytes");try{const probe=randomBytes5(length);if(!isBytes7(probe)||probe.length!==length)return void 0}catch{return void 0}return randomBytes5}function validateMSMPoints(points,c){aarray(points,"points");points.forEach((p,i)=>{if(!(p instanceof c))throw new Error("invalid point at index "+i)})}function validateMSMScalars(scalars,field,maxScalar){if(!Array.isArray(scalars))throw new Error("array of scalars expected");scalars.forEach((s,i)=>{const ok=maxScalar===void 0?field.isValid(s):isPosBig(s)&&s<maxScalar;if(!ok)throw new Error("invalid scalar at index "+i)})}var pointWindowSizes=new WeakMap;function getWindowSize(P2){return pointWindowSizes.get(P2)||1}function oddMultiples(p,size4){const dbl=p.double();const t2=[p];for(let j2=1;j2<size4;j2++)t2.push(t2[j2-1].add(dbl));return t2}function wnafDigits(n,W2){const size4=2**W2;const half=size4/2;const mask=BigInt(size4-1);const d=[];while(n>_0n5){let w=0;if(n&_1n5){w=Number(n&mask);if(w>=half)w-=size4;n-=BigInt(w)}d.push(w);n>>=_1n5}return d}function signedWindowDigits(n,W2,windows){const size4=2**W2;const half=size4/2;const mask=BigInt(size4-1);const shiftBy=BigInt(W2);const d=[];for(let w=0;w<windows;w++){let v=Number(n&mask);n>>=shiftBy;if(v>half){v-=size4;n+=_1n5}d.push(v)}if(n!==_0n5)throw new Error("invalid wnaf");return d}function wnafWalk(zero,tables,digits){let max=0;for(const d of digits)max=Math.max(max,d.length);let acc=zero;for(let bit=max-1;bit>=0;bit--){if(bit!==max-1)acc=acc.double();for(let i=0;i<digits.length;i++){const w=digits[i][bit];if(w){const item=tables[i][Math.abs(w)-1>>1];acc=acc.add(w<0?item.negate():item)}}}return acc}var ScalarMultiplier=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(Point2,randomBytes5){validatePointCons(Point2);this.randomBytes=probeRandomBytes(randomBytes5,BLIND_BYTES);this.Point=Point2;this.BASE=Point2.BASE;this.ZERO=Point2.ZERO;this.bits=Point2.Fn.BITS}buildWnafTable(point,W2,bits){const windows=Math.ceil(bits/W2)+1;const half=2**(W2-1);const comp=[];let base3=point;for(let w=0;w<windows;w++){let acc=base3;for(let i=0;i<half;i++){comp.push(acc);acc=acc.add(base3)}base3=comp[comp.length-1].double()}return{W:W2,bits,windows,comp}}wnafCachedCT(precomputes,n){const{W:W2,windows,comp}=precomputes;const half=2**(W2-1);const digits=signedWindowDigits(n,W2,windows);let p=this.ZERO;let f=this.BASE;for(let w=0;w<windows;w++){const digit=digits[w];const start=w*half;const idx=Math.abs(digit)-1;let sel=comp[start];for(let i=1;i<half;i++)sel=i===idx?comp[start+i]:sel;const neg=sel.negate();if(digit===0)f=f.add(comp[start]);else p=p.add(digit<0?neg:sel)}return{p,f}}getWnafPrecomputes(W2,point,bits,transform2){let entries=this.wnafPrecomputes.get(point);let comp=entries?.find(entry=>entry.W===W2&&entry.bits===bits);if(!comp){comp=this.buildWnafTable(point,W2,bits);if(typeof transform2==="function")comp={...comp,comp:transform2(comp.comp)};if(!entries){entries=[];this.wnafPrecomputes.set(point,entries)}entries.push(comp)}return comp}assertPoint(point){if(!(point instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof point)}validateMulInput(point,scalar){this.assertPoint(point);if(!inRange(scalar,_1n5,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(point,n,bits,transform2){const W2=getWindowSize(point);if(W2===1)return this.fixedWindowCT(point,n,bits);return this.wnafCachedCT(this.getWnafPrecomputes(W2,point,bits,transform2),n)}mulCT(point,scalar,transform2){this.validateMulInput(point,scalar);return this.runCT(point,scalar,this.bits,transform2)}mulCTBlinded(point,scalar,transform2){this.validateMulInput(point,scalar);if(this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const bits=this.Point.Fn.BITS+BLIND_BITS;const blind=this.randomBytes(BLIND_BYTES);if(!isBytes7(blind)||blind.length!==BLIND_BYTES)throw new Error("randomBytes returned invalid byte array");blind[0]=blind[0]&63|128;const n=scalar+bytesToNumberBE(blind)*this.Point.Fn.ORDER;return this.runCT(point,n,bits,transform2)}fixedWindowCT(point,n,bits){const W2=FW_WINDOW;const size4=1<<W2;const mask=bitMask(W2);const table=new Array(size4);table[0]=this.ZERO;for(let i=1;i<size4;i++)table[i]=table[i-1].add(point);const windows=Math.ceil(bits/W2);let acc=this.ZERO;for(let window=windows-1;window>=0;window--){if(window!==windows-1)for(let d=0;d<W2;d++)acc=acc.double();const digit=Number(n>>BigInt(window*W2)&mask);let sel=table[0];for(let i=1;i<size4;i++)sel=i===digit?table[i]:sel;acc=acc.add(sel)}return{p:acc,f:acc}}shouldBlind(point,cofactor){if(this.randomBytes===void 0)return false;if(cofactor===_1n5)return true;if(point!==this.BASE)return false;if(this.baseCanBeBlinded===void 0)this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0();return this.baseCanBeBlinded}mulSecret(point,scalar,cofactor,transform2){return this.shouldBlind(point,cofactor)?this.mulCTBlinded(point,scalar,transform2):this.mulCT(point,scalar,transform2)}mulUnsafe(point,scalar,transform2){this.assertPoint(point);if(!isPosBig(scalar))throw new Error("invalid scalar");const W2=getWindowSize(point);if(W2===1||scalar>=this.Point.Fn.ORDER)return mulAddUnsafe(this.Point,[point],[scalar],true);const precomputes=this.getWnafPrecomputes(W2,point,this.bits,transform2);return this.wnafCachedCT(precomputes,scalar).p}setWindowSize(point,W2){this.assertPoint(point);validateW(W2,this.bits);const windows=Math.ceil((this.bits+BLIND_BITS)/W2)+1;validateTableBytes(windows*2**(W2-1),this.Point.Fp.BYTES);pointWindowSizes.set(point,W2);this.wnafPrecomputes.delete(point)}hasWindowSize(point){return getWindowSize(point)!==1}};function mulAddUnsafe(c,points,scalars,allowOversized=false){validatePointCons(c);validateMSMPoints(points,c);abool(allowOversized,"allowOversized");validateMSMScalars(scalars,c.Fn,allowOversized?c.Fn.ORDER**_4n2:void 0);if(points.length!==scalars.length)throw new Error("arrays of points and scalars must have equal length");const tables=points.map(p=>oddMultiples(p,4));const digits=scalars.map(n=>wnafDigits(n,4));return wnafWalk(c.ZERO,tables,digits)}function createField(order,field,isLE3){if(field){if(field.ORDER!==order)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");validateField(field);return field}else{return Field(order,{isLE:isLE3})}}function createCurveFields(type,CURVE,curveOpts={},FpFnLE){if(type!=="weierstrass"&&type!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(FpFnLE===void 0)FpFnLE=type==="edwards";if(!CURVE||typeof CURVE!=="object")throw new Error(`expected valid ${type} CURVE object`);validateObject(curveOpts);for(const p of["p","n","h"]){const val=CURVE[p];if(!(isPosBig(val)&&val!==_0n5))throw new Error(`CURVE.${p} must be positive bigint`)}const Fp=createField(CURVE.p,curveOpts.Fp,FpFnLE);const Fn2=createField(CURVE.n,curveOpts.Fn,FpFnLE);const _b=type==="weierstrass"?"b":"d";const params=["Gx","Gy","a",_b];for(const p of params){if(!Fp.isValid(CURVE[p]))throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`)}CURVE=Object.freeze(Object.assign({},CURVE));return{CURVE,Fp,Fn:Fn2}}function createKeygen(randomSecretKey,getPublicKey){return function keygen(seed){const secretKey=randomSecretKey(seed);return{secretKey,publicKey:getPublicKey(secretKey)}}}var _HMAC=class{oHash;iHash;blockLen;outputLen;canXOF=false;finished=false;destroyed=false;constructor(hash3,key){ahash2(hash3);abytes4(key,void 0,"key");this.iHash=hash3.create();if(typeof this.iHash.update!=="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen;this.outputLen=this.iHash.outputLen;const blockLen=this.blockLen;const pad4=new Uint8Array(blockLen);pad4.set(key.length>blockLen?hash3.create().update(key).digest():key);for(let i=0;i<pad4.length;i++)pad4[i]^=54;this.iHash.update(pad4);this.oHash=hash3.create();for(let i=0;i<pad4.length;i++)pad4[i]^=54^92;this.oHash.update(pad4);clean4(pad4)}update(buf){aexists4(this);this.iHash.update(buf);return this}digestInto(out){aexists4(this);aoutput4(out,this);this.finished=true;const buf=out.subarray(0,this.outputLen);this.iHash.digestInto(buf);this.oHash.update(buf);this.oHash.digestInto(buf);this.destroy()}digest(){const out=new Uint8Array(this.oHash.outputLen);this.digestInto(out);return out}_cloneInto(to){to||=Object.create(Object.getPrototypeOf(this),{});const{oHash,iHash,finished,destroyed,blockLen,outputLen,canXOF}=this;to=to;to.finished=finished;to.destroyed=destroyed;to.blockLen=blockLen;to.outputLen=outputLen;to.canXOF=canXOF;to.oHash=oHash._cloneInto(to.oHash);to.iHash=iHash._cloneInto(to.iHash);return to}clone(){return this._cloneInto()}destroy(){this.destroyed=true;this.oHash.destroy();this.iHash.destroy()}};var hmac2=(()=>{const hmac_=((hash3,key,message2)=>new _HMAC(hash3,key).update(message2).digest());hmac_.create=(hash3,key)=>new _HMAC(hash3,key);return hmac_})();var _0n6=BigInt(0);var DERErr=class extends Error{constructor(m=""){super(m)}};var _DER={Err:DERErr,_tlv:{encode:(tag,data)=>{const{Err:E2}=_DER;asafenumber(tag,"tag");if(tag<0||tag>255)throw new E2("tlv.encode: wrong tag");astring(data,"data");if(data.length&1)throw new E2("tlv.encode: unpadded data");const dataLen=data.length/2;const len=numberToHexUnpadded(dataLen);if(len.length/2&128)throw new E2("tlv.encode: long form length too big");const lenLen=dataLen>127?numberToHexUnpadded(len.length/2|128):"";const t2=numberToHexUnpadded(tag);return t2+lenLen+len+data},decode(tag,data){const{Err:E2}=_DER;data=abytes6(data,void 0,"DER data");let pos=0;if(tag<0||tag>255)throw new E2("tlv.decode: wrong tag");if(data.length<2||data[pos++]!==tag)throw new E2("tlv.decode: wrong tlv");const first=data[pos++];const isLong=!!(first&128);let length=0;if(!isLong)length=first;else{const lenLen=first&127;if(!lenLen)throw new E2("tlv.decode(long): indefinite length not supported");if(lenLen>4)throw new E2("tlv.decode(long): byte length is too big");const lengthBytes=data.subarray(pos,pos+lenLen);if(lengthBytes.length!==lenLen)throw new E2("tlv.decode: length bytes not complete");if(lengthBytes[0]===0)throw new E2("tlv.decode(long): zero leftmost byte");for(const b2 of lengthBytes)length=length<<8|b2;pos+=lenLen;if(length<128)throw new E2("tlv.decode(long): not minimal encoding")}const v=data.subarray(pos,pos+length);if(v.length!==length)throw new E2("tlv.decode: wrong value length");return{v,l:data.subarray(pos+length)}}},_int:{encode(num){const{Err:E2}=_DER;abignumber(num);if(num<_0n6)throw new E2("integer: negative integers are not allowed");let hex3=numberToHexUnpadded(num);if(Number.parseInt(hex3[0],16)&8)hex3="00"+hex3;if(hex3.length&1)throw new E2("unexpected DER parsing assertion: unpadded hex");return hex3},decode(data){const{Err:E2}=_DER;if(data.length<1)throw new E2("invalid signature integer: empty");if(data[0]&128)throw new E2("invalid signature integer: negative");if(data.length>1&&data[0]===0&&!(data[1]&128))throw new E2("invalid signature integer: unnecessary leading zero");return bytesToNumberBE(data)}},toSig(bytes,maxScalarBytes){const{Err:E2,_int:int2,_tlv:tlv}=_DER;if(maxScalarBytes!==void 0){asafenumber(maxScalarBytes,"maxScalarBytes");if(maxScalarBytes<1)throw new E2("invalid signature: maxScalarBytes must be positive")}const data=abytes6(bytes,void 0,"signature");const{v:seqBytes,l:seqLeftBytes}=tlv.decode(48,data);if(seqLeftBytes.length)throw new E2("invalid signature: left bytes after parsing");const{v:rBytes,l:rLeftBytes}=tlv.decode(2,seqBytes);const{v:sBytes,l:sLeftBytes}=tlv.decode(2,rLeftBytes);if(sLeftBytes.length)throw new E2("invalid signature: left bytes after parsing");if(maxScalarBytes!==void 0&&(rBytes.length>maxScalarBytes||sBytes.length>maxScalarBytes))throw new E2("invalid signature: integer too large");return{r:int2.decode(rBytes),s:int2.decode(sBytes)}},hexFromSig(sig){const{_tlv:tlv,_int:int2}=_DER;validateObject(sig,{r:"bigint",s:"bigint"},{},"sig");const rs=tlv.encode(2,int2.encode(sig.r));const ss=tlv.encode(2,int2.encode(sig.s));const seq=rs+ss;return tlv.encode(48,seq)}};var DER=(()=>{Object.freeze(_DER._tlv);Object.freeze(_DER._int);return Object.freeze(_DER)})();var divNearest=(num,den)=>(num+(num>=0?den:-den)/_2n4)/den;function _splitEndoScalar(k2,basis,n){aInRange("scalar",k2,_0n7,n);const[[a1,b1],[a2,b2]]=basis;const c1=divNearest(b2*k2,n);const c2=divNearest(-b1*k2,n);let k1=k2-c1*a1-c2*a2;let k22=-c1*b1-c2*b2;const k1neg=k1<_0n7;const k2neg=k22<_0n7;if(k1neg)k1=-k1;if(k2neg)k22=-k22;const MAX_NUM=bitMask(Math.ceil(bitLen(n)/2))+_1n6;if(k1<_0n7||k1>=MAX_NUM||k22<_0n7||k22>=MAX_NUM){throw new Error("splitScalar (endomorphism): failed for k")}return{k1neg,k1,k2neg,k2:k22}}function validateSigFormat(format){if(!["compact","recovered","der"].includes(format))throw new Error('Signature format must be "compact", "recovered", or "der"');return format}function validateSigOpts(opts,def){validateObject(opts);const optsn={};for(let optName of Object.keys(def)){optsn[optName]=opts[optName]===void 0?def[optName]:opts[optName]}abool(optsn.lowS,"lowS");abool(optsn.prehash,"prehash");if(optsn.format!==void 0)validateSigFormat(optsn.format);return optsn}var _0n7=BigInt(0);var _1n6=BigInt(1);var _2n4=BigInt(2);var _3n2=BigInt(3);var _4n3=BigInt(4);function weierstrass(params,extraOpts={}){const validated=createCurveFields("weierstrass",params,extraOpts);const Fp=validated.Fp;const Fn2=validated.Fn;let CURVE=validated.CURVE;const{h:cofactor,n:CURVE_ORDER}=CURVE;validateObject(extraOpts,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});const{endo:endoOpts,allowInfinityPoint,clearCofactor,isTorsionFree,fromBytes:fromBytes3,toBytes:toBytes6}=extraOpts;const randomBytes5=extraOpts.randomBytes===void 0?randomBytes4:extraOpts.randomBytes;if(endoOpts){if(!Fp.is0(CURVE.a)||typeof endoOpts.beta!=="bigint"||!Array.isArray(endoOpts.basises)){throw new Error('invalid endo: expected "beta": bigint and "basises": array')}}const endo=endoOpts?{beta:endoOpts.beta,basises:endoOpts.basises.map(basis=>[...basis])}:void 0;const lengths=getWLengths(Fp,Fn2);function assertCompressionIsSupported(){if(!Fp.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function pointToBytes(_c,point,isCompressed){if(point.is0()){if(!allowInfinityPoint)throw new Error("bad point: ZERO");return Uint8Array.of(0)}const{x:x2,y}=point.toAffine();const bx=Fp.toBytes(x2);abool(isCompressed,"isCompressed");if(isCompressed){assertCompressionIsSupported();const hasEvenY=!Fp.isOdd(y);return concatBytes2(pprefix(hasEvenY),bx)}else{return concatBytes2(Uint8Array.of(4),bx,Fp.toBytes(y))}}function pointFromBytes(bytes){abytes6(bytes,void 0,"Point");const{publicKey:comp,publicKeyUncompressed:uncomp}=lengths;const length=bytes.length;const head=bytes[0];const tail=bytes.subarray(1);if(allowInfinityPoint&&length===1&&head===0)return{x:Fp.ZERO,y:Fp.ZERO};if(length===comp&&(head===2||head===3)){const x2=Fp.fromBytes(tail);if(!Fp.isValid(x2))throw new Error("bad point: is not on curve, wrong x");const y2=weierstrassEquation(x2);let y;try{y=Fp.sqrt(y2)}catch(sqrtError){const err=sqrtError instanceof Error?": "+sqrtError.message:"";throw new Error("bad point: is not on curve, sqrt error"+err)}assertCompressionIsSupported();const evenY=Fp.isOdd(y);const evenH=(head&1)===1;if(evenH!==evenY)y=Fp.neg(y);return{x:x2,y}}else if(length===uncomp&&head===4){const L2=Fp.BYTES;const x2=Fp.fromBytes(tail.subarray(0,L2));const y=Fp.fromBytes(tail.subarray(L2,L2*2));if(!isValidXY(x2,y))throw new Error("bad point: is not on curve");return{x:x2,y}}else{throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`)}}const encodePoint=toBytes6===void 0?pointToBytes:toBytes6;const decodePoint=fromBytes3===void 0?pointFromBytes:fromBytes3;const b3=Fp.mul(CURVE.b,_3n2);const mulA=Fp.is0(CURVE.a)?_=>Fp.ZERO:x2=>Fp.mul(CURVE.a,x2);function weierstrassEquation(x2){const x22=Fp.sqr(x2);const x3=Fp.mul(x22,x2);return Fp.add(Fp.add(x3,Fp.mul(x2,CURVE.a)),CURVE.b)}function isValidXY(x2,y){const left=Fp.sqr(y);const right=weierstrassEquation(x2);return Fp.eql(left,right)}if(!isValidXY(CURVE.Gx,CURVE.Gy))throw new Error("bad curve params: generator point");const _4a3=Fp.mul(Fp.pow(CURVE.a,_3n2),_4n3);const _27b2=Fp.mul(Fp.sqr(CURVE.b),BigInt(27));if(Fp.is0(Fp.add(_4a3,_27b2)))throw new Error("bad curve params: a or b");function acoord(title,n,banZero=false){if(!Fp.isValid(n)||banZero&&Fp.is0(n))throw new Error(`bad point coordinate ${title}`);return typeof n==="object"&&n!==null?Fp.create(n):n}function aprjpoint(other){if(!(other instanceof Point2))throw new Error("Weierstrass Point expected")}function splitEndoScalarN(k2){if(!endo||!endo.basises)throw new Error("no endo");return _splitEndoScalar(k2,endo.basises,Fn2.ORDER)}function pushWnafPair(points,scalars,p,k2){if(!Fn2.isValid(k2))throw new RangeError("invalid scalar: out of range");if(endo){const{k1neg,k1,k2neg,k2:k22}=splitEndoScalarN(k2);const psi=new Point2(Fp.mul(p.X,endo.beta),p.Y,p.Z);points.push(k1neg?p.negate():p,k2neg?psi.negate():psi);scalars.push(k1,k22)}else{points.push(p);scalars.push(k2)}}const validityCache=new WeakSet;class Point2{static BASE=new Point2(CURVE.Gx,CURVE.Gy,Fp.ONE);static ZERO=new Point2(Fp.ZERO,Fp.ONE,Fp.ZERO);static Fp=Fp;static Fn=Fn2;X;Y;Z;constructor(X2,Y2,Z2){this.X=acoord("x",X2);this.Y=acoord("y",Y2,true);this.Z=acoord("z",Z2);Object.freeze(this)}static CURVE(){return CURVE}static fromAffine(p){const{x:x2,y}=p||{};if(!p||!Fp.isValid(x2)||!Fp.isValid(y))throw new Error("invalid affine point");if(p instanceof Point2)throw new Error("projective point not allowed");if(Fp.is0(x2)&&Fp.is0(y))return Point2.ZERO;return new Point2(x2,y,Fp.ONE)}static fromBytes(bytes){const P2=Point2.fromAffine(decodePoint(abytes6(bytes,void 0,"point")));P2.assertValidity();return P2}static fromHex(hex3){return Point2.fromBytes(hexToBytes3(hex3))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(windowSize=6,isLazy=true){wnaf.setWindowSize(this,windowSize);if(!isLazy)this.multiply(_3n2);return this}assertValidity(){const p=this;if(p.is0()){if(allowInfinityPoint&&Fp.is0(p.X)&&Fp.eql(p.Y,Fp.ONE)&&Fp.is0(p.Z))return;throw new Error("bad point: ZERO")}if(validityCache.has(p))return;const{x:x2,y}=p.toAffine();if(!Fp.isValid(x2)||!Fp.isValid(y))throw new Error("bad point: x or y not field elements");if(!isValidXY(x2,y))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");validityCache.add(p)}hasEvenY(){const{y}=this.toAffine();if(!Fp.isOdd)throw new Error("Field doesn't support isOdd");return!Fp.isOdd(y)}equals(other){aprjpoint(other);const{X:X1,Y:Y1,Z:Z1}=this;const{X:X2,Y:Y2,Z:Z2}=other;const U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1));const U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point2(this.X,Fp.neg(this.Y),this.Z)}double(){const{X:X1,Y:Y1,Z:Z1}=this;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;let t0=Fp.mul(X1,X1);let t1=Fp.mul(Y1,Y1);let t2=Fp.mul(Z1,Z1);let t3=Fp.mul(X1,Y1);t3=Fp.add(t3,t3);Z3=Fp.mul(X1,Z1);Z3=Fp.add(Z3,Z3);X3=mulA(Z3);Y3=Fp.mul(b3,t2);Y3=Fp.add(X3,Y3);X3=Fp.sub(t1,Y3);Y3=Fp.add(t1,Y3);Y3=Fp.mul(X3,Y3);X3=Fp.mul(t3,X3);Z3=Fp.mul(b3,Z3);t2=mulA(t2);t3=Fp.sub(t0,t2);t3=mulA(t3);t3=Fp.add(t3,Z3);Z3=Fp.add(t0,t0);t0=Fp.add(Z3,t0);t0=Fp.add(t0,t2);t0=Fp.mul(t0,t3);Y3=Fp.add(Y3,t0);t2=Fp.mul(Y1,Z1);t2=Fp.add(t2,t2);t0=Fp.mul(t2,t3);X3=Fp.sub(X3,t0);Z3=Fp.mul(t2,t1);Z3=Fp.add(Z3,Z3);Z3=Fp.add(Z3,Z3);return new Point2(X3,Y3,Z3)}add(other){aprjpoint(other);const{X:X1,Y:Y1,Z:Z1}=this;const{X:X2,Y:Y2,Z:Z2}=other;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;let t0=Fp.mul(X1,X2);let t1=Fp.mul(Y1,Y2);let t2=Fp.mul(Z1,Z2);let t3=Fp.add(X1,Y1);let t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4);t4=Fp.add(t0,t1);t3=Fp.sub(t3,t4);t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);t4=Fp.mul(t4,t5);t5=Fp.add(t0,t2);t4=Fp.sub(t4,t5);t5=Fp.add(Y1,Z1);X3=Fp.add(Y2,Z2);t5=Fp.mul(t5,X3);X3=Fp.add(t1,t2);t5=Fp.sub(t5,X3);Z3=mulA(t4);X3=Fp.mul(b3,t2);Z3=Fp.add(X3,Z3);X3=Fp.sub(t1,Z3);Z3=Fp.add(t1,Z3);Y3=Fp.mul(X3,Z3);t1=Fp.add(t0,t0);t1=Fp.add(t1,t0);t2=mulA(t2);t4=Fp.mul(b3,t4);t1=Fp.add(t1,t2);t2=Fp.sub(t0,t2);t2=mulA(t2);t4=Fp.add(t4,t2);t0=Fp.mul(t1,t4);Y3=Fp.add(Y3,t0);t0=Fp.mul(t5,t4);X3=Fp.mul(t3,X3);X3=Fp.sub(X3,t0);t0=Fp.mul(t3,t1);Z3=Fp.mul(t5,Z3);Z3=Fp.add(Z3,t0);return new Point2(X3,Y3,Z3)}subtract(other){aprjpoint(other);return this.add(other.negate())}is0(){return this.equals(Point2.ZERO)}multiply(scalar){if(!Fn2.isValidNot0(scalar))throw new RangeError("invalid scalar: out of range");const{p,f}=wnaf.mulSecret(this,scalar,cofactor,normalize2);return normalize2([p,f])[0]}multiplyUnsafe(scalar){const p=this;const sc=scalar;if(!Fn2.isValid(sc))throw new RangeError("invalid scalar: out of range");if(sc===_0n7||p.is0())return Point2.ZERO;if(sc===_1n6)return p;if(wnaf.hasWindowSize(this))return wnaf.mulUnsafe(p,sc,normalize2);const points=[];const scalars=[];pushWnafPair(points,scalars,p,sc);return mulAddUnsafe(Point2,points,scalars)}mulAddUnsafe(a,other,b2){aprjpoint(other);const points=[];const scalars=[];pushWnafPair(points,scalars,this,a);pushWnafPair(points,scalars,other,b2);return mulAddUnsafe(Point2,points,scalars)}toAffine(invertedZ){const p=this;let iz=invertedZ;if(iz!=null&&!Fp.isValid(iz))throw new RangeError('"invertedZ" expected valid field element');const{X:X2,Y:Y2,Z:Z2}=p;if(Fp.eql(Z2,Fp.ONE))return{x:X2,y:Y2};const is0=p.is0();if(iz==null)iz=is0?Fp.ONE:Fp.inv(Z2);const x2=Fp.mul(X2,iz);const y=Fp.mul(Y2,iz);const zz=Fp.mul(Z2,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw new Error("invZ was invalid");return{x:x2,y}}isTorsionFree(){if(cofactor===_1n6)return true;if(isTorsionFree)return isTorsionFree(Point2,this);return wnaf.mulUnsafe(this,CURVE_ORDER).is0()}clearCofactor(){if(cofactor===_1n6)return this;if(clearCofactor)return clearCofactor(Point2,this);return this.multiplyUnsafe(cofactor)}isSmallOrder(){if(cofactor===_1n6)return this.is0();return this.clearCofactor().is0()}toBytes(isCompressed=true){abool(isCompressed,"isCompressed");this.assertValidity();return encodePoint(Point2,this,isCompressed)}toHex(isCompressed=true){return bytesToHex3(this.toBytes(isCompressed))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const normalize2=points=>normalizeZ(Point2,points);const wnaf=new ScalarMultiplier(Point2,randomBytes5);if(wnaf.bits>=6)Point2.BASE.precompute(6);Object.freeze(Point2.prototype);Object.freeze(Point2);return Point2}function pprefix(hasEvenY){return Uint8Array.of(hasEvenY?2:3)}function getWLengths(Fp,Fn2){return{secretKey:Fn2.BYTES,publicKey:1+Fp.BYTES,publicKeyUncompressed:1+2*Fp.BYTES,publicKeyHasPrefix:true,signature:2*Fn2.BYTES}}function ecdh(Point2,ecdhOpts={}){validatePointCons(Point2);const{Fn:Fn2}=Point2;const randomBytes_=ecdhOpts.randomBytes===void 0?randomBytes4:ecdhOpts.randomBytes;const lengths=Object.assign(getWLengths(Point2.Fp,Fn2),{seed:Math.max(getMinHashLength(Fn2.ORDER),16)});function isValidSecretKey(secretKey){try{const num=Fn2.fromBytes(secretKey);return Fn2.isValidNot0(num)}catch(error51){return false}}function isValidPublicKey(publicKey,isCompressed){const{publicKey:comp,publicKeyUncompressed}=lengths;try{const l=publicKey.length;if(isCompressed===true&&l!==comp)return false;if(isCompressed===false&&l!==publicKeyUncompressed)return false;return!Point2.fromBytes(publicKey).is0()}catch(error51){return false}}function randomSecretKey(seed){seed=seed===void 0?randomBytes_(lengths.seed):seed;return mapHashToField(abytes6(seed,lengths.seed,"seed"),Fn2.ORDER)}function getPublicKey(secretKey,isCompressed=true){return Point2.BASE.multiply(Fn2.fromBytes(secretKey)).toBytes(isCompressed)}function isProbPub(item){const{secretKey,publicKey,publicKeyUncompressed}=lengths;const allowedLengths=Fn2._lengths;if(!isBytes7(item))return void 0;const l=abytes6(item,void 0,"key").length;const isPub=l===publicKey||l===publicKeyUncompressed;const isSec=l===secretKey||!!allowedLengths?.includes(l);if(isPub&&isSec)return void 0;return isPub}function getSharedSecret(secretKeyA,publicKeyB,isCompressed=true){if(isProbPub(secretKeyA)===true)throw new Error("first arg must be private key");if(isProbPub(publicKeyB)===false)throw new Error("second arg must be public key");const s=Fn2.fromBytes(secretKeyA);const b2=Point2.fromBytes(publicKeyB);if(b2.is0())throw new Error("invalid public key: point at infinity");return b2.multiply(s).toBytes(isCompressed)}const utils2={isValidSecretKey,isValidPublicKey,randomSecretKey};const keygen=createKeygen(randomSecretKey,getPublicKey);Object.freeze(utils2);Object.freeze(lengths);return Object.freeze({getPublicKey,getSharedSecret,keygen,Point:Point2,utils:utils2,lengths})}function ecdsa(Point2,hash3,ecdsaOpts={}){validatePointCons(Point2);const hash_=hash3;ahash2(hash_);validateObject(ecdsaOpts,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const opts=Object.assign({},ecdsaOpts);const randomBytes5=opts.randomBytes===void 0?randomBytes4:opts.randomBytes;const hmac3=opts.hmac===void 0?(key,msg)=>hmac2(hash_,key,msg):opts.hmac;const{Fp,Fn:Fn2}=Point2;const{ORDER:CURVE_ORDER,BITS:fnBits}=Fn2;const blindLength=getMinHashLength(CURVE_ORDER);const csprng=probeRandomBytes(randomBytes5,blindLength);const{keygen,getPublicKey,getSharedSecret,utils:utils2,lengths}=ecdh(Point2,opts);const defaultSigOpts={prehash:true,lowS:typeof opts.lowS==="boolean"?opts.lowS:true,format:"compact",extraEntropy:false};const hasLargeRecoveryLifts=CURVE_ORDER*_2n4+_1n6<Fp.ORDER;function isBiggerThanHalfOrder(number4){const HALF=CURVE_ORDER>>_1n6;return number4>HALF}function validateRS(title,num){if(!Fn2.isValidNot0(num))throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);return num}function assertFieldSignIsSupported(){if(!Fp.isOdd)throw new Error("Field doesn't support isOdd")}function getRecoveryBit(x2,y,r){assertFieldSignIsSupported();return(x2===r?0:2)|Number(Fp.isOdd(y))}function assertRecoverableCurve(){if(hasLargeRecoveryLifts)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function validateSigLength(bytes,format){validateSigFormat(format);const size4=lengths.signature;const sizer=format==="compact"?size4:format==="recovered"?size4+1:void 0;return abytes6(bytes,sizer)}class Signature{r;s;recovery;constructor(r,s,recovery){this.r=validateRS("r",r);this.s=validateRS("s",s);if(recovery!=null){assertRecoverableCurve();if(![0,1,2,3].includes(recovery))throw new Error("invalid recovery id");this.recovery=recovery}Object.freeze(this)}static fromBytes(bytes,format=defaultSigOpts.format){validateSigLength(bytes,format);let recid;if(format==="der"){if(bytes.length>2*Fn2.BYTES+16)throw new DER.Err("invalid signature: DER signature too long");const{r:r2,s:s2}=DER.toSig(abytes6(bytes),Fn2.BYTES+1);return new Signature(r2,s2)}if(format==="recovered"){recid=bytes[0];format="compact";bytes=bytes.subarray(1)}const L2=lengths.signature/2;const r=bytes.subarray(0,L2);const s=bytes.subarray(L2,L2*2);return new Signature(Fn2.fromBytes(r),Fn2.fromBytes(s),recid)}static fromHex(hex3,format){return this.fromBytes(hexToBytes3(hex3),format)}assertRecovery(){const{recovery}=this;if(recovery==null)throw new Error("invalid recovery id: must be present");return recovery}addRecoveryBit(recovery){return new Signature(this.r,this.s,recovery)}recoverPublicKey(messageHash){const{r,s}=this;const recovery=this.assertRecovery();const radj=recovery===2||recovery===3?r+CURVE_ORDER:r;if(!Fp.isValid(radj))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const x2=Fp.toBytes(radj);const R=Point2.fromBytes(concatBytes2(pprefix((recovery&1)===0),x2));const ir2=Fn2.inv(radj);const h=bits2int_modN(abytes6(messageHash,void 0,"msgHash"));const u1=Fn2.create(-h*ir2);const u2=Fn2.create(s*ir2);const Q=Point2.BASE.mulAddUnsafe(u1,R,u2);if(Q.is0())throw new Error("invalid recovery: point at infinify");Q.assertValidity();return Q}hasHighS(){return isBiggerThanHalfOrder(this.s)}toBytes(format=defaultSigOpts.format){validateSigFormat(format);if(format==="der")return hexToBytes3(DER.hexFromSig(this));const{r,s}=this;const rb=Fn2.toBytes(r);const sb=Fn2.toBytes(s);if(format==="recovered"){assertRecoverableCurve();return concatBytes2(Uint8Array.of(this.assertRecovery()),rb,sb)}return concatBytes2(rb,sb)}toHex(format){return bytesToHex3(this.toBytes(format))}}Object.freeze(Signature.prototype);Object.freeze(Signature);const bits2int=opts.bits2int===void 0?function bits2int_def(bytes){if(bytes.length>8192)throw new Error("input is too large");const num=bytesToNumberBE(bytes);const delta=bytes.length*8-fnBits;return delta>0?num>>BigInt(delta):num}:opts.bits2int;const bits2int_modN=opts.bits2int_modN===void 0?function bits2int_modN_def(bytes){return Fn2.create(bits2int(bytes))}:opts.bits2int_modN;const ORDER_MASK=bitMask(fnBits);function int2octets(num){aInRange("num < 2^"+fnBits,num,_0n7,ORDER_MASK);return Fn2.toBytes(num)}function validateMsgAndHash(message2,prehash){abytes6(message2,void 0,"message");return prehash?abytes6(hash_(message2),void 0,"prehashed message"):message2}function prepSig(message2,secretKey,opts2){const{lowS,prehash,extraEntropy}=validateSigOpts(opts2,defaultSigOpts);message2=validateMsgAndHash(message2,prehash);const h1int=bits2int_modN(message2);const d=Fn2.fromBytes(secretKey);if(!Fn2.isValidNot0(d))throw new Error("invalid private key");const seedArgs=[int2octets(d),int2octets(h1int)];if(extraEntropy!=null&&extraEntropy!==false){const e17=extraEntropy===true?randomBytes5(lengths.secretKey):extraEntropy;seedArgs.push(abytes6(e17,void 0,"extraEntropy"))}const seed=concatBytes2(...seedArgs);const m=h1int;function k2sig(kBytes){const k2=bits2int(kBytes);if(!Fn2.isValidNot0(k2))return;const q2=Point2.BASE.multiply(k2).toAffine();const r=Fn2.create(q2.x);if(r===_0n7)return;let s;if(csprng!==void 0){const b2=bytesToNumberBE(mapHashToField(csprng(blindLength),CURVE_ORDER));const ibk=Fn2.inv(Fn2.mul(b2,k2));const bm=Fn2.mul(b2,m);const bd=Fn2.mul(b2,d);s=Fn2.create(ibk*Fn2.create(bm+bd*r))}else{const ik=invertCt(k2,CURVE_ORDER);s=Fn2.create(ik*Fn2.create(m+r*d))}if(s===_0n7)return;let recovery=getRecoveryBit(q2.x,q2.y,r);let normS=s;if(lowS&&isBiggerThanHalfOrder(s)){normS=Fn2.neg(s);recovery^=1}return new Signature(r,normS,hasLargeRecoveryLifts?void 0:recovery)}return{seed,k2sig}}function sign(message2,secretKey,opts2={}){const{seed,k2sig}=prepSig(message2,secretKey,opts2);const drbg=createHmacDrbg(hash_.outputLen,Fn2.BYTES,hmac3);const sig=drbg(seed,k2sig);return sig.toBytes(opts2.format)}function verify3(signature2,message2,publicKey,opts2={}){const{lowS,prehash,format}=validateSigOpts(opts2,defaultSigOpts);publicKey=abytes6(publicKey,void 0,"publicKey");message2=validateMsgAndHash(message2,prehash);if(!isBytes7(signature2)){const end=signature2 instanceof Signature?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+end)}validateSigLength(signature2,format);try{const sig=Signature.fromBytes(signature2,format);const P2=Point2.fromBytes(publicKey);if(P2.is0())return false;if(lowS&&sig.hasHighS())return false;const{r,s}=sig;const h=bits2int_modN(message2);const is=Fn2.inv(s);const u1=Fn2.create(h*is);const u2=Fn2.create(r*is);const R=Point2.BASE.mulAddUnsafe(u1,P2,u2);if(R.is0())return false;const q2=R.toAffine();const v=Fn2.create(q2.x);if(v!==r)return false;if(format==="recovered"&&sig.recovery!==getRecoveryBit(q2.x,q2.y,r))return false;return true}catch(e17){return false}}function recoverPublicKey(signature2,message2,opts2={}){const{prehash}=validateSigOpts(opts2,defaultSigOpts);message2=validateMsgAndHash(message2,prehash);return Signature.fromBytes(signature2,"recovered").recoverPublicKey(message2).toBytes()}return Object.freeze({keygen,getPublicKey,getSharedSecret,utils:utils2,lengths,Point:Point2,sign,verify:verify3,recoverPublicKey,Signature,hash:hash_})}var secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")};var secp256k1_ENDO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var _2n5=BigInt(2);function sqrtMod(y){const P2=secp256k1_CURVE.p;const _3n3=BigInt(3),_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22);const _23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88);const b2=y*y*y%P2;const b3=b2*b2*y%P2;const b6=pow2(b3,_3n3,P2)*b3%P2;const b9=pow2(b6,_3n3,P2)*b3%P2;const b11=pow2(b9,_2n5,P2)*b2%P2;const b22=pow2(b11,_11n,P2)*b11%P2;const b44=pow2(b22,_22n,P2)*b22%P2;const b88=pow2(b44,_44n,P2)*b44%P2;const b176=pow2(b88,_88n,P2)*b88%P2;const b220=pow2(b176,_44n,P2)*b44%P2;const b223=pow2(b220,_3n3,P2)*b3%P2;const t1=pow2(b223,_23n,P2)*b22%P2;const t2=pow2(t1,_6n,P2)*b2%P2;const root=pow2(t2,_2n5,P2);if(!Fpk1.eql(Fpk1.sqr(root),y))throw new Error("Cannot find square root");return root}var Fpk1=Field(secp256k1_CURVE.p,{sqrt:sqrtMod});var Pointk1=weierstrass(secp256k1_CURVE,{Fp:Fpk1,endo:secp256k1_ENDO});var secp256k1=ecdsa(Pointk1,sha2565);var Rho1602=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]);var Id1602=(()=>Uint8Array.from(new Array(16).fill(0).map((_,i)=>i)))();var Pi1602=(()=>Id1602.map(i=>(9*i+5)%16))();var idxLR2=(()=>{const L2=[Id1602];const R=[Pi1602];const res=[L2,R];for(let i=0;i<4;i++)for(let j2 of res)j2.push(j2[i].map(k2=>Rho1602[k2]));return res})();var idxL2=(()=>idxLR2[0])();var idxR2=(()=>idxLR2[1])();var shifts1602=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(i=>Uint8Array.from(i));var shiftsL1602=idxL2.map((idx,i)=>idx.map(j2=>shifts1602[i][j2]));var shiftsR1602=idxR2.map((idx,i)=>idx.map(j2=>shifts1602[i][j2]));var Kl1602=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]);var Kr1602=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function ripemd_f2(group,x2,y,z){if(group===0)return x2^y^z;if(group===1)return x2&y|~x2&z;if(group===2)return(x2|~y)^z;if(group===3)return x2&z|y&~z;return x2^(y|~z)}var BUF_1602=new Uint32Array(16);var _RIPEMD160=class extends HashMD3{h0=1732584193|0;h1=4023233417|0;h2=2562383102|0;h3=271733878|0;h4=3285377520|0;constructor(){super(64,20,8,true)}get(){const{h0,h1,h2,h3,h4}=this;return[h0,h1,h2,h3,h4]}set(h0,h1,h2,h3,h4){this.h0=h0|0;this.h1=h1|0;this.h2=h2|0;this.h3=h3|0;this.h4=h4|0}_cloneInto(to){(to||=new this.constructor).set(...this.get());return this._cloneIntoMeta(to)}process(view,offset){for(let i=0;i<16;i++,offset+=4)BUF_1602[i]=view.getUint32(offset,true);let al=this.h0|0,ar2=al,bl=this.h1|0,br=bl,cl=this.h2|0,cr=cl,dl=this.h3|0,dr2=dl,el=this.h4|0,er=el;for(let group=0;group<5;group++){const rGroup=4-group;const hbl=Kl1602[group],hbr=Kr1602[group];const rl=idxL2[group],rr=idxR2[group];const sl=shiftsL1602[group],sr2=shiftsR1602[group];for(let i=0;i<16;i++){const tl=rotl2(al+ripemd_f2(group,bl,cl,dl)+BUF_1602[rl[i]]+hbl,sl[i])+el|0;al=el,el=dl,dl=rotl2(cl,10)|0,cl=bl,bl=tl}for(let i=0;i<16;i++){const tr2=rotl2(ar2+ripemd_f2(rGroup,br,cr,dr2)+BUF_1602[rr[i]]+hbr,sr2[i])+er|0;ar2=er,er=dr2,dr2=rotl2(cr,10)|0,cr=br,br=tr2}}this.set(this.h1+cl+dr2|0,this.h2+dl+er|0,this.h3+el+ar2|0,this.h4+al+br|0,this.h0+bl+cr|0)}roundClean(){clean4(BUF_1602)}destroy(){this.destroyed=true;clean4(this.buffer);this.set(0,0,0,0,0)}};var ripemd1604=createHasher4(()=>new _RIPEMD160);var Point=(()=>secp256k1.Point)();var Fn=(()=>Point.Fn)();var base58check=createBase58check(sha2565);var MASTER_SECRET=(()=>{return Uint8Array.from("Bitcoin seed".split(""),char=>char.charCodeAt(0))})();var BITCOIN_VERSIONS={private:76066276,public:76067358};var HARDENED_OFFSET=2147483648;var MAX_DEPTH=255;var hash160=data=>ripemd1604(sha2565(data));var fromU32=data=>createView3(data).getUint32(0,false);var toU32=(n,title="number")=>{if(typeof n!=="number")throw new TypeError(`"${title}" expected number, got type=${typeof n}`);if(!Number.isSafeInteger(n)||n<0||n>2**32-1)throw new RangeError(`"${title}" expected integer in range 0..2**32-1, got ${n}`);const buf=new Uint8Array(4);createView3(buf).setUint32(0,n,false);return buf};var validateVersions=(versions2,title="versions")=>{if(!(typeof versions2==="object"&&versions2!==null))throw new Error("versions must be an object");toU32(versions2.private,`${title}.private`);toU32(versions2.public,`${title}.public`);return versions2};var HDKey=class _HDKey{get fingerprint(){if(!this._pubHash){throw new Error("No publicKey set!")}return fromU32(this._pubHash)}get identifier(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get pubKeyHash(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get privateKey(){return this._privateKey?Uint8Array.from(this._privateKey):null}get publicKey(){return this._publicKey?Uint8Array.from(this._publicKey):null}get chainCode(){return this._chainCode?Uint8Array.from(this._chainCode):null}get privateExtendedKey(){const priv=this._privateKey;if(!priv){throw new Error("No private key")}return base58check.encode(this.serialize(this.versions.private,concatBytes(Uint8Array.of(0),priv)))}get publicExtendedKey(){if(!this._publicKey){throw new Error("No public key")}return base58check.encode(this.serialize(this.versions.public,this._publicKey))}static fromMasterSeed(seed,versions2=BITCOIN_VERSIONS){abytes4(seed);versions2=validateVersions(versions2);if(8*seed.length<128||8*seed.length>512){throw new RangeError("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+seed.length)}const I=hmac2(sha5122,MASTER_SECRET,seed);const privateKey=I.slice(0,32);const chainCode=I.slice(32);return new _HDKey({versions:versions2,chainCode,privateKey})}static fromExtendedKey(base58key,versions2=BITCOIN_VERSIONS){versions2=validateVersions(versions2);const keyBuffer=base58check.decode(base58key);if(keyBuffer.length!==78){throw new Error(`HDKey: invalid extended key length: expected 78 bytes, got ${keyBuffer.length}`)}const keyView=createView3(keyBuffer);const version4=keyView.getUint32(0,false);const opt={versions:versions2,depth:keyBuffer[4],parentFingerprint:keyView.getUint32(5,false),index:keyView.getUint32(9,false),chainCode:keyBuffer.slice(13,45)};const key=keyBuffer.slice(45);const isPriv=key[0]===0;if(version4!==versions2[isPriv?"private":"public"]){throw new Error("Version mismatch")}if(isPriv){return new _HDKey({...opt,privateKey:key.slice(1)})}else{return new _HDKey({...opt,publicKey:key})}}static fromJSON(json3){return _HDKey.fromExtendedKey("xpriv"in json3?json3.xpriv:json3.xpub)}versions;depth=0;index=0;parentFingerprint=0;_chainCode=null;_privateKey;_publicKey;_pubHash;constructor(opt){if(!opt||typeof opt!=="object"){throw new Error("HDKey.constructor must not be called directly")}const depth=opt.depth??0;const index=opt.index??0;const parentFingerprint=opt.parentFingerprint??0;if(!Number.isSafeInteger(depth)||depth<0||depth>MAX_DEPTH){throw new RangeError("HDKey: depth must be an integer in range 0..255")}toU32(index,"index");toU32(parentFingerprint,"parentFingerprint");if(depth===0&&(index!==0||parentFingerprint!==0)){throw new Error("HDKey: zero depth with non-zero index/parent fingerprint")}this.versions=opt.versions?validateVersions(opt.versions):BITCOIN_VERSIONS;this.depth=depth;if(opt.chainCode)abytes4(opt.chainCode,32);this._chainCode=opt.chainCode?Uint8Array.from(opt.chainCode):null;this.index=index;this.parentFingerprint=parentFingerprint;if(opt.publicKey&&opt.privateKey){throw new Error("HDKey: publicKey and privateKey at same time.")}if(opt.privateKey){if(!secp256k1.utils.isValidSecretKey(opt.privateKey))throw new Error("Invalid private key");this._privateKey=Uint8Array.from(opt.privateKey);this._publicKey=secp256k1.getPublicKey(this._privateKey,true)}else if(opt.publicKey){this._publicKey=Point.fromBytes(opt.publicKey).toBytes(true)}else{throw new Error("HDKey: no public or private key provided")}this._pubHash=hash160(this._publicKey)}derive(path){if(!/^[mM]'?/.test(path)){throw new Error('Path must start with "m" or "M"')}if(/^[mM]'?$/.test(path)){return this}const parts=path.replace(/^[mM]'?\//,"").split("/");if(parts.length>MAX_DEPTH-this.depth){throw new Error("HDKey: path exceeds the serializable depth 255")}let child=this;for(const c of parts){const m=/^(\d+)('?)$/.exec(c);const m1=m&&m[1];if(!m||m.length!==3||typeof m1!=="string")throw new Error("invalid child index: "+c);let idx=+m1;if(!Number.isSafeInteger(idx)||idx>=HARDENED_OFFSET){throw new Error("Invalid index")}if(m[2]==="'"){idx+=HARDENED_OFFSET}child=child.deriveChild(idx)}return child}deriveChild(index){return this._deriveChild(index)}_deriveChild(index,_I){if(!this._publicKey||!this._chainCode){throw new Error("No publicKey or chainCode set")}let data=toU32(index,"index");if(index>=HARDENED_OFFSET){const priv=this._privateKey;if(!priv){throw new Error("Could not derive hardened child key")}data=concatBytes(Uint8Array.of(0),priv,data)}else{data=concatBytes(this._publicKey,data)}const out=_I||hmac2(sha5122,this._chainCode,data);abytes4(out,64);const childTweak=out.slice(0,32);const chainCode=out.slice(32);const opt={versions:this.versions,chainCode,depth:this.depth+1,parentFingerprint:this.fingerprint,index};if(opt.depth>MAX_DEPTH){throw new Error("HDKey: depth exceeds the serializable value 255")}const retry=()=>{const maxIndex=this._privateKey?2**32-1:HARDENED_OFFSET-1;if(index>=maxIndex){throw new Error(`HDKey: cannot retry child derivation at index ${index}`)}return this.deriveChild(index+1)};const ctweak=Fn.fromBytes(childTweak,true);if(!Fn.isValid(ctweak))return retry();if(this._privateKey){const added=Fn.create(Fn.fromBytes(this._privateKey)+ctweak);if(!Fn.isValidNot0(added))return retry();opt.privateKey=Fn.toBytes(added)}else{const point=Point.fromBytes(this._publicKey);const added=ctweak===0n?point:point.add(Point.BASE.multiply(ctweak));if(added.equals(Point.ZERO))return retry();opt.publicKey=added.toBytes(true)}return new _HDKey(opt)}sign(hash3){if(!this._privateKey){throw new Error("No privateKey set!")}abytes4(hash3,32);return secp256k1.sign(hash3,this._privateKey,{prehash:false})}verify(hash3,signature2){abytes4(hash3,32);abytes4(signature2,64);if(!this._publicKey){throw new Error("No publicKey set!")}return secp256k1.verify(signature2,hash3,this._publicKey,{prehash:false})}wipePrivateData(){if(this._privateKey){this._privateKey.fill(0);this._privateKey=void 0}return this}toJSON(){return this.toPrivateJSON()}toPrivateJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(version4,key){if(!this._chainCode){throw new Error("No chainCode set")}abytes4(key,33);return concatBytes(toU32(version4,"version"),new Uint8Array([this.depth]),toU32(this.parentFingerprint,"parentFingerprint"),toU32(this.index,"index"),this._chainCode,key)}};var b=class e extends Error{constructor(t2,n){super(t2),this.name="CTSError",n?.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:true,enumerable:false,value:n.cause,writable:true}),Object.setPrototypeOf(this,e.prototype)}};var x=class e2 extends b{constructor(t2,n,r){super(t2,r),this.status=n,this.name="HttpResponseError",Object.setPrototypeOf(this,e2.prototype)}};var S=class e3 extends b{constructor(t2,n){super(t2,n),this.name="NetworkError",Object.setPrototypeOf(this,e3.prototype)}};var T=class e4 extends x{constructor(t2,n){super(t2,429),this.retryAfterMs=n,this.name="RateLimitError",Object.setPrototypeOf(this,e4.prototype)}};var te=class e5 extends x{constructor(t2,n){super(n||"Unknown mint operation error",400),this.code=t2,this.name="MintOperationError",Object.setPrototypeOf(this,e5.prototype)}};var E={error(){},warn(){},info(){},debug(){},trace(){},log(){}};function re(e17,t2=E,n){throw t2.error(e17,n),new b(e17)}function D(e17,t2,n=E,r){e17&&re(t2,n,r)}function O(e17,t2,n=E,r){if(e17)try{let i=e17(t2);i&&typeof i.then=="function"&&i.catch(t3=>{try{n.warn("callback failed",{...r??{},error:t3,cb:e17.name??""})}catch{}})}catch(t3){try{n.warn("callback failed",{...r??{},error:t3,cb:e17.name??""})}catch{}}}var ae=8192;var oe=1e4;var se=1024;var ce=1024;var ue=2147483647;var de=2n**64n-1n;var be=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});function xe(e17){try{return be.decode(e17)}catch(e18){throw new b("Malformed UTF-8 sequence",{cause:e18})}}var Se=new TextDecoder("utf-8",{fatal:true});function Ee(e17,t2){if(t2.has(e17))throw TypeError("Cannot initialize the same private elements twice on an object")}function De(e17,t2,n){Ee(e17,t2),t2.set(e17,n)}function Oe(e17){"@babel/helpers - typeof";return Oe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e18){return typeof e18}:function(e18){return e18&&typeof Symbol=="function"&&e18.constructor===Symbol&&e18!==Symbol.prototype?"symbol":typeof e18},Oe(e17)}function ke(e17){if(Object(e17)!==e17)throw TypeError("right-hand side of 'in' should be an object, got "+(e17===null?"null":Oe(e17)));return e17}var k=class e6 extends b{constructor(t2){super(t2),this.name="AmountError",Object.setPrototypeOf(this,e6.prototype)}};var Ae=new WeakMap;var A=class e7{constructor(e17){if(De(this,Ae,true),e17<0n)throw new k(`Amount must be >= 0, got ${e17}`);if(e17>de)throw new k(`Amount exceeds u64 max, got ${e17}`);this.value=e17,Object.freeze(this)}static from(t2){if(t2 instanceof e7){if(!Ae.has(ke(t2)))throw new k("Invalid Amount instance");return t2}if(typeof t2=="bigint"){if(t2<0n)throw new k(`Amount must be >= 0, got ${t2}`);return new e7(t2)}if(typeof t2=="number"){if(!Number.isFinite(t2)||!Number.isInteger(t2))throw new k(`Invalid number amount: ${t2}`);if(t2<0)throw new k(`Amount must be >= 0, got ${t2}`);if(!Number.isSafeInteger(t2))throw new k(`Unsafe integer amount: ${t2}. Use bigint or decimal string.`);return new e7(BigInt(t2))}if(typeof t2=="string"){if(t2.length>20)throw new k(`Amount exceeds u64 max: "${t2.slice(0,20)}..."`);if(!/^(0|[1-9]\d*)$/.test(t2))throw new k(`Invalid amount string "${t2}". Expected non-negative decimal integer.`);return new e7(BigInt(t2))}throw new k("Unsupported amount input type")}static zero(){return new e7(0n)}static one(){return new e7(1n)}toBigInt(){return this.value}toNumber(){if(!this.isSafeNumber())throw new k(`Amount ${this.value} exceeds Number.MAX_SAFE_INTEGER; use toBigInt/toString/toJSON.`);return Number(this.value)}toNumberUnsafe(){return Number(this.value)}toString(){return this.value.toString(10)}toJSON(){return this.toString()}add(t2){let n=e7.from(t2);return new e7(this.value+n.value)}subtract(t2){let n=e7.from(t2),r=this.value-n.value;if(r<0n)throw new k(`Amount underflow: ${this.value} - ${n.value} would be negative`);return new e7(r)}multiplyBy(t2){let n=e7.from(t2).value;return new e7(this.value*n)}divideBy(t2){let n=e7.from(t2).value;if(n<=0n)throw new k(`Divisor must be > 0, got ${n}`);return new e7(this.value/n)}modulo(t2){let n=e7.from(t2).value;if(n<=0n)throw new k(`Divisor must be > 0, got ${n}`);return new e7(this.value%n)}ceilPercent(t2,n=100){if(!Number.isSafeInteger(t2)||t2<0)throw new k(`ceilPercent: numerator must be a non-negative integer, got ${t2}`);if(!Number.isSafeInteger(n)||n<=0)throw new k(`ceilPercent: denominator must be a positive integer, got ${n}`);let r=BigInt(t2),i=BigInt(n);return new e7((this.value*r+(i-1n))/i)}floorPercent(t2,n=100){if(!Number.isSafeInteger(t2)||t2<0)throw new k(`floorPercent: numerator must be a non-negative integer, got ${t2}`);if(!Number.isSafeInteger(n)||n<=0)throw new k(`floorPercent: denominator must be a positive integer, got ${n}`);let r=BigInt(t2),i=BigInt(n);return new e7(this.value*r/i)}inRange(t2,n){let r=e7.from(t2),i=e7.from(n);if(r.greaterThan(i))throw new k(`inRange: min (${r.toString()}) must be <= max (${i.toString()})`);return this.greaterThanOrEqual(r)&&this.lessThanOrEqual(i)}clamp(t2,n){let r=e7.from(t2),i=e7.from(n);if(r.greaterThan(i))throw new k(`clamp: min (${r.toString()}) must be <= max (${i.toString()})`);return e7.max(r,e7.min(i,this))}scaledBy(t2,n){let r=e7.from(t2).value,i=e7.from(n).value;if(i===0n)throw new k("scaledBy: denominator must be > 0");return r===0n?e7.zero():new e7((2n*this.value*r+i)/(2n*i))}isSafeNumber(){let e17=BigInt(2**53-1);return this.value<=e17}isZero(){return this.value===0n}equals(t2){return this.value===e7.from(t2).value}compareTo(t2){let n=e7.from(t2).value;return this.value<n?-1:+(this.value>n)}lessThan(e17){return this.compareTo(e17)<0}lessThanOrEqual(e17){return this.compareTo(e17)<=0}greaterThan(e17){return this.compareTo(e17)>0}greaterThanOrEqual(e17){return this.compareTo(e17)>=0}static min(t2,n){let r=e7.from(t2),i=e7.from(n);return r.compareTo(i)<=0?r:i}static max(t2,n){let r=e7.from(t2),i=e7.from(n);return r.compareTo(i)>=0?r:i}static sum(t2){let n=0n;for(let r of t2)n+=e7.from(r).value;return new e7(n)}withUnit(e17){return new Me(this,e17)}};var je=class e8 extends b{constructor(t2){super(t2),this.name="AmountWithUnitError",Object.setPrototypeOf(this,e8.prototype)}};var Me=class e9{constructor(e17,t2){if(typeof t2!="string"||t2.length===0)throw new je("unit required");this._amount=e17,this.unit=t2,Object.freeze(this)}static from(t2,n){return new e9(A.from(t2),n)}static zero(t2){return new e9(A.zero(),t2)}static one(t2){return new e9(A.one(),t2)}toAmount(){return this._amount}toBigInt(){return this._amount.toBigInt()}toNumber(){return this._amount.toNumber()}toString(){return`[${this.unit}]: ${this._amount.toString()}`}toJSON(){return{amount:this._amount.toString(),unit:this.unit}}[Symbol.toPrimitive](e17){if(e17==="string")return this.toString();throw new je(`Implicit ${e17==="number"?"numeric":"default"} coercion of AmountWithUnit is unsafe; use .toAmount() then explicit arithmetic, or .toString() for display.`)}isZero(){return this._amount.isZero()}isSafeNumber(){return this._amount.isSafeNumber()}requireSameUnit(e17){if(this.unit!==e17.unit)throw new je(`unit mismatch: ${this.unit} vs ${e17.unit}`)}add(t2){return this.requireSameUnit(t2),new e9(this._amount.add(t2._amount),this.unit)}subtract(t2){return this.requireSameUnit(t2),new e9(this._amount.subtract(t2._amount),this.unit)}equals(e17){return this.requireSameUnit(e17),this._amount.equals(e17._amount)}compareTo(e17){return this.requireSameUnit(e17),this._amount.compareTo(e17._amount)}lessThan(e17){return this.compareTo(e17)<0}lessThanOrEqual(e17){return this.compareTo(e17)<=0}greaterThan(e17){return this.compareTo(e17)>0}greaterThanOrEqual(e17){return this.compareTo(e17)>=0}inRange(e17,t2){return this.requireSameUnit(e17),this.requireSameUnit(t2),this._amount.inRange(e17._amount,t2._amount)}clamp(t2,n){return this.requireSameUnit(t2),this.requireSameUnit(n),new e9(this._amount.clamp(t2._amount,n._amount),this.unit)}multiplyBy(t2){return new e9(this._amount.multiplyBy(t2),this.unit)}divideBy(t2){return new e9(this._amount.divideBy(t2),this.unit)}modulo(t2){return new e9(this._amount.modulo(t2),this.unit)}ceilPercent(t2,n){return new e9(this._amount.ceilPercent(t2,n),this.unit)}floorPercent(t2,n){return new e9(this._amount.floorPercent(t2,n),this.unit)}scaledBy(t2,n){return new e9(this._amount.scaledBy(t2,n),this.unit)}static min(e17,t2){return e17.requireSameUnit(t2),e17.compareTo(t2)<=0?e17:t2}static max(e17,t2){return e17.requireSameUnit(t2),e17.compareTo(t2)>=0?e17:t2}static sum(t2,n){let r=n,i=0n,a=false;for(let e17 of t2){if(r===void 0)r=e17.unit;else if(e17.unit!==r)throw new je(`unit mismatch: ${r} vs ${e17.unit}`);i+=e17._amount.toBigInt(),a=true}if(r===void 0)throw new je("cannot infer unit from empty sum");return new e9(a?A.from(i):A.zero(),r)}};var j=Object.freeze({parse:Ve,stringify:Ge});var Ne=64;var Pe;function Fe(e17){return typeof e17=="object"&&!!e17&&!Array.isArray(e17)}function Ie(){let e17=globalThis.BigInt;return typeof e17=="function"?e17:void 0}function Le(e17){if(!Pe){let t2=e17(String(2**53-1));Pe={max:t2,min:-t2}}return Pe}var Re=class{constructor(e17,t2,n,r){this.src=e17,this.strict=t2,this.fallbackTo=n,this.bigIntCtor=r,this.i=0}parse(){let e17=this.parseValue(0);if(this.skipWhitespace(),!this.isEnd())throw this.syntaxError("Unexpected trailing input");return e17}parseValue(e17){if(e17>Ne)throw this.syntaxError("JSON nesting exceeds the maximum depth");this.skipWhitespace();let t2=this.peek();if(t2==="{")return this.parseObject(e17);if(t2==="[")return this.parseArray(e17);if(t2==='"')return this.parseString();if(t2==="-"||this.isDigit(t2))return this.parseNumber();if(t2==="t")return this.parseLiteral("true",true);if(t2==="f")return this.parseLiteral("false",false);if(t2==="n")return this.parseLiteral("null",null);throw this.syntaxError(`Unexpected token '${t2||"EOF"}'`)}parseObject(e17){this.expect("{"),this.skipWhitespace();let t2={},n=new Set;if(this.peek()==="}")return this.expect("}"),t2;for(;!this.isEnd();){let r=this.parseString();if(this.strict&&n.has(r))throw this.syntaxError(`Duplicate key "${r}"`);if(n.add(r),this.skipWhitespace(),this.expect(":"),Object.defineProperty(t2,r,{value:this.parseValue(e17+1),writable:true,enumerable:true,configurable:true}),this.skipWhitespace(),this.peek()==="}")return this.expect("}"),t2;this.expect(","),this.skipWhitespace()}throw this.syntaxError("Unterminated object")}parseArray(e17){this.expect("["),this.skipWhitespace();let t2=[];if(this.peek()==="]")return this.expect("]"),t2;for(;!this.isEnd();){if(t2.push(this.parseValue(e17+1)),this.skipWhitespace(),this.peek()==="]")return this.expect("]"),t2;this.expect(","),this.skipWhitespace()}throw this.syntaxError("Unterminated array")}parseString(){this.expect('"');let e17="";for(;!this.isEnd();){let t2=this.next();if(t2==='"')return e17;if(t2==="\\"){let t3=this.next();switch(t3){case'"':case"\\":case"/":e17+=t3;break;case"b":e17+="\b";break;case"f":e17+="\f";break;case"n":e17+="\n";break;case"r":e17+="\r";break;case"t":e17+=" ";break;case"u":{let t4=this.src.slice(this.i,this.i+4);if(!/^[0-9a-fA-F]{4}$/.test(t4))throw this.syntaxError("Invalid unicode escape");this.i+=4,e17+=String.fromCharCode(parseInt(t4,16));break}default:throw this.syntaxError(`Invalid escape '\\${t3}'`)}continue}if(t2<" ")throw this.syntaxError("Invalid control character in string");e17+=t2}throw this.syntaxError("Unterminated string")}parseNumber(){let e17=this.i;this.peek()==="-"&&(this.i+=1),this.peek()==="0"?this.i+=1:this.readDigits(),this.peek()==="."&&(this.i+=1,this.readDigits());let t2=this.peek();if(t2==="e"||t2==="E"){this.i+=1;let e18=this.peek();(e18==="+"||e18==="-")&&(this.i+=1),this.readDigits()}let n=this.src.slice(e17,this.i);if(!(n.indexOf(".")===-1&&n.indexOf("e")===-1&&n.indexOf("E")===-1)){let e18=Number(n);if(!Number.isFinite(e18))throw this.syntaxError("Bad number");return e18}if(!this.bigIntCtor)switch(this.fallbackTo){case"number":{let e18=Number(n);if(!Number.isFinite(e18))throw this.syntaxError("Bad number");return e18}case"string":return n;case"error":throw new b("BigInt is not available in this runtime")}let r=this.bigIntCtor(n),{max:i,min:a}=Le(this.bigIntCtor);return r>i||r<a?r:Number(n)}parseLiteral(e17,t2){if(this.src.slice(this.i,this.i+e17.length)!==e17)throw this.syntaxError(`Unexpected token near '${this.src.slice(this.i,this.i+8)}'`);return this.i+=e17.length,t2}readDigits(){let e17=this.i;for(;this.isDigit(this.peek());)this.i+=1;if(this.i===e17)throw this.syntaxError("Bad number")}skipWhitespace(){for(;!this.isEnd();){let e17=this.peek();if(e17===" "||e17==="\n"||e17==="\r"||e17===" "){this.i+=1;continue}break}}expect(e17){if(this.next()!==e17)throw this.syntaxError(`Expected '${e17}'`)}peek(){return this.src.charAt(this.i)}next(){let e17=this.src.charAt(this.i);return this.i+=1,e17}isDigit(e17){return e17>="0"&&e17<="9"}isEnd(){return this.i>=this.src.length}syntaxError(e17){return SyntaxError(`${e17} at position ${this.i}`)}};function ze(e17,t2,n){Reflect.defineProperty(e17,t2,{value:n,writable:true,enumerable:true,configurable:true})}function Be(e17,t2,n){let r=Array.isArray(e17)?e17[Number(t2)]:e17[t2];if(Array.isArray(r))for(let e18=0;e18<r.length;e18+=1){let t3=Be(r,String(e18),n);t3===void 0?Reflect.deleteProperty(r,e18):ze(r,String(e18),t3)}else if(Fe(r))for(let e18 of Object.keys(r)){let t3=Be(r,e18,n);t3===void 0?delete r[e18]:ze(r,e18,t3)}return n.call(e17,t2,r)}function Ve(e17,t2,n){let r=n?.strict===true,i=n?.fallbackTo??"number";if(i!=="number"&&i!=="string"&&i!=="error")throw new b(`Incorrect value for fallbackTo option, must be "number", "string", "error" or undefined but passed ${String(n?.fallbackTo)}`);let a=new Re(String(e17),r,i,Ie()).parse();return typeof t2=="function"?Be({"":a},"",t2):a}function He(e17){let t2=JSON.stringify(e17);if(typeof t2!="string")throw new b("Failed to stringify string value");return t2}function Ue(e17){return typeof e17=="object"&&!!e17&&"toJSON"in e17&&typeof e17.toJSON=="function"}function We(e17){return e17 instanceof Number||e17 instanceof String||e17 instanceof Boolean?e17.valueOf():e17}function Ge(e17,t2,n){let r="",i="",a=new WeakSet;if(typeof n=="number"?i=" ".repeat(Math.min(10,Math.max(0,Math.floor(n)))):typeof n=="string"&&(i=n.slice(0,10)),t2&&typeof t2!="function"&&!Array.isArray(t2))throw new b("stringify: replacer must be a function or array");let o=Array.isArray(t2)?Array.from(new Set(t2.filter(e18=>typeof e18=="string"||typeof e18=="number").map(e18=>String(e18)))):void 0,s=(e18,n2)=>{let c=e18[n2];switch(c instanceof A?c=c.toBigInt():Ue(c)&&(c=c.toJSON(n2)),typeof t2=="function"&&(c=t2.call(e18,n2,c)),c=We(c),typeof c){case"string":return He(c);case"number":return Number.isFinite(c)?String(c):"null";case"boolean":return c?"true":"false";case"bigint":return String(c);case"undefined":return;case"object":{if(c===null)return"null";if(a.has(c))throw TypeError("Converting circular structure to JSON");a.add(c);let e19=r;r+=i;try{if(Array.isArray(c)){let t4=[],n4=c;for(let e20=0;e20<c.length;e20+=1){let r2=s(n4,String(e20));t4.push(r2??"null")}let i3=t4.length===0?"[]":r?`[
|
|
2426
|
+
More results available \u2014 re-run with --cursor ${result.next_cursor}`)}}else{json({dvmId,slug,feedback:result.feedback,next_cursor:result.next_cursor,org:result.org})}}async function feedbackEnable(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await updateDvmSettings(platformUrl,token,dvmId,{feedback_enabled:true});if(opts.human){info(`Feedback collection enabled for '${slug}'.`)}else{json({...result,dvmId,slug})}}async function feedbackDisable(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await updateDvmSettings(platformUrl,token,dvmId,{feedback_enabled:false});if(opts.human){info(`Feedback collection disabled for '${slug}'.`)}else{json({...result,dvmId,slug})}}import{DvmError as DvmError24}from"@dvmkit/sdk/internal";init_output();async function handle(h,opts){const creds=resolveAuth();if(!creds){throw new DvmError24("auth_required","Not authenticated.","Set DVMKIT_API_KEY or run `dvmctl auth`.")}const platformUrl=process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev";await setHandle(platformUrl,creds.token,h);if(opts.human){info(`Handle set to "${h}". Your DVMs will be accessible at ${h}--<slug>.dvmkit.ai`)}else{json({status:"ok",handle:h})}}async function handleCheck(h,opts){const platformUrl=process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev";const result=await checkHandle(platformUrl,h);if(opts.human){info(result.available?`"${h}" is available.`:`"${h}" is taken.`)}else{json({handle:h,available:result.available})}}init_output();async function dvmInfo(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const{dvm,deploys,domains:domains2}=await getDvm(platformUrl,token,dvmId);if(opts.human){const suspension=dvm.status==="suspended"?dvm.suspensionReason==="builder_pause"?" (paused \u2014 run `dvmctl resume` to bring it back)":dvm.suspensionReason==="free_tier_idle"?" (idle \u2014 run `dvmctl resume` to bring it back)":` (${dvm.suspensionReason??"suspended by the operator"}${dvm.pausedAt!=null?"; you had also paused it":""})`:"";info(` Name: ${dvm.name}`);info(` Slug: ${dvm.slug}`);info(` Org: ${dvm.orgHandle??"personal"}`);info(` Status: ${dvm.status}${suspension}`);info(` Public URL: ${dvm.dvmkitUrl??"\u2014 (set a handle with `dvmctl handle set <handle>` to get one)"}`);info(` Origin: ${dvm.url??"\u2014"}`);info(` Region: ${dvm.region}`);info(` Created: ${fmtDate4(dvm.createdAt)}`);info(` Updated: ${fmtDate4(dvm.updatedAt)}`);if(deploys.length>0){info("");info(" Recent deploys:");for(const d of deploys.slice(0,5)){const duration3=d.endedAt?` (${fmtDuration2(d.endedAt-d.startedAt)})`:"";info(` #${d.id.slice(0,8)} ${d.status} ${fmtDate4(d.startedAt)}${duration3}`)}}if(domains2.length>0){info("");info(" Domains:");for(const d of domains2){info(` ${d.domain} ${d.status}`)}}}else{json({dvmId,slug,dvm,deploys,domains:domains2})}}function fmtDate4(epoch){return new Date(epoch).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}function fmtDuration2(ms){const s=Math.round(ms/1e3);if(s<60)return`${s}s`;const m=Math.floor(s/60);const rem=s%60;return rem>0?`${m}m ${rem}s`:`${m}m`}init_builder_store();init_output();import{randomUUID}from"crypto";import{DvmError as DvmError25}from"@dvmkit/sdk/internal";function init(handle2,opts){if(!opts.selfHosted){throw new DvmError25("init_requires_self_hosted","`dvmctl init` only applies to self-hosted DVMs.","Platform-hosted DVMs get their canonical_dvm_id from the platform at deploy time. Re-run with --self-hosted if this DVM runs outside dvmkit infrastructure.")}if(!/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(handle2)){throw new DvmError25("invalid_handle",`Handle "${handle2}" is not a valid DVM slug.`,"Handles are 3-40 lowercase alphanumeric characters or hyphens.")}const matches2=findBuilderDvmsByHandle(handle2);if(matches2.length>0){const existing=matches2[0];throw new DvmError25("already_initialized",existing.self_hosted?`Handle "${handle2}" is already initialized with canonical_dvm_id=${existing.canonical_dvm_id}.`:`Handle "${handle2}" already belongs to a deployed DVM (canonical_dvm_id=${existing.canonical_dvm_id}).`,`Initializing over it would mint a second canonical_dvm_id for the same handle, and the Cashu lock keys derive from that ID \u2014 every proof already locked under ${matches2.map(entry=>entry.canonical_dvm_id).join(", ")} would become underivable. If you genuinely want a new identity, melt or write off what is locked to the old one first, then remove that entry from ~/.dvmkit/builder.json by hand.`)}const canonicalDvmId=randomUUID();upsertBuilderDvm(canonicalDvmId,{handle:handle2,canonical_dvm_id:canonicalDvmId,current_rotation_index:0,self_hosted:true});if(opts.human){info(`Initialized self-hosted DVM "${handle2}".`);info(` canonical_dvm_id: ${canonicalDvmId}`);info(" rotation_index: 0");info("");info("Advertise this canonical_dvm_id on /v1/info via the SDK's");info("DVMKIT_CANONICAL_DVM_ID env var (or DVMKIT_DVM_ID for compatibility).")}else{json({status:"initialized",handle:handle2,canonical_dvm_id:canonicalDvmId,current_rotation_index:0,self_hosted:true})}}init_output();async function list(opts){const{token,platformUrl}=requireAuth();const{dvms,org}=await listDvms(platformUrl,token,{org:resolveOrgScope(opts)});if(opts.human){info(`Org: ${scopeLabel(org)}`);if(dvms.length===0){info(`No DVMs found in ${scopeLabel(org)}.`);return}const slugW=Math.max(4,...dvms.map(d=>d.slug.length));const nameW=Math.max(4,...dvms.map(d=>d.name.length));const statusW=Math.max(6,...dvms.map(d=>d.status.length));const regionW=Math.max(6,...dvms.map(d=>d.region.length));const header=` ${"SLUG".padEnd(slugW)} ${"NAME".padEnd(nameW)} ${"STATUS".padEnd(statusW)} ${"REGION".padEnd(regionW)} URL`;info(header);for(const d of dvms){const url2=d.dvmkitUrl??d.url??"\u2014";info(` ${d.slug.padEnd(slugW)} ${d.name.padEnd(nameW)} ${d.status.padEnd(statusW)} ${d.region.padEnd(regionW)} ${url2}`)}}else{json({dvms,org})}}init_builder_mnemonic();init_defaults();init_output();import{DvmError as DvmError26}from"@dvmkit/sdk/internal";function lockCreate(opts){const existing=readBuilderMnemonic();if(existing&&!opts.import&&!opts.force){if(opts.human){info("Builder mnemonic already exists.");info(`Mnemonic stored at: ${BUILDER_MNEMONIC_FILE}`);info("\nTo replace it, re-run with --force (fresh words) or --import <words>");info("(known words). Either way the current mnemonic is copied to a");info("timestamped .bak sibling first.");info("\n\u26A0 Proofs locked to lock pubkeys derived from the current words stop");info(" being spendable once you replace them \u2014 re-run `dvmctl deploy` for");info(" every DVM afterwards.")}else{json({status:"already_exists",mnemonicFile:BUILDER_MNEMONIC_FILE,hint:`A builder mnemonic already exists, so nothing was written. Re-run with --force to generate fresh words, or --import <words> to restore a known mnemonic; either way the current mnemonic is copied to a timestamped .bak sibling (mode 0600) first. Replacing it makes proofs locked to lock pubkeys derived from the current words unspendable, so \`dvmctl deploy\` has to be re-run for every DVM afterwards.`})}return}let mnemonic;if(opts.import){const words=opts.import.trim();if(!isValidMnemonic(words)){throw new DvmError26("invalid_mnemonic","The provided mnemonic is not a valid 12-word BIP-39 phrase.","Check that all 12 words are correct and separated by spaces.")}mnemonic=words}else{mnemonic=generateRecoveryMnemonic()}const{backupFile}=writeBuilderMnemonic(mnemonic,{force:Boolean(opts.import)||Boolean(opts.force)});if(opts.human){if(!opts.import){info("Builder mnemonic generated.\n");info("\u26A0 Write down these 12 words \u2014 they are the ONLY way to recover");info(" Cashu proofs locked to your DVMs. We never see them.\n");const words=mnemonic.split(" ");for(let i=0;i<words.length;i++){info(` ${String(i+1).padStart(2)}. ${words[i]}`)}info("")}else{info("Builder mnemonic imported.\n")}info(`Mnemonic stored at: ${BUILDER_MNEMONIC_FILE}`);if(backupFile){info(`Previous mnemonic backed up to: ${backupFile}`);info("\u26A0 Proofs locked to lock pubkeys derived from the previous mnemonic\n are no longer spendable with this one. Re-run `dvmctl deploy` for\n every DVM so it advertises a lock pubkey you can still derive.")}info("\nThe per-DVM lock pubkey is registered automatically on `dvmctl deploy`.")}else{json({status:opts.import?"imported":"generated",mnemonicFile:BUILDER_MNEMONIC_FILE,...backupFile?{backupFile,hint:`The mnemonic this replaced was copied to ${backupFile} (mode 0600). Proofs locked to lock pubkeys derived from it are not spendable with the new mnemonic \u2014 re-run \`dvmctl deploy\` for every DVM, or restore with \`dvmctl lock create --import\` from the backup.`}:{}})}}init_output();async function logs(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);if(opts.since)parseDurationMs(opts.since);if(opts.tail){const handle2=await streamLogs(platformUrl,token,dvmId,{since:opts.since},line=>{raw(line)});process.on("SIGINT",()=>{handle2.stop();process.exit(0)});await new Promise(()=>{});return}const lineCount=opts.lines?Number(opts.lines):100;const logLines=await getLogs(platformUrl,token,dvmId,{lines:lineCount,since:opts.since});for(const line of logLines){raw(line)}}init_output();import{DvmError as DvmError27}from"@dvmkit/sdk/internal";async function drainsOwed(handle2,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.getPendingDrains());const now=Date.now();const owed=res.drains.filter(d=>d.settlement==="manual").sort((a,b2)=>a.created_at-b2.created_at).map(d=>({...d,age_ms:Math.max(0,now-d.created_at)}));const totals=totalsByCurrency(owed);if(opts.human){if(owed.length===0){info("No stablecoin refunds are waiting on you. Nothing to settle by hand.");return}for(const drain of owed){raw(`${drain.credit_id} ${drain.drain_id} ${drain.method} ${formatOwed(drain)} to=${payoutAddress(drain)} ${formatAge(drain.age_ms)} old`)}info(`${owed.length} refund(s) owed: ${totals.map(t2=>formatMicro2(t2.amount_micro,t2.currency)).join(", ")}. Record one with \`dvmctl credit drain-settle ${handle2} <credit-id> <drain-id> --tx <hash>\`.`);return}json({op:"credit_drains_owed",handle:handle2,dvmId,slug:handle2,drains:owed,owed_count:owed.length,owed_totals:totals,display:owed.length===0?"This DVM owes no stablecoin refunds that a person has to settle.":`${owed.length} stablecoin refund(s) are owed to callers and no job will pay them: ${totals.map(t2=>formatMicro2(t2.amount_micro,t2.currency)).join(", ")}. Each one was debited from the caller's balance already, so the money is owed whether or not it is sent.`,hint:"Send each payout on its own rail (`method` names it, `payout.address` is the destination, `amount_native` is the figure in the token's own units), then record it with `dvmctl credit drain-settle <handle> <credit-id> <drain-id> --tx <hash>`."})}async function drainSettle(handle2,creditId,drainId,opts){const transaction=opts.tx?.trim();if(!transaction){throw new DvmError27("missing_transaction","No settlement transaction named.","Pass `--tx <hash>` \u2014 the on-chain transaction that paid the refund. It is the only evidence this row will ever carry, and `dvmctl credit drains-owed` lists the credit and drain ids to go with it.")}const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.markDrainSent({credit_id:creditId,drain_id:drainId,sent_ref:{transaction,settled_by:"operator",...opts.note===void 0?{}:{note:opts.note}}}));if(opts.human){info(res.replayed?`Drain ${drainId} was already recorded as sent \u2014 nothing changed, and your transaction was not recorded over the one on file.`:`Recorded ${transaction} against drain ${drainId} on ${creditId}.`);return}json({op:"credit_drain_settle",handle:handle2,dvmId,slug:handle2,credit_id:res.credit_id,drain_id:res.drain_id,transaction,replayed:res.replayed,display:res.replayed?`This refund was already recorded as sent, so nothing changed and the settlement reference on file was left alone. If you just sent the payout, check the recorded transaction before sending another \u2014 it may already have been paid.`:`Recorded the payout for drain ${drainId} on ${creditId}. The caller's next reclaim poll sees it settled, with a countersigned receipt.`,hint:"The reclaim is reported to the platform inside the same transaction as this transition, so its liability view catches up without another command \u2014 and exactly once, however many times this runs."})}function totalsByCurrency(drains){const byCurrency=new Map;for(const drain of drains){const total=byCurrency.get(drain.currency)??{currency:drain.currency,amount_micro:0,count:0};total.amount_micro+=drain.amount_micro;total.count++;byCurrency.set(drain.currency,total)}return[...byCurrency.values()].sort((a,b2)=>a.currency.localeCompare(b2.currency))}function payoutAddress(drain){const payout=drain.payout;return payout.address??"-"}function formatOwed(drain){const fiat=formatMicro2(drain.amount_micro,drain.currency);return drain.amount_native===null?fiat:`${fiat} (${drain.amount_native} native)`}function formatMicro2(amountMicro,currency){return`${(amountMicro/1e6).toFixed(6)} ${currency.toUpperCase()}`}function formatAge(ms){const seconds2=Math.floor(ms/1e3);if(seconds2<60)return`${seconds2}s`;if(seconds2<3600)return`${Math.round(seconds2/60)}m`;if(seconds2<86400)return`${Math.round(seconds2/3600)}h`;return`${Math.round(seconds2/86400)}d`}import{checkMeltQuoteState,DvmError as DvmError28,fetchLnurlPayInvoice,fetchMeltQuote,getInputFeesForProofs,makeInvoice,missingDleqRecoveryDiagnostic as missingDleqRecoveryDiagnostic2,parseNwcUri as parseNwcUri2,toLockPubkey as toLockPubkey3}from"@dvmkit/sdk/internal";init_builder_lock_identity();init_defaults();import{chmodSync as chmodSync3,existsSync as existsSync8,mkdirSync as mkdirSync6,readFileSync as readFileSync8,writeFileSync as writeFileSync6}from"fs";function recordDrainState(dvmId,known,nowMs=Date.now()){const state=readState();if(known){if(!state.has(dvmId))return null;state.delete(dvmId);writeState(state);return null}const existing=state.get(dvmId)?.unknown_since;if(existing)return existing;const since=new Date(nowMs).toISOString();state.set(dvmId,{unknown_since:since});writeState(state);return since}function drainHoldElapsedMs(unknownSince,nowMs=Date.now()){if(!unknownSince)return null;const startedMs=Date.parse(unknownSince);if(Number.isNaN(startedMs))return null;return Math.max(0,nowMs-startedMs)}function readState(){const state=new Map;if(!existsSync8(DRAIN_HOLD_STATE_FILE))return state;try{const parsed=JSON.parse(readFileSync8(DRAIN_HOLD_STATE_FILE,"utf-8"));if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return state;for(const[dvmId,entry]of Object.entries(parsed)){const since=entry?.unknown_since;if(typeof since==="string")state.set(dvmId,{unknown_since:since})}return state}catch{return new Map}}function writeState(state){try{if(!existsSync8(BUILDER_CONFIG_DIR)){mkdirSync6(BUILDER_CONFIG_DIR,{recursive:true,mode:448})}writeFileSync6(DRAIN_HOLD_STATE_FILE,JSON.stringify(Object.fromEntries(state)),{mode:384});chmodSync3(DRAIN_HOLD_STATE_FILE,384)}catch{}}init_defaults();import{appendFileSync,chmodSync as chmodSync4,existsSync as existsSync9,mkdirSync as mkdirSync7,readFileSync as readFileSync9,writeFileSync as writeFileSync7}from"fs";function appendPreMelt(entry){appendEntry({...entry,kind:"pre_melt",ts:Date.now()})}function appendPostMelt(entry){appendEntry({...entry,kind:"post_melt",ts:Date.now()})}function readInFlight(dvmId){if(!existsSync9(MELT_PENDING_LOG_FILE))return[];const raw2=readFileSync9(MELT_PENDING_LOG_FILE,"utf-8");const pre=new Map;const done=new Set;for(const line of raw2.split("\n")){if(!line)continue;let entry;try{entry=JSON.parse(line)}catch{continue}if(entry.dvm_id!==dvmId)continue;const key=`${entry.dvm_id}|${entry.quote_id}`;if(entry.kind==="pre_melt"){pre.set(key,entry)}else{done.add(key)}}const out=[];for(const[key,entry]of pre){if(done.has(key))continue;out.push({ts:entry.ts,dvmId:entry.dvm_id,rowIds:entry.row_ids,mintUrl:entry.mint_url,quoteId:entry.quote_id,lockPubkey:entry.lock_pubkey,totalSats:entry.total_sats})}return out}function appendEntry(entry){ensureLogFile();appendFileSync(MELT_PENDING_LOG_FILE,JSON.stringify(entry)+"\n")}function ensureLogFile(){if(!existsSync9(BUILDER_CONFIG_DIR)){mkdirSync7(BUILDER_CONFIG_DIR,{recursive:true,mode:448})}if(!existsSync9(MELT_PENDING_LOG_FILE)){writeFileSync7(MELT_PENDING_LOG_FILE,"",{mode:384})}else{chmodSync4(MELT_PENDING_LOG_FILE,384)}}init_defaults();import{chmodSync as chmodSync5,existsSync as existsSync10,mkdirSync as mkdirSync8,readFileSync as readFileSync10,writeFileSync as writeFileSync8}from"fs";function recordMeltSuccess(dvmId,mode,run,nowMs=Date.now()){const state=readState2();const existing=state.get(dvmId)??{sweep:null,drains_only:null};state.set(dvmId,{...existing,[mode]:{...run,at:new Date(nowMs).toISOString()}});writeState2(state)}function readMeltSuccesses(){return readState2()}function meltRunAgeMs(run,nowMs=Date.now()){if(!run)return null;const atMs=Date.parse(run.at);if(Number.isNaN(atMs))return null;if(atMs>nowMs)return null;return nowMs-atMs}function readState2(){const state=new Map;if(!existsSync10(MELT_SUCCESS_FILE))return state;try{const parsed=JSON.parse(readFileSync10(MELT_SUCCESS_FILE,"utf-8"));if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return state;for(const[dvmId,entry]of Object.entries(parsed)){const record2=coerce(entry);if(record2)state.set(dvmId,record2)}return state}catch{return new Map}}function coerce(entry){if(!entry||typeof entry!=="object"||Array.isArray(entry))return null;const candidate=entry;const sweep=coerceRun(candidate.sweep);const drainsOnly=coerceRun(candidate.drains_only);if(!sweep&&!drainsOnly)return null;return{sweep,drains_only:drainsOnly}}function coerceRun(run){if(!run||typeof run!=="object"||Array.isArray(run))return null;const candidate=run;if(typeof candidate.at!=="string")return null;return{at:candidate.at,handle:typeof candidate.handle==="string"?candidate.handle:"",batches_melted:numberOr(candidate.batches_melted),sats_melted:numberOr(candidate.sats_melted),drains_parked:numberOr(candidate.drains_parked)}}function numberOr(value){return typeof value==="number"&&Number.isFinite(value)?value:0}function writeState2(state){try{if(!existsSync10(BUILDER_CONFIG_DIR)){mkdirSync8(BUILDER_CONFIG_DIR,{recursive:true,mode:448})}writeFileSync8(MELT_SUCCESS_FILE,JSON.stringify(Object.fromEntries(state)),{mode:384});chmodSync5(MELT_SUCCESS_FILE,384)}catch{}}init_builder_store();init_output();var U32_MASK643=(()=>BigInt(2**32-1))();var _32n3=BigInt(32);function fromBig3(n,le=false){if(le)return{h:Number(n&U32_MASK643),l:Number(n>>_32n3&U32_MASK643)};return{h:Number(n>>_32n3&U32_MASK643)|0,l:Number(n&U32_MASK643)|0}}function split3(lst,le=false){const len=lst.length;let Ah=new Uint32Array(len);let Al=new Uint32Array(len);for(let i=0;i<len;i++){const{h,l}=fromBig3(lst[i],le);[Ah[i],Al[i]]=[h,l]}return[Ah,Al]}var fromNumH=n=>n/2**32|0;var fromNumL=n=>n>>>0;function setU64FromNum(view,byteOffset,n,isLE3){const h=fromNumH(n);const l=fromNumL(n);view.setUint32(byteOffset,isLE3?l:h,isLE3);view.setUint32(byteOffset+4,isLE3?h:l,isLE3)}var shrSH=(h,_l,s)=>h>>>s;var shrSL=(h,l,s)=>h<<32-s|l>>>s;var rotrSH=(h,l,s)=>h>>>s|l<<32-s;var rotrSL=(h,l,s)=>h<<32-s|l>>>s;var rotrBH=(h,l,s)=>h<<64-s|l>>>s-32;var rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:l|0}}var add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0);var add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0;var add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0);var add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0;var add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0);var add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0;function isBytes5(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}var atitle=title=>title?`"${title}" `:"";function anumber5(n,title=""){if(typeof n!=="number")throw new TypeError(atitle(title)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(atitle(title)+"expected integer >= 0, got "+n);return n}function abytes4(value,length,title=""){if(isBytes5(value)&&(length===void 0||value.length===length))return value;if(length!==void 0)anumber5(length,"length");const bytes=isBytes5(value);const ofLen=length!==void 0?` of length ${length}`:"";const got=bytes?`length=${value.length}`:`type=${typeof value}`;const message2=atitle(title)+"expected Uint8Array"+ofLen+", got "+got;if(!bytes)throw new TypeError(message2);throw new RangeError(message2)}function ahash2(h){if(typeof h!=="function"||typeof h.create!=="function")throw new TypeError("expected hash wrapped by utils.createHasher");anumber5(h.outputLen);anumber5(h.blockLen);if(h.outputLen<1||h.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var aobject=(value,label)=>{if(value===null||typeof value!=="object"||Array.isArray(value))throw new TypeError((label==="object"?"":`"${label}" `)+"expected object, got type="+typeof value)};var aopts=(value,label)=>{aobject(value,label);const proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)throw new TypeError(`"${label}" expected plain object`);if(Object.hasOwn(value,"__proto__"))throw new TypeError(`"${label}.__proto__" is not allowed`)};function aexists4(instance,checkFinished=true){if(instance.destroyed)throw new Error("hash was destroyed");if(checkFinished&&instance.finished)throw new Error("digest() was already called")}function aoutput4(out,instance){abytes4(out,void 0,"output");const min=instance.outputLen;if(!(out.length>=min)){throw new RangeError('"output" expected length >= '+min)}}function clean4(...arrays){for(let i=0;i<arrays.length;i++){arrays[i].fill(0)}}function createView3(arr){return new DataView(arr.buffer,arr.byteOffset,arr.byteLength)}function rotr3(word,shift){return word<<32-shift|word>>>shift}function rotl2(word,shift){return word<<shift|word>>>32-shift>>>0}var hasHexBuiltin2=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")();var hexes3=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));function bytesToHex2(bytes){abytes4(bytes);if(hasHexBuiltin2)return bytes.toHex();let hex3="";for(let i=0;i<bytes.length;i++){hex3+=hexes3[bytes[i]]}return hex3}function asciiToBase16(ch){return ch>=48&&ch<=57?ch-48:ch>=65&&ch<=70?ch-(65-10):ch>=97&&ch<=102?ch-(97-10):void 0}function hexToBytes2(hex3){if(typeof hex3!=="string")throw new TypeError("hex string expected, got "+typeof hex3);if(hasHexBuiltin2){try{return Uint8Array.fromHex(hex3)}catch(error51){if(error51 instanceof SyntaxError)throw new RangeError(error51.message);throw error51}}const hl=hex3.length;const al=hl/2;if(hl%2)throw new RangeError("hex string expected, got unpadded hex of length "+hl);const array2=new Uint8Array(al);for(let ai=0,hi=0;ai<al;ai++,hi+=2){const n1=asciiToBase16(hex3.charCodeAt(hi));const n2=asciiToBase16(hex3.charCodeAt(hi+1));if(n1===void 0||n2===void 0){const char=hex3[hi]+hex3[hi+1];throw new RangeError('hex string expected, got non-hex character "'+char+'" at index '+hi)}array2[ai]=n1*16+n2}return array2}function utf8ToBytes3(str2){if(typeof str2!=="string")throw new TypeError("string expected");const encoded=new TextEncoder().encode(str2);try{return new Uint8Array(encoded)}finally{clean4(encoded)}}function concatBytes(...arrays){let sum2=0;for(let i=0;i<arrays.length;i++){const a=arrays[i];abytes4(a);sum2+=a.length}const res=new Uint8Array(sum2);for(let i=0,pad4=0;i<arrays.length;i++){const a=arrays[i];res.set(a,pad4);pad4+=a.length}return res}function checkOpts(defaults,opts,title="opts"){aopts(defaults,"defaults");if(opts!==void 0)aopts(opts,title);const merged=Object.assign(Object.create(null),defaults,opts);return merged}function createHasher4(hashCons,info2={}){if(typeof hashCons!=="function")throw new TypeError('"hashCons" expected function, got type='+typeof hashCons);info2=checkOpts({},info2,"info");const hashC=(msg,opts)=>hashCons(opts).update(msg).digest();const tmp=hashCons(void 0);hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.canXOF=tmp.canXOF;hashC.create=opts=>hashCons(opts);Object.assign(hashC,info2);return Object.freeze(hashC)}function randomBytes3(bytesLength=32){anumber5(bytesLength,"bytesLength");const cr=typeof globalThis==="object"?globalThis.crypto:null;if(typeof cr?.getRandomValues!=="function")throw new Error("crypto.getRandomValues must be defined");if(bytesLength>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);return cr.getRandomValues(new Uint8Array(bytesLength))}var oidNist2=suffix=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,suffix])});function Chi3(a,b2,c){return a&b2^~a&c}function Maj3(a,b2,c){return a&b2^a&c^b2&c}var HashMD3=class{blockLen;outputLen;canXOF=false;padOffset;isLE;buffer;view;finished=false;length=0;pos=0;destroyed=false;constructor(blockLen,outputLen,padOffset,isLE3){this.blockLen=blockLen;this.outputLen=outputLen;this.padOffset=padOffset;this.isLE=isLE3;this.buffer=new Uint8Array(blockLen);this.view=createView3(this.buffer)}update(data){aexists4(this);abytes4(data);const{view,buffer,blockLen}=this;const len=data.length;let processed=false;for(let pos=0;pos<len;){const take=Math.min(blockLen-this.pos,len-pos);if(take===blockLen){const dataView=createView3(data);for(;blockLen<=len-pos;pos+=blockLen)this.process(dataView,pos);processed=true;continue}buffer.set(pos===0&&take===len?data:data.subarray(pos,pos+take),this.pos);this.pos+=take;pos+=take;if(this.pos===blockLen){this.process(view,0);this.pos=0;processed=true}}this.length+=data.length;if(processed)this.roundClean();return this}digestInto(out){aexists4(this);aoutput4(out,this);this.finished=true;const{buffer,view,blockLen,isLE:isLE3}=this;let{pos}=this;buffer[pos++]=128;buffer.fill(0,pos);if(this.padOffset>blockLen-pos){this.process(view,0);buffer.fill(0)}setU64FromNum(view,blockLen-8,this.length*8,isLE3);this.process(view,0);this.roundClean();const oview=out===buffer?view:createView3(out);const len=this.outputLen;const outLen=len/4;const state=this.get();if(len%4||outLen>state.length)throw new Error("invalid outputLen");for(let i=0;i<outLen;i++)oview.setUint32(4*i,state[i],isLE3)}digest(){const{buffer,outputLen}=this;this.digestInto(buffer);const res=buffer.slice(0,outputLen);this.destroy();return res}_cloneIntoMeta(to){const{buffer,length,finished,destroyed,pos}=this;to.destroyed=destroyed;to.finished=finished;to.length=length;to.pos=pos;if(pos)to.buffer.set(buffer);return to}clone(){return this._cloneInto()}};var SHA256_IV3=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var SHA512_IV3=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var SHA256_K3=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]);var SHA256_W3=new Uint32Array(64);var SHA2_32B2=class extends HashMD3{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(outputLen,IV){super(64,outputLen,8,false);this.A=IV[0]|0;this.B=IV[1]|0;this.C=IV[2]|0;this.D=IV[3]|0;this.E=IV[4]|0;this.F=IV[5]|0;this.G=IV[6]|0;this.H=IV[7]|0}get(){const{A:A2,B:B2,C,D:D2,E:E2,F,G:G2,H:H2}=this;return[A2,B2,C,D2,E2,F,G2,H2]}set(A2,B2,C,D2,E2,F,G2,H2){this.A=A2|0;this.B=B2|0;this.C=C|0;this.D=D2|0;this.E=E2|0;this.F=F|0;this.G=G2|0;this.H=H2|0}_cloneInto(to){(to||=new this.constructor).set(...this.get());return this._cloneIntoMeta(to)}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W3[i]=view.getUint32(offset,false);for(let i=16;i<64;i++){const W15=SHA256_W3[i-15];const W2=SHA256_W3[i-2];const s0=rotr3(W15,7)^rotr3(W15,18)^W15>>>3;const s1=rotr3(W2,17)^rotr3(W2,19)^W2>>>10;SHA256_W3[i]=s1+SHA256_W3[i-7]+s0+SHA256_W3[i-16]|0}let{A:A2,B:B2,C,D:D2,E:E2,F,G:G2,H:H2}=this;for(let i=0;i<64;i++){const sigma1=rotr3(E2,6)^rotr3(E2,11)^rotr3(E2,25);const T12=H2+sigma1+Chi3(E2,F,G2)+SHA256_K3[i]+SHA256_W3[i]|0;const sigma0=rotr3(A2,2)^rotr3(A2,13)^rotr3(A2,22);const T2=sigma0+Maj3(A2,B2,C)|0;H2=G2;G2=F;F=E2;E2=D2+T12|0;D2=C;C=B2;B2=A2;A2=T12+T2|0}A2=A2+this.A|0;B2=B2+this.B|0;C=C+this.C|0;D2=D2+this.D|0;E2=E2+this.E|0;F=F+this.F|0;G2=G2+this.G|0;H2=H2+this.H|0;this.set(A2,B2,C,D2,E2,F,G2,H2)}roundClean(){clean4(SHA256_W3)}destroy(){this.destroyed=true;this.set(0,0,0,0,0,0,0,0);clean4(this.buffer)}};var _SHA2562=class extends SHA2_32B2{constructor(){super(32,SHA256_IV3)}};var K512=(()=>split3(["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(n=>BigInt(n))))();var SHA512_Kh=(()=>K512[0])();var SHA512_Kl=(()=>K512[1])();var SHA512_W_H=new Uint32Array(80);var SHA512_W_L=new Uint32Array(80);var SHA2_64B=class extends HashMD3{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(outputLen,IV){super(128,outputLen,16,false);this.Ah=IV[0]|0;this.Al=IV[1]|0;this.Bh=IV[2]|0;this.Bl=IV[3]|0;this.Ch=IV[4]|0;this.Cl=IV[5]|0;this.Dh=IV[6]|0;this.Dl=IV[7]|0;this.Eh=IV[8]|0;this.El=IV[9]|0;this.Fh=IV[10]|0;this.Fl=IV[11]|0;this.Gh=IV[12]|0;this.Gl=IV[13]|0;this.Hh=IV[14]|0;this.Hl=IV[15]|0}get(){const{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0;this.Al=Al|0;this.Bh=Bh|0;this.Bl=Bl|0;this.Ch=Ch|0;this.Cl=Cl|0;this.Dh=Dh|0;this.Dl=Dl|0;this.Eh=Eh|0;this.El=El|0;this.Fh=Fh|0;this.Fl=Fl|0;this.Gh=Gh|0;this.Gl=Gl|0;this.Hh=Hh|0;this.Hl=Hl|0}_cloneInto(to){(to||=new this.constructor).set(...this.get());return this._cloneIntoMeta(to)}process(view,offset){for(let i=0;i<16;i++,offset+=4){SHA512_W_H[i]=view.getUint32(offset);SHA512_W_L[i]=view.getUint32(offset+=4)}for(let i=16;i<80;i++){const W15h=SHA512_W_H[i-15]|0;const W15l=SHA512_W_L[i-15]|0;const s0h=rotrSH(W15h,W15l,1)^rotrSH(W15h,W15l,8)^shrSH(W15h,W15l,7);const s0l=rotrSL(W15h,W15l,1)^rotrSL(W15h,W15l,8)^shrSL(W15h,W15l,7);const W2h=SHA512_W_H[i-2]|0;const W2l=SHA512_W_L[i-2]|0;const s1h=rotrSH(W2h,W2l,19)^rotrBH(W2h,W2l,61)^shrSH(W2h,W2l,6);const s1l=rotrSL(W2h,W2l,19)^rotrBL(W2h,W2l,61)^shrSL(W2h,W2l,6);const SUMl=add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]);const SUMh=add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=SUMh|0;SHA512_W_L[i]=SUMl|0}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){const sigma1h=rotrSH(Eh,El,14)^rotrSH(Eh,El,18)^rotrBH(Eh,El,41);const sigma1l=rotrSL(Eh,El,14)^rotrSL(Eh,El,18)^rotrBL(Eh,El,41);const CHIh=Eh&Fh^~Eh&Gh;const CHIl=El&Fl^~El&Gl;const T1ll=add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]);const T1h=add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]);const T1l=T1ll|0;const sigma0h=rotrSH(Ah,Al,28)^rotrBH(Ah,Al,34)^rotrBH(Ah,Al,39);const sigma0l=rotrSL(Ah,Al,28)^rotrBL(Ah,Al,34)^rotrBL(Ah,Al,39);const MAJh=Ah&Bh^Ah&Ch^Bh&Ch;const MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0;Hl=Gl|0;Gh=Fh|0;Gl=Fl|0;Fh=Eh|0;Fl=El|0;({h:Eh,l:El}=add(Dh|0,Dl|0,T1h|0,T1l|0));Dh=Ch|0;Dl=Cl|0;Ch=Bh|0;Cl=Bl|0;Bh=Ah|0;Bl=Al|0;const All=add3L(T1l,sigma0l,MAJl);Ah=add3H(All,T1h,sigma0h,MAJh);Al=All|0}({h:Ah,l:Al}=add(this.Ah|0,this.Al|0,Ah|0,Al|0));({h:Bh,l:Bl}=add(this.Bh|0,this.Bl|0,Bh|0,Bl|0));({h:Ch,l:Cl}=add(this.Ch|0,this.Cl|0,Ch|0,Cl|0));({h:Dh,l:Dl}=add(this.Dh|0,this.Dl|0,Dh|0,Dl|0));({h:Eh,l:El}=add(this.Eh|0,this.El|0,Eh|0,El|0));({h:Fh,l:Fl}=add(this.Fh|0,this.Fl|0,Fh|0,Fl|0));({h:Gh,l:Gl}=add(this.Gh|0,this.Gl|0,Gh|0,Gl|0));({h:Hh,l:Hl}=add(this.Hh|0,this.Hl|0,Hh|0,Hl|0));this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){clean4(SHA512_W_H,SHA512_W_L)}destroy(){this.destroyed=true;clean4(this.buffer);this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var _SHA512=class extends SHA2_64B{constructor(){super(64,SHA512_IV3)}};var sha2565=createHasher4(()=>new _SHA2562,oidNist2(1));var sha5122=createHasher4(()=>new _SHA512,oidNist2(3));var freeze=fn=>Object.freeze(fn());function isBytes6(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in a&&a.BYTES_PER_ELEMENT===1}function abytes5(b2){if(!isBytes6(b2))throw new TypeError("Uint8Array expected")}function afn2(input){if(typeof input!=="function")throw new TypeError("function expected");return true}function astr2(label,input){if(typeof input!=="string")throw new TypeError(`${label}: string expected`);return true}function anumber6(n,title="number"){if(typeof n!=="number")throw new TypeError(`${title}: expected number, got ${typeof n}`);if(!Number.isSafeInteger(n))throw new RangeError(`${title}: expected safe integer, got ${n}`)}function chain2(...args){const id=a=>a;const wrap=(a,b2)=>c=>a(b2(c));const encode2=args.map(x2=>x2.encode).reduceRight(wrap,id);const decode2=args.map(x2=>x2.decode).reduce(wrap,id);return{encode:encode2,decode:decode2}}var powers2=(()=>{let res=[];for(let i=0;i<40;i++)res.push(2**i);return res})();var asciiDecoder=(()=>{try{const decoder3=new TextDecoder;return decoder3.decode(Uint8Array.of(65,48,43,127))==="A0+\x7F"?decoder3:void 0}catch(e17){return void 0}})();var B2S_CHUNK=8192;function charcodesToString(codes){const len=codes.length;if(asciiDecoder!==void 0&&len>=12)return asciiDecoder.decode(codes);if(len<=B2S_CHUNK)return String.fromCharCode.apply(null,codes);let res="";for(let i=0;i<len;i+=B2S_CHUNK)res+=String.fromCharCode.apply(null,codes.subarray(i,i+B2S_CHUNK));return res}function radix22(bits){anumber6(bits);if(bits<=0||bits>8)throw new RangeError("radix2: bits should be in (0..8]");const mask=powers2[bits]-1;return{encode:bytes=>{abytes5(bytes);const len=bytes.length;const res=new Uint8Array(Math.ceil(len*8/bits));let carry2=0;let pos=0;let j2=0;for(let i=0;i<len;){if(i+2<len){carry2=carry2<<24|bytes[i]<<16|bytes[i+1]<<8|bytes[i+2];pos+=24;i+=3}else{carry2=(carry2<<8|bytes[i])&65535;pos+=8;i++}for(;;){pos-=bits;res[j2++]=carry2>>pos&mask;if(pos<bits)break}}if(pos>0)res[j2]=carry2<<bits-pos&mask;return res},decode:digits=>{const len=digits.length;const res=new Uint8Array(Math.floor(len*bits/8));let carry2=0;let pos=0;let j2=0;for(let i=0;i<len;i++){carry2=(carry2<<bits|digits[i])&65535;pos+=bits;for(;pos>=8;pos-=8)res[j2++]=carry2>>pos-8&255}carry2=carry2<<8-pos&255;if(pos>=bits)throw new Error("Excess padding");if(carry2>0)throw new Error(`Non-zero padding: ${carry2}`);return res}}}function alphabet2(letters,aliases){const len=letters.length;if(len>128)throw new Error("alphabet: max 128 letters");const encTable=new Uint8Array(len);const decTable=new Int8Array(128).fill(-1);for(let i=0;i<len;i++){const code=letters.charCodeAt(i);if(letters.codePointAt(i)!==code||code>127)throw new Error("alphabet: single-char ASCII letters only");encTable[i]=code;decTable[code]=i}if(aliases!==void 0){for(const alias of Object.keys(aliases)){const code=alias.charCodeAt(0);const target=decTable[aliases[alias].charCodeAt(0)];if(alias.length!==1||code>127||target===void 0||target===-1)throw new Error(`alphabet: invalid alias ${alias}`);decTable[code]=target}}return{encode:digits=>{const codes=new Uint8Array(digits.length);for(let i=0;i<digits.length;i++){const d=digits[i];const code=encTable[d];if(code===void 0)throw new Error(`alphabet.encode: invalid digit ${d}`);codes[i]=code}return charcodesToString(codes)},decode:input=>{astr2("decode",input);const slen=input.length;const digits=new Uint8Array(slen);for(let i=0;i<slen;i++){const code=input.charCodeAt(i);const digit=code<128?decTable[code]:-1;if(digit===-1)throw new Error(`Unknown letter "${input[i]}". Allowed: ${letters}`);digits[i]=digit}return digits}}}function padding2(bits,chr="="){anumber6(bits);astr2("padding",chr);return{encode(data){while(data.length*bits%8)data+=chr;return data},decode(input){astr2("decode",input);let end=input.length;if(end*bits%8)throw new Error("padding: invalid length");for(;end>0&&input[end-1]===chr;end--){const byte=(end-1)*bits;if(byte%8===0)throw new Error("padding: excess padding")}return input.slice(0,end)}}}function checksum4(len,fn){anumber6(len);if(len<=0)throw new RangeError(`checksum length must be positive: ${len}`);afn2(fn);const _fn=fn;return{encode(data){abytes5(data);const sum2=_fn(data).slice(0,len);const res=new Uint8Array(data.length+len);res.set(data);res.set(sum2,data.length);return res},decode(data){abytes5(data);const payload=data.slice(0,-len);const oldChecksum=data.slice(-len);const newChecksum=_fn(payload).slice(0,len);for(let i=0;i<len;i++)if(newChecksum[i]!==oldChecksum[i])throw new Error("Invalid checksum");return payload}}}var hasBase64Builtin=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")();var ASCII_WHITESPACE=/[\t\n\f\r ]/;var decodeBase64Builtin=(s,isUrl)=>{astr2("base64",s);const alphabet3=isUrl?"base64url":"base64";if(s.length>0&&ASCII_WHITESPACE.test(s))throw new Error("invalid base64");return Uint8Array.fromBase64(s,{alphabet:alphabet3,lastChunkHandling:"strict"})};var base64Fallback=freeze(()=>chain2(radix22(6),alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding2(6)));var base64urlFallback=freeze(()=>chain2(radix22(6),alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),padding2(6)));var base643=freeze(()=>hasBase64Builtin?{encode(b2){abytes5(b2);return b2.toBase64()},decode(s){return decodeBase64Builtin(s,false)}}:base64Fallback);var base64nopad=freeze(()=>chain2(radix22(6),alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")));var base64url3=freeze(()=>hasBase64Builtin?{encode(b2){abytes5(b2);return b2.toBase64({alphabet:"base64url"})},decode(s){return decodeBase64Builtin(s,true)}}:base64urlFallback);var base64urlnopad=freeze(()=>chain2(radix22(6),alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")));var B58_GROUP=656356768;var RADIX_BASE_N_MAX_LENGTH=65536;var BASE_N_MAX_BYTES=2048;var BASE_N_MAX_CHARS=4096;var radixBaseN=(BASE,GROUP)=>({encode:bytes=>{abytes5(bytes);const blen=bytes.length;if(blen===0)return new Uint8Array(0);if(blen>=RADIX_BASE_N_MAX_LENGTH)throw new Error("invalid length");let zeros=0;while(zeros<blen-1&&bytes[zeros]===0)zeros++;const nlimbs=Math.ceil(blen/2);const limbs=new Uint16Array(nlimbs);const odd=blen&1;if(odd)limbs[0]=bytes[0];for(let i=odd,j3=odd;i<blen;i+=2,j3++)limbs[j3]=bytes[i]<<8|bytes[i+1];const groups=[];let pos=0;while(pos<nlimbs){let carry2=0;for(let i=pos;i<nlimbs;i++){const cur=carry2*65536+limbs[i];const q2=Math.floor(cur/GROUP);carry2=cur-q2*GROUP;limbs[i]=q2;if(q2===0&&i===pos)pos++}groups.push(carry2)}const top=groups.length-1;let sig=top*5;for(let v=groups[top];;v=Math.floor(v/BASE)){sig++;if(v<BASE)break}const res=new Uint8Array(zeros+sig);let j2=res.length-1;for(let g=0;g<top;g++){let v=groups[g];for(let k2=0;k2<5;k2++){res[j2--]=v%BASE;v=Math.floor(v/BASE)}}for(let v=groups[top];j2>=zeros;v=Math.floor(v/BASE))res[j2--]=v%BASE;return res},decode:digits=>{abytes5(digits);const dlen=digits.length;if(dlen===0)return new Uint8Array(0);if(dlen>=RADIX_BASE_N_MAX_LENGTH)throw new Error("invalid length");let zeros=0;while(zeros<dlen-1&&digits[zeros]===0)zeros++;const limbs=new Uint16Array(Math.ceil(dlen*6/16)+1);let used=0;let i=0;let group=dlen%5||5;while(i<dlen){let gval=0;let factor=1;for(const end=i+group;i<end;i++){const d=digits[i];if(d>=BASE)throw new Error(`invalid integer: ${d}`);gval=gval*BASE+d;factor*=BASE}group=5;let carry2=gval;for(let k2=0;k2<used;k2++){const cur=limbs[k2]*factor+carry2;carry2=Math.floor(cur/65536);limbs[k2]=cur-carry2*65536}for(;carry2>0;carry2=Math.floor(carry2/65536))limbs[used++]=carry2%65536}const valueBytes=used===0?1:used*2-(limbs[used-1]<256?1:0);const res=new Uint8Array(zeros+valueBytes);let j2=res.length-1;for(let k2=0;k2<used;k2++){const limb=limbs[k2];res[j2--]=limb&255;if(j2>=zeros)res[j2--]=limb>>8}return res}});var genBaseN=(radix3,abc)=>{const letters=alphabet2(abc);return{encode(bytes){abytes5(bytes);if(bytes.length>BASE_N_MAX_BYTES)throw new Error("invalid length");return letters.encode(radix3.encode(bytes))},decode(str2){astr2("baseN.decode",str2);if(str2.length>BASE_N_MAX_CHARS)throw new Error("invalid length");return radix3.decode(letters.decode(str2))}}};var radix58=radixBaseN(58,B58_GROUP);var genBase58=abc=>genBaseN(radix58,abc);var base58=freeze(()=>genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"));var createBase58check=sha2566=>{afn2(sha2566);const _sha256=sha2566;return chain2(checksum4(4,data=>_sha256(_sha256(data))),base58)};function aarray(item,title,inner=()=>{}){if(!Array.isArray(item))throw new TypeError(`"${title}" expected array, got type=${typeof item}`);for(let i=0;i<item.length;i++)inner(item[i],`${title}[${i}]`);return item}var abytes6=(value,length,title)=>abytes4(value,length,title);var anumber7=anumber5;function astring(value,title=""){if(typeof value!=="string"){const prefix=title&&`"${title}" `;throw new TypeError(prefix+"expected string, got type="+typeof value)}return value}function aobject2(value,title="object"){if(value===null||typeof value!=="object"||Array.isArray(value))throw new TypeError(title==="object"?"expected valid options object":`"${title}" expected object, got type=${typeof value}`);return value}function afunction(value,title){if(typeof value!=="function")throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);return value}var bytesToHex3=bytesToHex2;var concatBytes2=(...arrays)=>concatBytes(...arrays);var hexToBytes3=hex3=>hexToBytes2(hex3);var isBytes7=isBytes5;var randomBytes4=bytesLength=>randomBytes3(bytesLength);var _0n3=BigInt(0);var _1n3=BigInt(1);var atitle2=title=>title?`"${title}" `:"";function abool(value,title=""){if(typeof value!=="boolean")throw new TypeError(atitle2(title)+"expected boolean, got type="+typeof value);return value}function abignumber(n){if(typeof n==="bigint"){if(!isPosBig(n))throw new RangeError("positive bigint expected, got "+n)}else anumber7(n);return n}function asafenumber(value,title=""){if(typeof value!=="number"){const prefix=title&&`"${title}" `;throw new TypeError(prefix+"expected number, got type="+typeof value)}if(!Number.isSafeInteger(value)){const prefix=title&&`"${title}" `;throw new RangeError(prefix+"expected safe integer, got "+value)}}function numberToHexUnpadded(num){const hex3=abignumber(num).toString(16);return hex3.length&1?"0"+hex3:hex3}function hexToNumber(hex3){if(typeof hex3!=="string")throw new TypeError("hex string expected, got "+typeof hex3);return hex3===""?_0n3:BigInt("0x"+hex3)}function bytesToNumberBE(bytes){return hexToNumber(bytesToHex2(bytes))}function bytesToNumberLE(bytes){return hexToNumber(bytesToHex2(copyBytes(abytes4(bytes)).reverse()))}function numberToBytesBE(n,len){anumber5(len);if(len===0)throw new Error("zero output length is invalid");n=abignumber(n);const expectedLen=len*2;const hex3=n.toString(16);if(hex3.length>expectedLen)throw new RangeError("number is too large");return hexToBytes2(hex3.padStart(expectedLen,"0"))}function numberToBytesLE(n,len){return numberToBytesBE(n,len).reverse()}function equalBytes2(a,b2){a=abytes6(a);b2=abytes6(b2);if(a.length!==b2.length)return false;let diff=0;for(let i=0;i<a.length;i++)diff|=a[i]^b2[i];return diff===0}function copyBytes(bytes){return Uint8Array.from(abytes6(bytes))}function isPosBig(n){return typeof n==="bigint"&&_0n3<=n}function inRange(n,min,max){return isPosBig(n)&&isPosBig(min)&&isPosBig(max)&&min<=n&&n<max}function aInRange(title,n,min,max){if(!inRange(n,min,max))throw new RangeError("expected valid "+title+": "+min+" <= n < "+max+", got "+n)}function bitLen(n){if(n<_0n3)throw new Error("expected non-negative bigint, got "+n);return n===_0n3?0:n.toString(2).length}var bitMask=n=>{asafenumber(n,"n");return(_1n3<<BigInt(n))-_1n3};function createHmacDrbg(hashLen,qByteLen,hmacFn){anumber5(hashLen,"hashLen");anumber5(qByteLen,"qByteLen");if(typeof hmacFn!=="function")throw new TypeError("hmacFn must be a function");const u8n=len=>new Uint8Array(len);const NULL=Uint8Array.of();const byte0=Uint8Array.of(0);const byte1=Uint8Array.of(1);const _maxDrbgIters=1e3;let v=u8n(hashLen);let k2=u8n(hashLen);let i=0;const reset=()=>{v.fill(1);k2.fill(0);i=0};const h=(...msgs)=>hmacFn(k2,concatBytes2(v,...msgs));const reseed=(seed=NULL)=>{k2=h(byte0,seed);v=h();if(seed.length===0)return;k2=h(byte1,seed);v=h()};const gen3=()=>{if(i++>=_maxDrbgIters)throw new Error("drbg: tried max amount of iterations");let len=0;const out=[];while(len<qByteLen){v=h();const sl=v.slice();out.push(sl);len+=v.length}return concatBytes2(...out)};const genUntil=(seed,pred)=>{reset();reseed(seed);let res=void 0;while((res=pred(gen3()))===void 0)reseed();reset();return res};return genUntil}function validateObject(object2,fields={},optFields={},title="object"){aobject2(object2,title);aobject2(fields,"fields");aobject2(optFields,"optFields");function checkField(fieldName,expectedType,isOpt){const label=title==="object"?`param "${String(fieldName)}"`:`"${title}.${String(fieldName)}"`;const val=object2[fieldName];if(!Object.hasOwn(object2,fieldName)&&(isOpt?val!==void 0:expectedType!=="function")){throw new TypeError(`${label} is invalid: expected own property`)}if(isOpt&&val===void 0)return;const current=typeof val;if(current!==expectedType||val===null)throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`)}const iter=(f,isOpt)=>Object.entries(f).forEach(([k2,v])=>checkField(k2,v,isOpt));iter(fields,false);iter(optFields,true)}var _0n4=BigInt(0);var _1n4=BigInt(1);var _2n3=BigInt(2);var _3n=BigInt(3);var _4n=BigInt(4);var _5n=BigInt(5);var _7n3=BigInt(7);var _8n=BigInt(8);var _9n=BigInt(9);var _15n=BigInt(15);var _16n=BigInt(16);var POW_WINDOWED_MIN=BigInt("0x10000000000000000");function mod(a,b2){if(b2<=_0n4)throw new Error("mod: expected positive modulus, got "+b2);const result=a%b2;return result>=_0n4?result:b2+result}function pow(num,power,modulo){if(modulo<=_1n4)throw new Error("pow: expected modulus > 1, got "+modulo);if(typeof power!=="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof power);if(power<_0n4)throw new Error("invalid exponent, negatives unsupported");if(power===_0n4)return _1n4;if(power===_1n4)return num;let d=num%modulo;if(d<_0n4)d+=modulo;if(power<POW_WINDOWED_MIN){let p2=_1n4;while(power>_0n4){if(power&_1n4)p2=p2*d%modulo;d=d*d%modulo;power>>=_1n4}return p2}const digits=[];while(power>_0n4){digits.push(Number(power&_15n));power>>=_4n}const table=new Array(16);table[0]=_1n4;table[1]=d;for(let i=2;i<16;i++)table[i]=table[i-1]*d%modulo;let p=table[digits[digits.length-1]];for(let w=digits.length-2;w>=0;w--){p=p*p%modulo;p=p*p%modulo;p=p*p%modulo;p=p*p%modulo;const digit=digits[w];if(digit!==0)p=p*table[digit]%modulo}return p}function pow2(x2,power,modulo){if(modulo<=_1n4)throw new Error("pow2: expected modulus > 1, got "+modulo);if(power<_0n4)throw new Error("pow2: expected non-negative exponent, got "+power);let res=x2;while(power-- >_0n4){res*=res;res%=modulo}return res}function invert(number4,modulo){if(number4===_0n4)throw new Error("invert: expected non-zero number");if(modulo<=_1n4)throw new Error("invert: expected modulus > 1, got "+modulo);let a=mod(number4,modulo);let b2=modulo;let x2=_0n4,u=_1n4;while(a!==_0n4){const q2=b2/a;const r=b2-a*q2;const m=x2-u*q2;b2=a,a=r,x2=u,u=m}const gcd2=b2;if(gcd2!==_1n4)throw new Error("invert: does not exist");return mod(x2,modulo)}function invertCt(a,prime){if(prime<=_1n4)throw new Error("invertCt: expected prime modulus > 1, got "+prime);const an=mod(a,prime);if(an===_0n4)throw new Error("invertCt: expected non-zero number");const inverse=pow(an,prime-_2n3,prime);if(mod(an*inverse,prime)!==_1n4)throw new Error("invertCt: does not exist");return inverse}function assertIsSquare(Fp,root,n){const F=Fp;if(!F.eql(F.sqr(root),n))throw new Error("Cannot find square root")}function aoddModulus(order,fnName){if((order&_1n4)===_0n4)throw new Error(fnName+": expected odd modulus, got "+order)}function sqrt3mod4(Fp,n){const F=Fp;const p1div4=(F.ORDER+_1n4)/_4n;const root=F.pow(n,p1div4);assertIsSquare(F,root,n);return root}function sqrt5mod8(Fp,n){const F=Fp;const p5div8=(F.ORDER-_5n)/_8n;const n2=F.mul(n,_2n3);const v=F.pow(n2,p5div8);const nv=F.mul(n,v);const i=F.mul(F.mul(nv,_2n3),v);const root=F.mul(nv,F.sub(i,F.ONE));assertIsSquare(F,root,n);return root}function sqrt9mod16(P2){const Fp_=Field(P2);const tn=tonelliShanks(P2);const c1=tn(Fp_,Fp_.neg(Fp_.ONE));const c2=tn(Fp_,c1);const c3=tn(Fp_,Fp_.neg(c1));const c4=(P2+_7n3)/_16n;return((Fp,n)=>{const F=Fp;let tv1=F.pow(n,c4);let tv2=F.mul(tv1,c1);const tv3=F.mul(tv1,c2);const tv4=F.mul(tv1,c3);const e1=F.eql(F.sqr(tv2),n);const e22=F.eql(F.sqr(tv3),n);tv1=F.cmov(tv1,tv2,e1);tv2=F.cmov(tv4,tv3,e22);const e32=F.eql(F.sqr(tv2),n);const root=F.cmov(tv1,tv2,e32);assertIsSquare(F,root,n);return root})}function tonelliShanks(P2){if(P2<_3n)throw new Error("sqrt is not defined for small field");aoddModulus(P2,"tonelliShanks");let Q=P2-_1n4;let S2=0;while(Q%_2n3===_0n4){Q/=_2n3;S2++}let Z2=_2n3;const _Fp=Field(P2);while(FpLegendre(_Fp,Z2)===1){if(Z2++>1e3)throw new Error("Cannot find square root: probably non-prime P")}if(S2===1)return sqrt3mod4;let cc=_Fp.pow(Z2,Q);const Q1div2=(Q+_1n4)/_2n3;return function tonelliSlow(Fp,n){const F=Fp;if(F.is0(n))return n;if(FpLegendre(F,n)!==1)throw new Error("Cannot find square root");let M=S2;let c=F.mul(F.ONE,cc);let t2=F.pow(n,Q);let R=F.pow(n,Q1div2);while(!F.eql(t2,F.ONE)){if(F.is0(t2))throw new Error("Cannot find square root: probably non-prime P");let i=1;let t_tmp=F.sqr(t2);while(!F.eql(t_tmp,F.ONE)){i++;t_tmp=F.sqr(t_tmp);if(i===M)throw new Error("Cannot find square root")}const exponent=_1n4<<BigInt(M-i-1);const b2=F.pow(c,exponent);M=i;c=F.sqr(b2);t2=F.mul(t2,c);R=F.mul(R,b2)}return R}}function FpSqrt(P2){aoddModulus(P2,"Fp.sqrt");if(P2%_4n===_3n)return sqrt3mod4;if(P2%_8n===_5n)return sqrt5mod8;if(P2%_16n===_9n)return sqrt9mod16(P2);return tonelliShanks(P2)}var FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(field){aobject2(field,"field");if(typeof field.ORDER!=="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof field.ORDER);asafenumber(field.BYTES,"BYTES");asafenumber(field.BITS,"BITS");for(const name of FIELD_FIELDS)afunction(field[name],"field."+name);if(field.BYTES<1||field.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(field.ORDER<=_1n4)throw new Error("invalid field: expected ORDER > 1, got "+field.ORDER);return field}function FpInvertBatch(Fp,nums,passZero=false){validateField(Fp);aarray(nums,"nums");abool(passZero,"passZero");const F=Fp;const inverted=new Array(nums.length).fill(passZero?F.ZERO:void 0);const multipliedAcc=nums.reduce((acc,num,i)=>{if(F.is0(num))return acc;inverted[i]=acc;return F.mul(acc,num)},F.ONE);const invertedAcc=F.inv(multipliedAcc);nums.reduceRight((acc,num,i)=>{if(F.is0(num))return acc;inverted[i]=F.mul(acc,inverted[i]);return F.mul(acc,num)},invertedAcc);return inverted}function FpLegendre(Fp,n){validateField(Fp);const F=Fp;aoddModulus(F.ORDER,"FpLegendre");const p1mod2=(F.ORDER-_1n4)/_2n3;const powered=F.pow(n,p1mod2);const yes=F.eql(powered,F.ONE);const zero=F.eql(powered,F.ZERO);const no=F.eql(powered,F.neg(F.ONE));if(!yes&&!zero&&!no)throw new Error("invalid Legendre symbol result");return yes?1:zero?0:-1}function nLength(n,nBitLength){if(nBitLength!==void 0)anumber7(nBitLength);if(n<=_0n4)throw new Error("invalid n length: expected positive n, got "+n);if(nBitLength!==void 0&&nBitLength<1)throw new Error("invalid n length: expected positive bit length, got "+nBitLength);const bits=bitLen(n);if(nBitLength!==void 0&&nBitLength<bits)throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);const _nBitLength=nBitLength!==void 0?nBitLength:bits;const nByteLength=Math.ceil(_nBitLength/8);return{nBitLength:_nBitLength,nByteLength}}var FIELD_SQRT=new WeakMap;var _Field=class{ORDER;BITS;BYTES;isLE;ZERO=_0n4;ONE=_1n4;_lengths;_mod;constructor(ORDER,opts={}){if(ORDER<=_1n4)throw new Error("invalid field: expected ORDER > 1, got "+ORDER);let _nbitLength=void 0;this.isLE=false;if(opts!=null&&typeof opts==="object"){if(typeof opts.BITS==="number")_nbitLength=opts.BITS;if(typeof opts.sqrt==="function")Object.defineProperty(this,"sqrt",{value:opts.sqrt,enumerable:true});if(typeof opts.isLE==="boolean")this.isLE=opts.isLE;if(opts.allowedLengths)this._lengths=Object.freeze(opts.allowedLengths.slice());if(typeof opts.modFromBytes==="boolean")this._mod=opts.modFromBytes}const{nBitLength,nByteLength}=nLength(ORDER,_nbitLength);if(nByteLength>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=ORDER;this.BITS=nBitLength;this.BYTES=nByteLength;Object.freeze(this)}create(num){return mod(num,this.ORDER)}isValid(num){if(typeof num!=="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof num);return _0n4<=num&&num<this.ORDER}is0(num){return num===_0n4}isValidNot0(num){return!this.is0(num)&&this.isValid(num)}isOdd(num){return(num&_1n4)===_1n4}neg(num){return mod(-num,this.ORDER)}eql(lhs,rhs){return lhs===rhs}sqr(num){return mod(num*num,this.ORDER)}add(lhs,rhs){return mod(lhs+rhs,this.ORDER)}sub(lhs,rhs){return mod(lhs-rhs,this.ORDER)}mul(lhs,rhs){return mod(lhs*rhs,this.ORDER)}pow(num,power){return pow(num,power,this.ORDER)}div(lhs,rhs){return mod(lhs*invert(rhs,this.ORDER),this.ORDER)}sqrN(num){return num*num}addN(lhs,rhs){return lhs+rhs}subN(lhs,rhs){return lhs-rhs}mulN(lhs,rhs){return lhs*rhs}inv(num){return invert(num,this.ORDER)}sqrt(num){let sqrt=FIELD_SQRT.get(this);if(!sqrt)FIELD_SQRT.set(this,sqrt=FpSqrt(this.ORDER));return sqrt(this,num)}toBytes(num){return this.isLE?numberToBytesLE(num,this.BYTES):numberToBytesBE(num,this.BYTES)}fromBytes(bytes,skipValidation=false){abytes6(bytes);const{_lengths:allowedLengths,BYTES,isLE:isLE3,ORDER,_mod:modFromBytes}=this;if(allowedLengths){if(bytes.length<1||!allowedLengths.includes(bytes.length)||bytes.length>BYTES){throw new Error("Field.fromBytes: expected "+allowedLengths+" bytes, got "+bytes.length)}const padded=new Uint8Array(BYTES);padded.set(bytes,isLE3?0:padded.length-bytes.length);bytes=padded}if(bytes.length!==BYTES)throw new Error("Field.fromBytes: expected "+BYTES+" bytes, got "+bytes.length);let scalar=isLE3?bytesToNumberLE(bytes):bytesToNumberBE(bytes);if(modFromBytes)scalar=mod(scalar,ORDER);if(!skipValidation){if(!this.isValid(scalar))throw new Error("invalid field element: outside of range 0..ORDER")}return scalar}invertBatch(lst){return FpInvertBatch(this,lst,true)}cmov(a,b2,condition){abool(condition,"condition");return condition?b2:a}};function Field(ORDER,opts={}){Object.freeze(_Field.prototype);return new _Field(ORDER,opts)}function getFieldBytesLength(fieldOrder){if(typeof fieldOrder!=="bigint")throw new Error("field order must be bigint");if(fieldOrder<=_1n4)throw new Error("field order must be greater than 1");const bitLength=bitLen(fieldOrder-_1n4);return Math.ceil(bitLength/8)}function getMinHashLength(fieldOrder){const length=getFieldBytesLength(fieldOrder);return length+Math.ceil(length/2)}function mapHashToField(key,fieldOrder,isLE3=false){abytes6(key);const len=key.length;const fieldLen=getFieldBytesLength(fieldOrder);const minLen=Math.max(getMinHashLength(fieldOrder),16);if(len<minLen||len>1024)throw new Error("expected "+minLen+"-1024 bytes of input, got "+len);const num=isLE3?bytesToNumberLE(key):bytesToNumberBE(key);const reduced=mod(num,fieldOrder-_1n4)+_1n4;return isLE3?numberToBytesLE(reduced,fieldLen):numberToBytesBE(reduced,fieldLen)}var _0n5=BigInt(0);var _1n5=BigInt(1);var _4n2=BigInt(4);var BLIND_BYTES=16;var BLIND_BITS=128;var FW_WINDOW=5;var TABLE_BYTES_MAX=(()=>2**31)();function validatePointCons(Point2){const pc=Point2;if(typeof pc!=="function")throw new TypeError('"Point" expected constructor, got type='+typeof Point2);afunction(pc.fromAffine,"Point.fromAffine");afunction(pc.fromBytes,"Point.fromBytes");afunction(pc.fromHex,"Point.fromHex");aobject2(pc.BASE,"Point.BASE");aobject2(pc.ZERO,"Point.ZERO");validateField(pc.Fp);validateField(pc.Fn)}function normalizeZ(c,points){validatePointCons(c);validateMSMPoints(points,c);const invertedZs=FpInvertBatch(c.Fp,points.map(p=>p.Z));return points.map((p,i)=>c.fromAffine(p.toAffine(invertedZs[i])))}function validateW(W2,bits,min=1){if(!Number.isSafeInteger(W2)||W2<min||W2>bits)throw new Error("invalid window size, expected ["+min+".."+bits+"], got W="+W2)}function validateTableBytes(numPoints,fpBytes){const bytes=numPoints*(4*fpBytes+128);if(bytes>TABLE_BYTES_MAX)throw new Error("invalid window size: table would need ~"+Math.ceil(bytes/2**20)+" MiB, max "+TABLE_BYTES_MAX/2**20+" MiB")}function probeRandomBytes(randomBytes5,length){if(randomBytes5===void 0)return void 0;afunction(randomBytes5,"randomBytes");try{const probe=randomBytes5(length);if(!isBytes7(probe)||probe.length!==length)return void 0}catch{return void 0}return randomBytes5}function validateMSMPoints(points,c){aarray(points,"points");points.forEach((p,i)=>{if(!(p instanceof c))throw new Error("invalid point at index "+i)})}function validateMSMScalars(scalars,field,maxScalar){if(!Array.isArray(scalars))throw new Error("array of scalars expected");scalars.forEach((s,i)=>{const ok=maxScalar===void 0?field.isValid(s):isPosBig(s)&&s<maxScalar;if(!ok)throw new Error("invalid scalar at index "+i)})}var pointWindowSizes=new WeakMap;function getWindowSize(P2){return pointWindowSizes.get(P2)||1}function oddMultiples(p,size4){const dbl=p.double();const t2=[p];for(let j2=1;j2<size4;j2++)t2.push(t2[j2-1].add(dbl));return t2}function wnafDigits(n,W2){const size4=2**W2;const half=size4/2;const mask=BigInt(size4-1);const d=[];while(n>_0n5){let w=0;if(n&_1n5){w=Number(n&mask);if(w>=half)w-=size4;n-=BigInt(w)}d.push(w);n>>=_1n5}return d}function signedWindowDigits(n,W2,windows){const size4=2**W2;const half=size4/2;const mask=BigInt(size4-1);const shiftBy=BigInt(W2);const d=[];for(let w=0;w<windows;w++){let v=Number(n&mask);n>>=shiftBy;if(v>half){v-=size4;n+=_1n5}d.push(v)}if(n!==_0n5)throw new Error("invalid wnaf");return d}function wnafWalk(zero,tables,digits){let max=0;for(const d of digits)max=Math.max(max,d.length);let acc=zero;for(let bit=max-1;bit>=0;bit--){if(bit!==max-1)acc=acc.double();for(let i=0;i<digits.length;i++){const w=digits[i][bit];if(w){const item=tables[i][Math.abs(w)-1>>1];acc=acc.add(w<0?item.negate():item)}}}return acc}var ScalarMultiplier=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(Point2,randomBytes5){validatePointCons(Point2);this.randomBytes=probeRandomBytes(randomBytes5,BLIND_BYTES);this.Point=Point2;this.BASE=Point2.BASE;this.ZERO=Point2.ZERO;this.bits=Point2.Fn.BITS}buildWnafTable(point,W2,bits){const windows=Math.ceil(bits/W2)+1;const half=2**(W2-1);const comp=[];let base3=point;for(let w=0;w<windows;w++){let acc=base3;for(let i=0;i<half;i++){comp.push(acc);acc=acc.add(base3)}base3=comp[comp.length-1].double()}return{W:W2,bits,windows,comp}}wnafCachedCT(precomputes,n){const{W:W2,windows,comp}=precomputes;const half=2**(W2-1);const digits=signedWindowDigits(n,W2,windows);let p=this.ZERO;let f=this.BASE;for(let w=0;w<windows;w++){const digit=digits[w];const start=w*half;const idx=Math.abs(digit)-1;let sel=comp[start];for(let i=1;i<half;i++)sel=i===idx?comp[start+i]:sel;const neg=sel.negate();if(digit===0)f=f.add(comp[start]);else p=p.add(digit<0?neg:sel)}return{p,f}}getWnafPrecomputes(W2,point,bits,transform2){let entries=this.wnafPrecomputes.get(point);let comp=entries?.find(entry=>entry.W===W2&&entry.bits===bits);if(!comp){comp=this.buildWnafTable(point,W2,bits);if(typeof transform2==="function")comp={...comp,comp:transform2(comp.comp)};if(!entries){entries=[];this.wnafPrecomputes.set(point,entries)}entries.push(comp)}return comp}assertPoint(point){if(!(point instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof point)}validateMulInput(point,scalar){this.assertPoint(point);if(!inRange(scalar,_1n5,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(point,n,bits,transform2){const W2=getWindowSize(point);if(W2===1)return this.fixedWindowCT(point,n,bits);return this.wnafCachedCT(this.getWnafPrecomputes(W2,point,bits,transform2),n)}mulCT(point,scalar,transform2){this.validateMulInput(point,scalar);return this.runCT(point,scalar,this.bits,transform2)}mulCTBlinded(point,scalar,transform2){this.validateMulInput(point,scalar);if(this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");const bits=this.Point.Fn.BITS+BLIND_BITS;const blind=this.randomBytes(BLIND_BYTES);if(!isBytes7(blind)||blind.length!==BLIND_BYTES)throw new Error("randomBytes returned invalid byte array");blind[0]=blind[0]&63|128;const n=scalar+bytesToNumberBE(blind)*this.Point.Fn.ORDER;return this.runCT(point,n,bits,transform2)}fixedWindowCT(point,n,bits){const W2=FW_WINDOW;const size4=1<<W2;const mask=bitMask(W2);const table=new Array(size4);table[0]=this.ZERO;for(let i=1;i<size4;i++)table[i]=table[i-1].add(point);const windows=Math.ceil(bits/W2);let acc=this.ZERO;for(let window=windows-1;window>=0;window--){if(window!==windows-1)for(let d=0;d<W2;d++)acc=acc.double();const digit=Number(n>>BigInt(window*W2)&mask);let sel=table[0];for(let i=1;i<size4;i++)sel=i===digit?table[i]:sel;acc=acc.add(sel)}return{p:acc,f:acc}}shouldBlind(point,cofactor){if(this.randomBytes===void 0)return false;if(cofactor===_1n5)return true;if(point!==this.BASE)return false;if(this.baseCanBeBlinded===void 0)this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0();return this.baseCanBeBlinded}mulSecret(point,scalar,cofactor,transform2){return this.shouldBlind(point,cofactor)?this.mulCTBlinded(point,scalar,transform2):this.mulCT(point,scalar,transform2)}mulUnsafe(point,scalar,transform2){this.assertPoint(point);if(!isPosBig(scalar))throw new Error("invalid scalar");const W2=getWindowSize(point);if(W2===1||scalar>=this.Point.Fn.ORDER)return mulAddUnsafe(this.Point,[point],[scalar],true);const precomputes=this.getWnafPrecomputes(W2,point,this.bits,transform2);return this.wnafCachedCT(precomputes,scalar).p}setWindowSize(point,W2){this.assertPoint(point);validateW(W2,this.bits);const windows=Math.ceil((this.bits+BLIND_BITS)/W2)+1;validateTableBytes(windows*2**(W2-1),this.Point.Fp.BYTES);pointWindowSizes.set(point,W2);this.wnafPrecomputes.delete(point)}hasWindowSize(point){return getWindowSize(point)!==1}};function mulAddUnsafe(c,points,scalars,allowOversized=false){validatePointCons(c);validateMSMPoints(points,c);abool(allowOversized,"allowOversized");validateMSMScalars(scalars,c.Fn,allowOversized?c.Fn.ORDER**_4n2:void 0);if(points.length!==scalars.length)throw new Error("arrays of points and scalars must have equal length");const tables=points.map(p=>oddMultiples(p,4));const digits=scalars.map(n=>wnafDigits(n,4));return wnafWalk(c.ZERO,tables,digits)}function createField(order,field,isLE3){if(field){if(field.ORDER!==order)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");validateField(field);return field}else{return Field(order,{isLE:isLE3})}}function createCurveFields(type,CURVE,curveOpts={},FpFnLE){if(type!=="weierstrass"&&type!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(FpFnLE===void 0)FpFnLE=type==="edwards";if(!CURVE||typeof CURVE!=="object")throw new Error(`expected valid ${type} CURVE object`);validateObject(curveOpts);for(const p of["p","n","h"]){const val=CURVE[p];if(!(isPosBig(val)&&val!==_0n5))throw new Error(`CURVE.${p} must be positive bigint`)}const Fp=createField(CURVE.p,curveOpts.Fp,FpFnLE);const Fn2=createField(CURVE.n,curveOpts.Fn,FpFnLE);const _b=type==="weierstrass"?"b":"d";const params=["Gx","Gy","a",_b];for(const p of params){if(!Fp.isValid(CURVE[p]))throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`)}CURVE=Object.freeze(Object.assign({},CURVE));return{CURVE,Fp,Fn:Fn2}}function createKeygen(randomSecretKey,getPublicKey){return function keygen(seed){const secretKey=randomSecretKey(seed);return{secretKey,publicKey:getPublicKey(secretKey)}}}var _HMAC=class{oHash;iHash;blockLen;outputLen;canXOF=false;finished=false;destroyed=false;constructor(hash3,key){ahash2(hash3);abytes4(key,void 0,"key");this.iHash=hash3.create();if(typeof this.iHash.update!=="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen;this.outputLen=this.iHash.outputLen;const blockLen=this.blockLen;const pad4=new Uint8Array(blockLen);pad4.set(key.length>blockLen?hash3.create().update(key).digest():key);for(let i=0;i<pad4.length;i++)pad4[i]^=54;this.iHash.update(pad4);this.oHash=hash3.create();for(let i=0;i<pad4.length;i++)pad4[i]^=54^92;this.oHash.update(pad4);clean4(pad4)}update(buf){aexists4(this);this.iHash.update(buf);return this}digestInto(out){aexists4(this);aoutput4(out,this);this.finished=true;const buf=out.subarray(0,this.outputLen);this.iHash.digestInto(buf);this.oHash.update(buf);this.oHash.digestInto(buf);this.destroy()}digest(){const out=new Uint8Array(this.oHash.outputLen);this.digestInto(out);return out}_cloneInto(to){to||=Object.create(Object.getPrototypeOf(this),{});const{oHash,iHash,finished,destroyed,blockLen,outputLen,canXOF}=this;to=to;to.finished=finished;to.destroyed=destroyed;to.blockLen=blockLen;to.outputLen=outputLen;to.canXOF=canXOF;to.oHash=oHash._cloneInto(to.oHash);to.iHash=iHash._cloneInto(to.iHash);return to}clone(){return this._cloneInto()}destroy(){this.destroyed=true;this.oHash.destroy();this.iHash.destroy()}};var hmac2=(()=>{const hmac_=((hash3,key,message2)=>new _HMAC(hash3,key).update(message2).digest());hmac_.create=(hash3,key)=>new _HMAC(hash3,key);return hmac_})();var _0n6=BigInt(0);var DERErr=class extends Error{constructor(m=""){super(m)}};var _DER={Err:DERErr,_tlv:{encode:(tag,data)=>{const{Err:E2}=_DER;asafenumber(tag,"tag");if(tag<0||tag>255)throw new E2("tlv.encode: wrong tag");astring(data,"data");if(data.length&1)throw new E2("tlv.encode: unpadded data");const dataLen=data.length/2;const len=numberToHexUnpadded(dataLen);if(len.length/2&128)throw new E2("tlv.encode: long form length too big");const lenLen=dataLen>127?numberToHexUnpadded(len.length/2|128):"";const t2=numberToHexUnpadded(tag);return t2+lenLen+len+data},decode(tag,data){const{Err:E2}=_DER;data=abytes6(data,void 0,"DER data");let pos=0;if(tag<0||tag>255)throw new E2("tlv.decode: wrong tag");if(data.length<2||data[pos++]!==tag)throw new E2("tlv.decode: wrong tlv");const first=data[pos++];const isLong=!!(first&128);let length=0;if(!isLong)length=first;else{const lenLen=first&127;if(!lenLen)throw new E2("tlv.decode(long): indefinite length not supported");if(lenLen>4)throw new E2("tlv.decode(long): byte length is too big");const lengthBytes=data.subarray(pos,pos+lenLen);if(lengthBytes.length!==lenLen)throw new E2("tlv.decode: length bytes not complete");if(lengthBytes[0]===0)throw new E2("tlv.decode(long): zero leftmost byte");for(const b2 of lengthBytes)length=length<<8|b2;pos+=lenLen;if(length<128)throw new E2("tlv.decode(long): not minimal encoding")}const v=data.subarray(pos,pos+length);if(v.length!==length)throw new E2("tlv.decode: wrong value length");return{v,l:data.subarray(pos+length)}}},_int:{encode(num){const{Err:E2}=_DER;abignumber(num);if(num<_0n6)throw new E2("integer: negative integers are not allowed");let hex3=numberToHexUnpadded(num);if(Number.parseInt(hex3[0],16)&8)hex3="00"+hex3;if(hex3.length&1)throw new E2("unexpected DER parsing assertion: unpadded hex");return hex3},decode(data){const{Err:E2}=_DER;if(data.length<1)throw new E2("invalid signature integer: empty");if(data[0]&128)throw new E2("invalid signature integer: negative");if(data.length>1&&data[0]===0&&!(data[1]&128))throw new E2("invalid signature integer: unnecessary leading zero");return bytesToNumberBE(data)}},toSig(bytes,maxScalarBytes){const{Err:E2,_int:int2,_tlv:tlv}=_DER;if(maxScalarBytes!==void 0){asafenumber(maxScalarBytes,"maxScalarBytes");if(maxScalarBytes<1)throw new E2("invalid signature: maxScalarBytes must be positive")}const data=abytes6(bytes,void 0,"signature");const{v:seqBytes,l:seqLeftBytes}=tlv.decode(48,data);if(seqLeftBytes.length)throw new E2("invalid signature: left bytes after parsing");const{v:rBytes,l:rLeftBytes}=tlv.decode(2,seqBytes);const{v:sBytes,l:sLeftBytes}=tlv.decode(2,rLeftBytes);if(sLeftBytes.length)throw new E2("invalid signature: left bytes after parsing");if(maxScalarBytes!==void 0&&(rBytes.length>maxScalarBytes||sBytes.length>maxScalarBytes))throw new E2("invalid signature: integer too large");return{r:int2.decode(rBytes),s:int2.decode(sBytes)}},hexFromSig(sig){const{_tlv:tlv,_int:int2}=_DER;validateObject(sig,{r:"bigint",s:"bigint"},{},"sig");const rs=tlv.encode(2,int2.encode(sig.r));const ss=tlv.encode(2,int2.encode(sig.s));const seq=rs+ss;return tlv.encode(48,seq)}};var DER=(()=>{Object.freeze(_DER._tlv);Object.freeze(_DER._int);return Object.freeze(_DER)})();var divNearest=(num,den)=>(num+(num>=0?den:-den)/_2n4)/den;function _splitEndoScalar(k2,basis,n){aInRange("scalar",k2,_0n7,n);const[[a1,b1],[a2,b2]]=basis;const c1=divNearest(b2*k2,n);const c2=divNearest(-b1*k2,n);let k1=k2-c1*a1-c2*a2;let k22=-c1*b1-c2*b2;const k1neg=k1<_0n7;const k2neg=k22<_0n7;if(k1neg)k1=-k1;if(k2neg)k22=-k22;const MAX_NUM=bitMask(Math.ceil(bitLen(n)/2))+_1n6;if(k1<_0n7||k1>=MAX_NUM||k22<_0n7||k22>=MAX_NUM){throw new Error("splitScalar (endomorphism): failed for k")}return{k1neg,k1,k2neg,k2:k22}}function validateSigFormat(format){if(!["compact","recovered","der"].includes(format))throw new Error('Signature format must be "compact", "recovered", or "der"');return format}function validateSigOpts(opts,def){validateObject(opts);const optsn={};for(let optName of Object.keys(def)){optsn[optName]=opts[optName]===void 0?def[optName]:opts[optName]}abool(optsn.lowS,"lowS");abool(optsn.prehash,"prehash");if(optsn.format!==void 0)validateSigFormat(optsn.format);return optsn}var _0n7=BigInt(0);var _1n6=BigInt(1);var _2n4=BigInt(2);var _3n2=BigInt(3);var _4n3=BigInt(4);function weierstrass(params,extraOpts={}){const validated=createCurveFields("weierstrass",params,extraOpts);const Fp=validated.Fp;const Fn2=validated.Fn;let CURVE=validated.CURVE;const{h:cofactor,n:CURVE_ORDER}=CURVE;validateObject(extraOpts,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});const{endo:endoOpts,allowInfinityPoint,clearCofactor,isTorsionFree,fromBytes:fromBytes3,toBytes:toBytes6}=extraOpts;const randomBytes5=extraOpts.randomBytes===void 0?randomBytes4:extraOpts.randomBytes;if(endoOpts){if(!Fp.is0(CURVE.a)||typeof endoOpts.beta!=="bigint"||!Array.isArray(endoOpts.basises)){throw new Error('invalid endo: expected "beta": bigint and "basises": array')}}const endo=endoOpts?{beta:endoOpts.beta,basises:endoOpts.basises.map(basis=>[...basis])}:void 0;const lengths=getWLengths(Fp,Fn2);function assertCompressionIsSupported(){if(!Fp.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function pointToBytes(_c,point,isCompressed){if(point.is0()){if(!allowInfinityPoint)throw new Error("bad point: ZERO");return Uint8Array.of(0)}const{x:x2,y}=point.toAffine();const bx=Fp.toBytes(x2);abool(isCompressed,"isCompressed");if(isCompressed){assertCompressionIsSupported();const hasEvenY=!Fp.isOdd(y);return concatBytes2(pprefix(hasEvenY),bx)}else{return concatBytes2(Uint8Array.of(4),bx,Fp.toBytes(y))}}function pointFromBytes(bytes){abytes6(bytes,void 0,"Point");const{publicKey:comp,publicKeyUncompressed:uncomp}=lengths;const length=bytes.length;const head=bytes[0];const tail=bytes.subarray(1);if(allowInfinityPoint&&length===1&&head===0)return{x:Fp.ZERO,y:Fp.ZERO};if(length===comp&&(head===2||head===3)){const x2=Fp.fromBytes(tail);if(!Fp.isValid(x2))throw new Error("bad point: is not on curve, wrong x");const y2=weierstrassEquation(x2);let y;try{y=Fp.sqrt(y2)}catch(sqrtError){const err=sqrtError instanceof Error?": "+sqrtError.message:"";throw new Error("bad point: is not on curve, sqrt error"+err)}assertCompressionIsSupported();const evenY=Fp.isOdd(y);const evenH=(head&1)===1;if(evenH!==evenY)y=Fp.neg(y);return{x:x2,y}}else if(length===uncomp&&head===4){const L2=Fp.BYTES;const x2=Fp.fromBytes(tail.subarray(0,L2));const y=Fp.fromBytes(tail.subarray(L2,L2*2));if(!isValidXY(x2,y))throw new Error("bad point: is not on curve");return{x:x2,y}}else{throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`)}}const encodePoint=toBytes6===void 0?pointToBytes:toBytes6;const decodePoint=fromBytes3===void 0?pointFromBytes:fromBytes3;const b3=Fp.mul(CURVE.b,_3n2);const mulA=Fp.is0(CURVE.a)?_=>Fp.ZERO:x2=>Fp.mul(CURVE.a,x2);function weierstrassEquation(x2){const x22=Fp.sqr(x2);const x3=Fp.mul(x22,x2);return Fp.add(Fp.add(x3,Fp.mul(x2,CURVE.a)),CURVE.b)}function isValidXY(x2,y){const left=Fp.sqr(y);const right=weierstrassEquation(x2);return Fp.eql(left,right)}if(!isValidXY(CURVE.Gx,CURVE.Gy))throw new Error("bad curve params: generator point");const _4a3=Fp.mul(Fp.pow(CURVE.a,_3n2),_4n3);const _27b2=Fp.mul(Fp.sqr(CURVE.b),BigInt(27));if(Fp.is0(Fp.add(_4a3,_27b2)))throw new Error("bad curve params: a or b");function acoord(title,n,banZero=false){if(!Fp.isValid(n)||banZero&&Fp.is0(n))throw new Error(`bad point coordinate ${title}`);return typeof n==="object"&&n!==null?Fp.create(n):n}function aprjpoint(other){if(!(other instanceof Point2))throw new Error("Weierstrass Point expected")}function splitEndoScalarN(k2){if(!endo||!endo.basises)throw new Error("no endo");return _splitEndoScalar(k2,endo.basises,Fn2.ORDER)}function pushWnafPair(points,scalars,p,k2){if(!Fn2.isValid(k2))throw new RangeError("invalid scalar: out of range");if(endo){const{k1neg,k1,k2neg,k2:k22}=splitEndoScalarN(k2);const psi=new Point2(Fp.mul(p.X,endo.beta),p.Y,p.Z);points.push(k1neg?p.negate():p,k2neg?psi.negate():psi);scalars.push(k1,k22)}else{points.push(p);scalars.push(k2)}}const validityCache=new WeakSet;class Point2{static BASE=new Point2(CURVE.Gx,CURVE.Gy,Fp.ONE);static ZERO=new Point2(Fp.ZERO,Fp.ONE,Fp.ZERO);static Fp=Fp;static Fn=Fn2;X;Y;Z;constructor(X2,Y2,Z2){this.X=acoord("x",X2);this.Y=acoord("y",Y2,true);this.Z=acoord("z",Z2);Object.freeze(this)}static CURVE(){return CURVE}static fromAffine(p){const{x:x2,y}=p||{};if(!p||!Fp.isValid(x2)||!Fp.isValid(y))throw new Error("invalid affine point");if(p instanceof Point2)throw new Error("projective point not allowed");if(Fp.is0(x2)&&Fp.is0(y))return Point2.ZERO;return new Point2(x2,y,Fp.ONE)}static fromBytes(bytes){const P2=Point2.fromAffine(decodePoint(abytes6(bytes,void 0,"point")));P2.assertValidity();return P2}static fromHex(hex3){return Point2.fromBytes(hexToBytes3(hex3))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(windowSize=6,isLazy=true){wnaf.setWindowSize(this,windowSize);if(!isLazy)this.multiply(_3n2);return this}assertValidity(){const p=this;if(p.is0()){if(allowInfinityPoint&&Fp.is0(p.X)&&Fp.eql(p.Y,Fp.ONE)&&Fp.is0(p.Z))return;throw new Error("bad point: ZERO")}if(validityCache.has(p))return;const{x:x2,y}=p.toAffine();if(!Fp.isValid(x2)||!Fp.isValid(y))throw new Error("bad point: x or y not field elements");if(!isValidXY(x2,y))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");validityCache.add(p)}hasEvenY(){const{y}=this.toAffine();if(!Fp.isOdd)throw new Error("Field doesn't support isOdd");return!Fp.isOdd(y)}equals(other){aprjpoint(other);const{X:X1,Y:Y1,Z:Z1}=this;const{X:X2,Y:Y2,Z:Z2}=other;const U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1));const U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point2(this.X,Fp.neg(this.Y),this.Z)}double(){const{X:X1,Y:Y1,Z:Z1}=this;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;let t0=Fp.mul(X1,X1);let t1=Fp.mul(Y1,Y1);let t2=Fp.mul(Z1,Z1);let t3=Fp.mul(X1,Y1);t3=Fp.add(t3,t3);Z3=Fp.mul(X1,Z1);Z3=Fp.add(Z3,Z3);X3=mulA(Z3);Y3=Fp.mul(b3,t2);Y3=Fp.add(X3,Y3);X3=Fp.sub(t1,Y3);Y3=Fp.add(t1,Y3);Y3=Fp.mul(X3,Y3);X3=Fp.mul(t3,X3);Z3=Fp.mul(b3,Z3);t2=mulA(t2);t3=Fp.sub(t0,t2);t3=mulA(t3);t3=Fp.add(t3,Z3);Z3=Fp.add(t0,t0);t0=Fp.add(Z3,t0);t0=Fp.add(t0,t2);t0=Fp.mul(t0,t3);Y3=Fp.add(Y3,t0);t2=Fp.mul(Y1,Z1);t2=Fp.add(t2,t2);t0=Fp.mul(t2,t3);X3=Fp.sub(X3,t0);Z3=Fp.mul(t2,t1);Z3=Fp.add(Z3,Z3);Z3=Fp.add(Z3,Z3);return new Point2(X3,Y3,Z3)}add(other){aprjpoint(other);const{X:X1,Y:Y1,Z:Z1}=this;const{X:X2,Y:Y2,Z:Z2}=other;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;let t0=Fp.mul(X1,X2);let t1=Fp.mul(Y1,Y2);let t2=Fp.mul(Z1,Z2);let t3=Fp.add(X1,Y1);let t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4);t4=Fp.add(t0,t1);t3=Fp.sub(t3,t4);t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);t4=Fp.mul(t4,t5);t5=Fp.add(t0,t2);t4=Fp.sub(t4,t5);t5=Fp.add(Y1,Z1);X3=Fp.add(Y2,Z2);t5=Fp.mul(t5,X3);X3=Fp.add(t1,t2);t5=Fp.sub(t5,X3);Z3=mulA(t4);X3=Fp.mul(b3,t2);Z3=Fp.add(X3,Z3);X3=Fp.sub(t1,Z3);Z3=Fp.add(t1,Z3);Y3=Fp.mul(X3,Z3);t1=Fp.add(t0,t0);t1=Fp.add(t1,t0);t2=mulA(t2);t4=Fp.mul(b3,t4);t1=Fp.add(t1,t2);t2=Fp.sub(t0,t2);t2=mulA(t2);t4=Fp.add(t4,t2);t0=Fp.mul(t1,t4);Y3=Fp.add(Y3,t0);t0=Fp.mul(t5,t4);X3=Fp.mul(t3,X3);X3=Fp.sub(X3,t0);t0=Fp.mul(t3,t1);Z3=Fp.mul(t5,Z3);Z3=Fp.add(Z3,t0);return new Point2(X3,Y3,Z3)}subtract(other){aprjpoint(other);return this.add(other.negate())}is0(){return this.equals(Point2.ZERO)}multiply(scalar){if(!Fn2.isValidNot0(scalar))throw new RangeError("invalid scalar: out of range");const{p,f}=wnaf.mulSecret(this,scalar,cofactor,normalize2);return normalize2([p,f])[0]}multiplyUnsafe(scalar){const p=this;const sc=scalar;if(!Fn2.isValid(sc))throw new RangeError("invalid scalar: out of range");if(sc===_0n7||p.is0())return Point2.ZERO;if(sc===_1n6)return p;if(wnaf.hasWindowSize(this))return wnaf.mulUnsafe(p,sc,normalize2);const points=[];const scalars=[];pushWnafPair(points,scalars,p,sc);return mulAddUnsafe(Point2,points,scalars)}mulAddUnsafe(a,other,b2){aprjpoint(other);const points=[];const scalars=[];pushWnafPair(points,scalars,this,a);pushWnafPair(points,scalars,other,b2);return mulAddUnsafe(Point2,points,scalars)}toAffine(invertedZ){const p=this;let iz=invertedZ;if(iz!=null&&!Fp.isValid(iz))throw new RangeError('"invertedZ" expected valid field element');const{X:X2,Y:Y2,Z:Z2}=p;if(Fp.eql(Z2,Fp.ONE))return{x:X2,y:Y2};const is0=p.is0();if(iz==null)iz=is0?Fp.ONE:Fp.inv(Z2);const x2=Fp.mul(X2,iz);const y=Fp.mul(Y2,iz);const zz=Fp.mul(Z2,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw new Error("invZ was invalid");return{x:x2,y}}isTorsionFree(){if(cofactor===_1n6)return true;if(isTorsionFree)return isTorsionFree(Point2,this);return wnaf.mulUnsafe(this,CURVE_ORDER).is0()}clearCofactor(){if(cofactor===_1n6)return this;if(clearCofactor)return clearCofactor(Point2,this);return this.multiplyUnsafe(cofactor)}isSmallOrder(){if(cofactor===_1n6)return this.is0();return this.clearCofactor().is0()}toBytes(isCompressed=true){abool(isCompressed,"isCompressed");this.assertValidity();return encodePoint(Point2,this,isCompressed)}toHex(isCompressed=true){return bytesToHex3(this.toBytes(isCompressed))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}const normalize2=points=>normalizeZ(Point2,points);const wnaf=new ScalarMultiplier(Point2,randomBytes5);if(wnaf.bits>=6)Point2.BASE.precompute(6);Object.freeze(Point2.prototype);Object.freeze(Point2);return Point2}function pprefix(hasEvenY){return Uint8Array.of(hasEvenY?2:3)}function getWLengths(Fp,Fn2){return{secretKey:Fn2.BYTES,publicKey:1+Fp.BYTES,publicKeyUncompressed:1+2*Fp.BYTES,publicKeyHasPrefix:true,signature:2*Fn2.BYTES}}function ecdh(Point2,ecdhOpts={}){validatePointCons(Point2);const{Fn:Fn2}=Point2;const randomBytes_=ecdhOpts.randomBytes===void 0?randomBytes4:ecdhOpts.randomBytes;const lengths=Object.assign(getWLengths(Point2.Fp,Fn2),{seed:Math.max(getMinHashLength(Fn2.ORDER),16)});function isValidSecretKey(secretKey){try{const num=Fn2.fromBytes(secretKey);return Fn2.isValidNot0(num)}catch(error51){return false}}function isValidPublicKey(publicKey,isCompressed){const{publicKey:comp,publicKeyUncompressed}=lengths;try{const l=publicKey.length;if(isCompressed===true&&l!==comp)return false;if(isCompressed===false&&l!==publicKeyUncompressed)return false;return!Point2.fromBytes(publicKey).is0()}catch(error51){return false}}function randomSecretKey(seed){seed=seed===void 0?randomBytes_(lengths.seed):seed;return mapHashToField(abytes6(seed,lengths.seed,"seed"),Fn2.ORDER)}function getPublicKey(secretKey,isCompressed=true){return Point2.BASE.multiply(Fn2.fromBytes(secretKey)).toBytes(isCompressed)}function isProbPub(item){const{secretKey,publicKey,publicKeyUncompressed}=lengths;const allowedLengths=Fn2._lengths;if(!isBytes7(item))return void 0;const l=abytes6(item,void 0,"key").length;const isPub=l===publicKey||l===publicKeyUncompressed;const isSec=l===secretKey||!!allowedLengths?.includes(l);if(isPub&&isSec)return void 0;return isPub}function getSharedSecret(secretKeyA,publicKeyB,isCompressed=true){if(isProbPub(secretKeyA)===true)throw new Error("first arg must be private key");if(isProbPub(publicKeyB)===false)throw new Error("second arg must be public key");const s=Fn2.fromBytes(secretKeyA);const b2=Point2.fromBytes(publicKeyB);if(b2.is0())throw new Error("invalid public key: point at infinity");return b2.multiply(s).toBytes(isCompressed)}const utils2={isValidSecretKey,isValidPublicKey,randomSecretKey};const keygen=createKeygen(randomSecretKey,getPublicKey);Object.freeze(utils2);Object.freeze(lengths);return Object.freeze({getPublicKey,getSharedSecret,keygen,Point:Point2,utils:utils2,lengths})}function ecdsa(Point2,hash3,ecdsaOpts={}){validatePointCons(Point2);const hash_=hash3;ahash2(hash_);validateObject(ecdsaOpts,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const opts=Object.assign({},ecdsaOpts);const randomBytes5=opts.randomBytes===void 0?randomBytes4:opts.randomBytes;const hmac3=opts.hmac===void 0?(key,msg)=>hmac2(hash_,key,msg):opts.hmac;const{Fp,Fn:Fn2}=Point2;const{ORDER:CURVE_ORDER,BITS:fnBits}=Fn2;const blindLength=getMinHashLength(CURVE_ORDER);const csprng=probeRandomBytes(randomBytes5,blindLength);const{keygen,getPublicKey,getSharedSecret,utils:utils2,lengths}=ecdh(Point2,opts);const defaultSigOpts={prehash:true,lowS:typeof opts.lowS==="boolean"?opts.lowS:true,format:"compact",extraEntropy:false};const hasLargeRecoveryLifts=CURVE_ORDER*_2n4+_1n6<Fp.ORDER;function isBiggerThanHalfOrder(number4){const HALF=CURVE_ORDER>>_1n6;return number4>HALF}function validateRS(title,num){if(!Fn2.isValidNot0(num))throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);return num}function assertFieldSignIsSupported(){if(!Fp.isOdd)throw new Error("Field doesn't support isOdd")}function getRecoveryBit(x2,y,r){assertFieldSignIsSupported();return(x2===r?0:2)|Number(Fp.isOdd(y))}function assertRecoverableCurve(){if(hasLargeRecoveryLifts)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function validateSigLength(bytes,format){validateSigFormat(format);const size4=lengths.signature;const sizer=format==="compact"?size4:format==="recovered"?size4+1:void 0;return abytes6(bytes,sizer)}class Signature{r;s;recovery;constructor(r,s,recovery){this.r=validateRS("r",r);this.s=validateRS("s",s);if(recovery!=null){assertRecoverableCurve();if(![0,1,2,3].includes(recovery))throw new Error("invalid recovery id");this.recovery=recovery}Object.freeze(this)}static fromBytes(bytes,format=defaultSigOpts.format){validateSigLength(bytes,format);let recid;if(format==="der"){if(bytes.length>2*Fn2.BYTES+16)throw new DER.Err("invalid signature: DER signature too long");const{r:r2,s:s2}=DER.toSig(abytes6(bytes),Fn2.BYTES+1);return new Signature(r2,s2)}if(format==="recovered"){recid=bytes[0];format="compact";bytes=bytes.subarray(1)}const L2=lengths.signature/2;const r=bytes.subarray(0,L2);const s=bytes.subarray(L2,L2*2);return new Signature(Fn2.fromBytes(r),Fn2.fromBytes(s),recid)}static fromHex(hex3,format){return this.fromBytes(hexToBytes3(hex3),format)}assertRecovery(){const{recovery}=this;if(recovery==null)throw new Error("invalid recovery id: must be present");return recovery}addRecoveryBit(recovery){return new Signature(this.r,this.s,recovery)}recoverPublicKey(messageHash){const{r,s}=this;const recovery=this.assertRecovery();const radj=recovery===2||recovery===3?r+CURVE_ORDER:r;if(!Fp.isValid(radj))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const x2=Fp.toBytes(radj);const R=Point2.fromBytes(concatBytes2(pprefix((recovery&1)===0),x2));const ir2=Fn2.inv(radj);const h=bits2int_modN(abytes6(messageHash,void 0,"msgHash"));const u1=Fn2.create(-h*ir2);const u2=Fn2.create(s*ir2);const Q=Point2.BASE.mulAddUnsafe(u1,R,u2);if(Q.is0())throw new Error("invalid recovery: point at infinify");Q.assertValidity();return Q}hasHighS(){return isBiggerThanHalfOrder(this.s)}toBytes(format=defaultSigOpts.format){validateSigFormat(format);if(format==="der")return hexToBytes3(DER.hexFromSig(this));const{r,s}=this;const rb=Fn2.toBytes(r);const sb=Fn2.toBytes(s);if(format==="recovered"){assertRecoverableCurve();return concatBytes2(Uint8Array.of(this.assertRecovery()),rb,sb)}return concatBytes2(rb,sb)}toHex(format){return bytesToHex3(this.toBytes(format))}}Object.freeze(Signature.prototype);Object.freeze(Signature);const bits2int=opts.bits2int===void 0?function bits2int_def(bytes){if(bytes.length>8192)throw new Error("input is too large");const num=bytesToNumberBE(bytes);const delta=bytes.length*8-fnBits;return delta>0?num>>BigInt(delta):num}:opts.bits2int;const bits2int_modN=opts.bits2int_modN===void 0?function bits2int_modN_def(bytes){return Fn2.create(bits2int(bytes))}:opts.bits2int_modN;const ORDER_MASK=bitMask(fnBits);function int2octets(num){aInRange("num < 2^"+fnBits,num,_0n7,ORDER_MASK);return Fn2.toBytes(num)}function validateMsgAndHash(message2,prehash){abytes6(message2,void 0,"message");return prehash?abytes6(hash_(message2),void 0,"prehashed message"):message2}function prepSig(message2,secretKey,opts2){const{lowS,prehash,extraEntropy}=validateSigOpts(opts2,defaultSigOpts);message2=validateMsgAndHash(message2,prehash);const h1int=bits2int_modN(message2);const d=Fn2.fromBytes(secretKey);if(!Fn2.isValidNot0(d))throw new Error("invalid private key");const seedArgs=[int2octets(d),int2octets(h1int)];if(extraEntropy!=null&&extraEntropy!==false){const e17=extraEntropy===true?randomBytes5(lengths.secretKey):extraEntropy;seedArgs.push(abytes6(e17,void 0,"extraEntropy"))}const seed=concatBytes2(...seedArgs);const m=h1int;function k2sig(kBytes){const k2=bits2int(kBytes);if(!Fn2.isValidNot0(k2))return;const q2=Point2.BASE.multiply(k2).toAffine();const r=Fn2.create(q2.x);if(r===_0n7)return;let s;if(csprng!==void 0){const b2=bytesToNumberBE(mapHashToField(csprng(blindLength),CURVE_ORDER));const ibk=Fn2.inv(Fn2.mul(b2,k2));const bm=Fn2.mul(b2,m);const bd=Fn2.mul(b2,d);s=Fn2.create(ibk*Fn2.create(bm+bd*r))}else{const ik=invertCt(k2,CURVE_ORDER);s=Fn2.create(ik*Fn2.create(m+r*d))}if(s===_0n7)return;let recovery=getRecoveryBit(q2.x,q2.y,r);let normS=s;if(lowS&&isBiggerThanHalfOrder(s)){normS=Fn2.neg(s);recovery^=1}return new Signature(r,normS,hasLargeRecoveryLifts?void 0:recovery)}return{seed,k2sig}}function sign(message2,secretKey,opts2={}){const{seed,k2sig}=prepSig(message2,secretKey,opts2);const drbg=createHmacDrbg(hash_.outputLen,Fn2.BYTES,hmac3);const sig=drbg(seed,k2sig);return sig.toBytes(opts2.format)}function verify3(signature2,message2,publicKey,opts2={}){const{lowS,prehash,format}=validateSigOpts(opts2,defaultSigOpts);publicKey=abytes6(publicKey,void 0,"publicKey");message2=validateMsgAndHash(message2,prehash);if(!isBytes7(signature2)){const end=signature2 instanceof Signature?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+end)}validateSigLength(signature2,format);try{const sig=Signature.fromBytes(signature2,format);const P2=Point2.fromBytes(publicKey);if(P2.is0())return false;if(lowS&&sig.hasHighS())return false;const{r,s}=sig;const h=bits2int_modN(message2);const is=Fn2.inv(s);const u1=Fn2.create(h*is);const u2=Fn2.create(r*is);const R=Point2.BASE.mulAddUnsafe(u1,P2,u2);if(R.is0())return false;const q2=R.toAffine();const v=Fn2.create(q2.x);if(v!==r)return false;if(format==="recovered"&&sig.recovery!==getRecoveryBit(q2.x,q2.y,r))return false;return true}catch(e17){return false}}function recoverPublicKey(signature2,message2,opts2={}){const{prehash}=validateSigOpts(opts2,defaultSigOpts);message2=validateMsgAndHash(message2,prehash);return Signature.fromBytes(signature2,"recovered").recoverPublicKey(message2).toBytes()}return Object.freeze({keygen,getPublicKey,getSharedSecret,utils:utils2,lengths,Point:Point2,sign,verify:verify3,recoverPublicKey,Signature,hash:hash_})}var secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")};var secp256k1_ENDO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var _2n5=BigInt(2);function sqrtMod(y){const P2=secp256k1_CURVE.p;const _3n3=BigInt(3),_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22);const _23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88);const b2=y*y*y%P2;const b3=b2*b2*y%P2;const b6=pow2(b3,_3n3,P2)*b3%P2;const b9=pow2(b6,_3n3,P2)*b3%P2;const b11=pow2(b9,_2n5,P2)*b2%P2;const b22=pow2(b11,_11n,P2)*b11%P2;const b44=pow2(b22,_22n,P2)*b22%P2;const b88=pow2(b44,_44n,P2)*b44%P2;const b176=pow2(b88,_88n,P2)*b88%P2;const b220=pow2(b176,_44n,P2)*b44%P2;const b223=pow2(b220,_3n3,P2)*b3%P2;const t1=pow2(b223,_23n,P2)*b22%P2;const t2=pow2(t1,_6n,P2)*b2%P2;const root=pow2(t2,_2n5,P2);if(!Fpk1.eql(Fpk1.sqr(root),y))throw new Error("Cannot find square root");return root}var Fpk1=Field(secp256k1_CURVE.p,{sqrt:sqrtMod});var Pointk1=weierstrass(secp256k1_CURVE,{Fp:Fpk1,endo:secp256k1_ENDO});var secp256k1=ecdsa(Pointk1,sha2565);var Rho1602=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]);var Id1602=(()=>Uint8Array.from(new Array(16).fill(0).map((_,i)=>i)))();var Pi1602=(()=>Id1602.map(i=>(9*i+5)%16))();var idxLR2=(()=>{const L2=[Id1602];const R=[Pi1602];const res=[L2,R];for(let i=0;i<4;i++)for(let j2 of res)j2.push(j2[i].map(k2=>Rho1602[k2]));return res})();var idxL2=(()=>idxLR2[0])();var idxR2=(()=>idxLR2[1])();var shifts1602=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(i=>Uint8Array.from(i));var shiftsL1602=idxL2.map((idx,i)=>idx.map(j2=>shifts1602[i][j2]));var shiftsR1602=idxR2.map((idx,i)=>idx.map(j2=>shifts1602[i][j2]));var Kl1602=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]);var Kr1602=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function ripemd_f2(group,x2,y,z){if(group===0)return x2^y^z;if(group===1)return x2&y|~x2&z;if(group===2)return(x2|~y)^z;if(group===3)return x2&z|y&~z;return x2^(y|~z)}var BUF_1602=new Uint32Array(16);var _RIPEMD160=class extends HashMD3{h0=1732584193|0;h1=4023233417|0;h2=2562383102|0;h3=271733878|0;h4=3285377520|0;constructor(){super(64,20,8,true)}get(){const{h0,h1,h2,h3,h4}=this;return[h0,h1,h2,h3,h4]}set(h0,h1,h2,h3,h4){this.h0=h0|0;this.h1=h1|0;this.h2=h2|0;this.h3=h3|0;this.h4=h4|0}_cloneInto(to){(to||=new this.constructor).set(...this.get());return this._cloneIntoMeta(to)}process(view,offset){for(let i=0;i<16;i++,offset+=4)BUF_1602[i]=view.getUint32(offset,true);let al=this.h0|0,ar2=al,bl=this.h1|0,br=bl,cl=this.h2|0,cr=cl,dl=this.h3|0,dr2=dl,el=this.h4|0,er=el;for(let group=0;group<5;group++){const rGroup=4-group;const hbl=Kl1602[group],hbr=Kr1602[group];const rl=idxL2[group],rr=idxR2[group];const sl=shiftsL1602[group],sr2=shiftsR1602[group];for(let i=0;i<16;i++){const tl=rotl2(al+ripemd_f2(group,bl,cl,dl)+BUF_1602[rl[i]]+hbl,sl[i])+el|0;al=el,el=dl,dl=rotl2(cl,10)|0,cl=bl,bl=tl}for(let i=0;i<16;i++){const tr2=rotl2(ar2+ripemd_f2(rGroup,br,cr,dr2)+BUF_1602[rr[i]]+hbr,sr2[i])+er|0;ar2=er,er=dr2,dr2=rotl2(cr,10)|0,cr=br,br=tr2}}this.set(this.h1+cl+dr2|0,this.h2+dl+er|0,this.h3+el+ar2|0,this.h4+al+br|0,this.h0+bl+cr|0)}roundClean(){clean4(BUF_1602)}destroy(){this.destroyed=true;clean4(this.buffer);this.set(0,0,0,0,0)}};var ripemd1604=createHasher4(()=>new _RIPEMD160);var Point=(()=>secp256k1.Point)();var Fn=(()=>Point.Fn)();var base58check=createBase58check(sha2565);var MASTER_SECRET=(()=>{return Uint8Array.from("Bitcoin seed".split(""),char=>char.charCodeAt(0))})();var BITCOIN_VERSIONS={private:76066276,public:76067358};var HARDENED_OFFSET=2147483648;var MAX_DEPTH=255;var hash160=data=>ripemd1604(sha2565(data));var fromU32=data=>createView3(data).getUint32(0,false);var toU32=(n,title="number")=>{if(typeof n!=="number")throw new TypeError(`"${title}" expected number, got type=${typeof n}`);if(!Number.isSafeInteger(n)||n<0||n>2**32-1)throw new RangeError(`"${title}" expected integer in range 0..2**32-1, got ${n}`);const buf=new Uint8Array(4);createView3(buf).setUint32(0,n,false);return buf};var validateVersions=(versions2,title="versions")=>{if(!(typeof versions2==="object"&&versions2!==null))throw new Error("versions must be an object");toU32(versions2.private,`${title}.private`);toU32(versions2.public,`${title}.public`);return versions2};var HDKey=class _HDKey{get fingerprint(){if(!this._pubHash){throw new Error("No publicKey set!")}return fromU32(this._pubHash)}get identifier(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get pubKeyHash(){return this._pubHash?Uint8Array.from(this._pubHash):void 0}get privateKey(){return this._privateKey?Uint8Array.from(this._privateKey):null}get publicKey(){return this._publicKey?Uint8Array.from(this._publicKey):null}get chainCode(){return this._chainCode?Uint8Array.from(this._chainCode):null}get privateExtendedKey(){const priv=this._privateKey;if(!priv){throw new Error("No private key")}return base58check.encode(this.serialize(this.versions.private,concatBytes(Uint8Array.of(0),priv)))}get publicExtendedKey(){if(!this._publicKey){throw new Error("No public key")}return base58check.encode(this.serialize(this.versions.public,this._publicKey))}static fromMasterSeed(seed,versions2=BITCOIN_VERSIONS){abytes4(seed);versions2=validateVersions(versions2);if(8*seed.length<128||8*seed.length>512){throw new RangeError("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got "+seed.length)}const I=hmac2(sha5122,MASTER_SECRET,seed);const privateKey=I.slice(0,32);const chainCode=I.slice(32);return new _HDKey({versions:versions2,chainCode,privateKey})}static fromExtendedKey(base58key,versions2=BITCOIN_VERSIONS){versions2=validateVersions(versions2);const keyBuffer=base58check.decode(base58key);if(keyBuffer.length!==78){throw new Error(`HDKey: invalid extended key length: expected 78 bytes, got ${keyBuffer.length}`)}const keyView=createView3(keyBuffer);const version4=keyView.getUint32(0,false);const opt={versions:versions2,depth:keyBuffer[4],parentFingerprint:keyView.getUint32(5,false),index:keyView.getUint32(9,false),chainCode:keyBuffer.slice(13,45)};const key=keyBuffer.slice(45);const isPriv=key[0]===0;if(version4!==versions2[isPriv?"private":"public"]){throw new Error("Version mismatch")}if(isPriv){return new _HDKey({...opt,privateKey:key.slice(1)})}else{return new _HDKey({...opt,publicKey:key})}}static fromJSON(json3){return _HDKey.fromExtendedKey("xpriv"in json3?json3.xpriv:json3.xpub)}versions;depth=0;index=0;parentFingerprint=0;_chainCode=null;_privateKey;_publicKey;_pubHash;constructor(opt){if(!opt||typeof opt!=="object"){throw new Error("HDKey.constructor must not be called directly")}const depth=opt.depth??0;const index=opt.index??0;const parentFingerprint=opt.parentFingerprint??0;if(!Number.isSafeInteger(depth)||depth<0||depth>MAX_DEPTH){throw new RangeError("HDKey: depth must be an integer in range 0..255")}toU32(index,"index");toU32(parentFingerprint,"parentFingerprint");if(depth===0&&(index!==0||parentFingerprint!==0)){throw new Error("HDKey: zero depth with non-zero index/parent fingerprint")}this.versions=opt.versions?validateVersions(opt.versions):BITCOIN_VERSIONS;this.depth=depth;if(opt.chainCode)abytes4(opt.chainCode,32);this._chainCode=opt.chainCode?Uint8Array.from(opt.chainCode):null;this.index=index;this.parentFingerprint=parentFingerprint;if(opt.publicKey&&opt.privateKey){throw new Error("HDKey: publicKey and privateKey at same time.")}if(opt.privateKey){if(!secp256k1.utils.isValidSecretKey(opt.privateKey))throw new Error("Invalid private key");this._privateKey=Uint8Array.from(opt.privateKey);this._publicKey=secp256k1.getPublicKey(this._privateKey,true)}else if(opt.publicKey){this._publicKey=Point.fromBytes(opt.publicKey).toBytes(true)}else{throw new Error("HDKey: no public or private key provided")}this._pubHash=hash160(this._publicKey)}derive(path){if(!/^[mM]'?/.test(path)){throw new Error('Path must start with "m" or "M"')}if(/^[mM]'?$/.test(path)){return this}const parts=path.replace(/^[mM]'?\//,"").split("/");if(parts.length>MAX_DEPTH-this.depth){throw new Error("HDKey: path exceeds the serializable depth 255")}let child=this;for(const c of parts){const m=/^(\d+)('?)$/.exec(c);const m1=m&&m[1];if(!m||m.length!==3||typeof m1!=="string")throw new Error("invalid child index: "+c);let idx=+m1;if(!Number.isSafeInteger(idx)||idx>=HARDENED_OFFSET){throw new Error("Invalid index")}if(m[2]==="'"){idx+=HARDENED_OFFSET}child=child.deriveChild(idx)}return child}deriveChild(index){return this._deriveChild(index)}_deriveChild(index,_I){if(!this._publicKey||!this._chainCode){throw new Error("No publicKey or chainCode set")}let data=toU32(index,"index");if(index>=HARDENED_OFFSET){const priv=this._privateKey;if(!priv){throw new Error("Could not derive hardened child key")}data=concatBytes(Uint8Array.of(0),priv,data)}else{data=concatBytes(this._publicKey,data)}const out=_I||hmac2(sha5122,this._chainCode,data);abytes4(out,64);const childTweak=out.slice(0,32);const chainCode=out.slice(32);const opt={versions:this.versions,chainCode,depth:this.depth+1,parentFingerprint:this.fingerprint,index};if(opt.depth>MAX_DEPTH){throw new Error("HDKey: depth exceeds the serializable value 255")}const retry=()=>{const maxIndex=this._privateKey?2**32-1:HARDENED_OFFSET-1;if(index>=maxIndex){throw new Error(`HDKey: cannot retry child derivation at index ${index}`)}return this.deriveChild(index+1)};const ctweak=Fn.fromBytes(childTweak,true);if(!Fn.isValid(ctweak))return retry();if(this._privateKey){const added=Fn.create(Fn.fromBytes(this._privateKey)+ctweak);if(!Fn.isValidNot0(added))return retry();opt.privateKey=Fn.toBytes(added)}else{const point=Point.fromBytes(this._publicKey);const added=ctweak===0n?point:point.add(Point.BASE.multiply(ctweak));if(added.equals(Point.ZERO))return retry();opt.publicKey=added.toBytes(true)}return new _HDKey(opt)}sign(hash3){if(!this._privateKey){throw new Error("No privateKey set!")}abytes4(hash3,32);return secp256k1.sign(hash3,this._privateKey,{prehash:false})}verify(hash3,signature2){abytes4(hash3,32);abytes4(signature2,64);if(!this._publicKey){throw new Error("No publicKey set!")}return secp256k1.verify(signature2,hash3,this._publicKey,{prehash:false})}wipePrivateData(){if(this._privateKey){this._privateKey.fill(0);this._privateKey=void 0}return this}toJSON(){return this.toPrivateJSON()}toPrivateJSON(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}}serialize(version4,key){if(!this._chainCode){throw new Error("No chainCode set")}abytes4(key,33);return concatBytes(toU32(version4,"version"),new Uint8Array([this.depth]),toU32(this.parentFingerprint,"parentFingerprint"),toU32(this.index,"index"),this._chainCode,key)}};var b=class e extends Error{constructor(t2,n){super(t2),this.name="CTSError",n?.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:true,enumerable:false,value:n.cause,writable:true}),Object.setPrototypeOf(this,e.prototype)}};var x=class e2 extends b{constructor(t2,n,r){super(t2,r),this.status=n,this.name="HttpResponseError",Object.setPrototypeOf(this,e2.prototype)}};var S=class e3 extends b{constructor(t2,n){super(t2,n),this.name="NetworkError",Object.setPrototypeOf(this,e3.prototype)}};var T=class e4 extends x{constructor(t2,n){super(t2,429),this.retryAfterMs=n,this.name="RateLimitError",Object.setPrototypeOf(this,e4.prototype)}};var te=class e5 extends x{constructor(t2,n){super(n||"Unknown mint operation error",400),this.code=t2,this.name="MintOperationError",Object.setPrototypeOf(this,e5.prototype)}};var E={error(){},warn(){},info(){},debug(){},trace(){},log(){}};function re(e17,t2=E,n){throw t2.error(e17,n),new b(e17)}function D(e17,t2,n=E,r){e17&&re(t2,n,r)}function O(e17,t2,n=E,r){if(e17)try{let i=e17(t2);i&&typeof i.then=="function"&&i.catch(t3=>{try{n.warn("callback failed",{...r??{},error:t3,cb:e17.name??""})}catch{}})}catch(t3){try{n.warn("callback failed",{...r??{},error:t3,cb:e17.name??""})}catch{}}}var ae=8192;var oe=1e4;var se=1024;var ce=1024;var ue=2147483647;var de=2n**64n-1n;var be=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});function xe(e17){try{return be.decode(e17)}catch(e18){throw new b("Malformed UTF-8 sequence",{cause:e18})}}var Se=new TextDecoder("utf-8",{fatal:true});function Ee(e17,t2){if(t2.has(e17))throw TypeError("Cannot initialize the same private elements twice on an object")}function De(e17,t2,n){Ee(e17,t2),t2.set(e17,n)}function Oe(e17){"@babel/helpers - typeof";return Oe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e18){return typeof e18}:function(e18){return e18&&typeof Symbol=="function"&&e18.constructor===Symbol&&e18!==Symbol.prototype?"symbol":typeof e18},Oe(e17)}function ke(e17){if(Object(e17)!==e17)throw TypeError("right-hand side of 'in' should be an object, got "+(e17===null?"null":Oe(e17)));return e17}var k=class e6 extends b{constructor(t2){super(t2),this.name="AmountError",Object.setPrototypeOf(this,e6.prototype)}};var Ae=new WeakMap;var A=class e7{constructor(e17){if(De(this,Ae,true),e17<0n)throw new k(`Amount must be >= 0, got ${e17}`);if(e17>de)throw new k(`Amount exceeds u64 max, got ${e17}`);this.value=e17,Object.freeze(this)}static from(t2){if(t2 instanceof e7){if(!Ae.has(ke(t2)))throw new k("Invalid Amount instance");return t2}if(typeof t2=="bigint"){if(t2<0n)throw new k(`Amount must be >= 0, got ${t2}`);return new e7(t2)}if(typeof t2=="number"){if(!Number.isFinite(t2)||!Number.isInteger(t2))throw new k(`Invalid number amount: ${t2}`);if(t2<0)throw new k(`Amount must be >= 0, got ${t2}`);if(!Number.isSafeInteger(t2))throw new k(`Unsafe integer amount: ${t2}. Use bigint or decimal string.`);return new e7(BigInt(t2))}if(typeof t2=="string"){if(t2.length>20)throw new k(`Amount exceeds u64 max: "${t2.slice(0,20)}..."`);if(!/^(0|[1-9]\d*)$/.test(t2))throw new k(`Invalid amount string "${t2}". Expected non-negative decimal integer.`);return new e7(BigInt(t2))}throw new k("Unsupported amount input type")}static zero(){return new e7(0n)}static one(){return new e7(1n)}toBigInt(){return this.value}toNumber(){if(!this.isSafeNumber())throw new k(`Amount ${this.value} exceeds Number.MAX_SAFE_INTEGER; use toBigInt/toString/toJSON.`);return Number(this.value)}toNumberUnsafe(){return Number(this.value)}toString(){return this.value.toString(10)}toJSON(){return this.toString()}add(t2){let n=e7.from(t2);return new e7(this.value+n.value)}subtract(t2){let n=e7.from(t2),r=this.value-n.value;if(r<0n)throw new k(`Amount underflow: ${this.value} - ${n.value} would be negative`);return new e7(r)}multiplyBy(t2){let n=e7.from(t2).value;return new e7(this.value*n)}divideBy(t2){let n=e7.from(t2).value;if(n<=0n)throw new k(`Divisor must be > 0, got ${n}`);return new e7(this.value/n)}modulo(t2){let n=e7.from(t2).value;if(n<=0n)throw new k(`Divisor must be > 0, got ${n}`);return new e7(this.value%n)}ceilPercent(t2,n=100){if(!Number.isSafeInteger(t2)||t2<0)throw new k(`ceilPercent: numerator must be a non-negative integer, got ${t2}`);if(!Number.isSafeInteger(n)||n<=0)throw new k(`ceilPercent: denominator must be a positive integer, got ${n}`);let r=BigInt(t2),i=BigInt(n);return new e7((this.value*r+(i-1n))/i)}floorPercent(t2,n=100){if(!Number.isSafeInteger(t2)||t2<0)throw new k(`floorPercent: numerator must be a non-negative integer, got ${t2}`);if(!Number.isSafeInteger(n)||n<=0)throw new k(`floorPercent: denominator must be a positive integer, got ${n}`);let r=BigInt(t2),i=BigInt(n);return new e7(this.value*r/i)}inRange(t2,n){let r=e7.from(t2),i=e7.from(n);if(r.greaterThan(i))throw new k(`inRange: min (${r.toString()}) must be <= max (${i.toString()})`);return this.greaterThanOrEqual(r)&&this.lessThanOrEqual(i)}clamp(t2,n){let r=e7.from(t2),i=e7.from(n);if(r.greaterThan(i))throw new k(`clamp: min (${r.toString()}) must be <= max (${i.toString()})`);return e7.max(r,e7.min(i,this))}scaledBy(t2,n){let r=e7.from(t2).value,i=e7.from(n).value;if(i===0n)throw new k("scaledBy: denominator must be > 0");return r===0n?e7.zero():new e7((2n*this.value*r+i)/(2n*i))}isSafeNumber(){let e17=BigInt(2**53-1);return this.value<=e17}isZero(){return this.value===0n}equals(t2){return this.value===e7.from(t2).value}compareTo(t2){let n=e7.from(t2).value;return this.value<n?-1:+(this.value>n)}lessThan(e17){return this.compareTo(e17)<0}lessThanOrEqual(e17){return this.compareTo(e17)<=0}greaterThan(e17){return this.compareTo(e17)>0}greaterThanOrEqual(e17){return this.compareTo(e17)>=0}static min(t2,n){let r=e7.from(t2),i=e7.from(n);return r.compareTo(i)<=0?r:i}static max(t2,n){let r=e7.from(t2),i=e7.from(n);return r.compareTo(i)>=0?r:i}static sum(t2){let n=0n;for(let r of t2)n+=e7.from(r).value;return new e7(n)}withUnit(e17){return new Me(this,e17)}};var je=class e8 extends b{constructor(t2){super(t2),this.name="AmountWithUnitError",Object.setPrototypeOf(this,e8.prototype)}};var Me=class e9{constructor(e17,t2){if(typeof t2!="string"||t2.length===0)throw new je("unit required");this._amount=e17,this.unit=t2,Object.freeze(this)}static from(t2,n){return new e9(A.from(t2),n)}static zero(t2){return new e9(A.zero(),t2)}static one(t2){return new e9(A.one(),t2)}toAmount(){return this._amount}toBigInt(){return this._amount.toBigInt()}toNumber(){return this._amount.toNumber()}toString(){return`[${this.unit}]: ${this._amount.toString()}`}toJSON(){return{amount:this._amount.toString(),unit:this.unit}}[Symbol.toPrimitive](e17){if(e17==="string")return this.toString();throw new je(`Implicit ${e17==="number"?"numeric":"default"} coercion of AmountWithUnit is unsafe; use .toAmount() then explicit arithmetic, or .toString() for display.`)}isZero(){return this._amount.isZero()}isSafeNumber(){return this._amount.isSafeNumber()}requireSameUnit(e17){if(this.unit!==e17.unit)throw new je(`unit mismatch: ${this.unit} vs ${e17.unit}`)}add(t2){return this.requireSameUnit(t2),new e9(this._amount.add(t2._amount),this.unit)}subtract(t2){return this.requireSameUnit(t2),new e9(this._amount.subtract(t2._amount),this.unit)}equals(e17){return this.requireSameUnit(e17),this._amount.equals(e17._amount)}compareTo(e17){return this.requireSameUnit(e17),this._amount.compareTo(e17._amount)}lessThan(e17){return this.compareTo(e17)<0}lessThanOrEqual(e17){return this.compareTo(e17)<=0}greaterThan(e17){return this.compareTo(e17)>0}greaterThanOrEqual(e17){return this.compareTo(e17)>=0}inRange(e17,t2){return this.requireSameUnit(e17),this.requireSameUnit(t2),this._amount.inRange(e17._amount,t2._amount)}clamp(t2,n){return this.requireSameUnit(t2),this.requireSameUnit(n),new e9(this._amount.clamp(t2._amount,n._amount),this.unit)}multiplyBy(t2){return new e9(this._amount.multiplyBy(t2),this.unit)}divideBy(t2){return new e9(this._amount.divideBy(t2),this.unit)}modulo(t2){return new e9(this._amount.modulo(t2),this.unit)}ceilPercent(t2,n){return new e9(this._amount.ceilPercent(t2,n),this.unit)}floorPercent(t2,n){return new e9(this._amount.floorPercent(t2,n),this.unit)}scaledBy(t2,n){return new e9(this._amount.scaledBy(t2,n),this.unit)}static min(e17,t2){return e17.requireSameUnit(t2),e17.compareTo(t2)<=0?e17:t2}static max(e17,t2){return e17.requireSameUnit(t2),e17.compareTo(t2)>=0?e17:t2}static sum(t2,n){let r=n,i=0n,a=false;for(let e17 of t2){if(r===void 0)r=e17.unit;else if(e17.unit!==r)throw new je(`unit mismatch: ${r} vs ${e17.unit}`);i+=e17._amount.toBigInt(),a=true}if(r===void 0)throw new je("cannot infer unit from empty sum");return new e9(a?A.from(i):A.zero(),r)}};var j=Object.freeze({parse:Ve,stringify:Ge});var Ne=64;var Pe;function Fe(e17){return typeof e17=="object"&&!!e17&&!Array.isArray(e17)}function Ie(){let e17=globalThis.BigInt;return typeof e17=="function"?e17:void 0}function Le(e17){if(!Pe){let t2=e17(String(2**53-1));Pe={max:t2,min:-t2}}return Pe}var Re=class{constructor(e17,t2,n,r){this.src=e17,this.strict=t2,this.fallbackTo=n,this.bigIntCtor=r,this.i=0}parse(){let e17=this.parseValue(0);if(this.skipWhitespace(),!this.isEnd())throw this.syntaxError("Unexpected trailing input");return e17}parseValue(e17){if(e17>Ne)throw this.syntaxError("JSON nesting exceeds the maximum depth");this.skipWhitespace();let t2=this.peek();if(t2==="{")return this.parseObject(e17);if(t2==="[")return this.parseArray(e17);if(t2==='"')return this.parseString();if(t2==="-"||this.isDigit(t2))return this.parseNumber();if(t2==="t")return this.parseLiteral("true",true);if(t2==="f")return this.parseLiteral("false",false);if(t2==="n")return this.parseLiteral("null",null);throw this.syntaxError(`Unexpected token '${t2||"EOF"}'`)}parseObject(e17){this.expect("{"),this.skipWhitespace();let t2={},n=new Set;if(this.peek()==="}")return this.expect("}"),t2;for(;!this.isEnd();){let r=this.parseString();if(this.strict&&n.has(r))throw this.syntaxError(`Duplicate key "${r}"`);if(n.add(r),this.skipWhitespace(),this.expect(":"),Object.defineProperty(t2,r,{value:this.parseValue(e17+1),writable:true,enumerable:true,configurable:true}),this.skipWhitespace(),this.peek()==="}")return this.expect("}"),t2;this.expect(","),this.skipWhitespace()}throw this.syntaxError("Unterminated object")}parseArray(e17){this.expect("["),this.skipWhitespace();let t2=[];if(this.peek()==="]")return this.expect("]"),t2;for(;!this.isEnd();){if(t2.push(this.parseValue(e17+1)),this.skipWhitespace(),this.peek()==="]")return this.expect("]"),t2;this.expect(","),this.skipWhitespace()}throw this.syntaxError("Unterminated array")}parseString(){this.expect('"');let e17="";for(;!this.isEnd();){let t2=this.next();if(t2==='"')return e17;if(t2==="\\"){let t3=this.next();switch(t3){case'"':case"\\":case"/":e17+=t3;break;case"b":e17+="\b";break;case"f":e17+="\f";break;case"n":e17+="\n";break;case"r":e17+="\r";break;case"t":e17+=" ";break;case"u":{let t4=this.src.slice(this.i,this.i+4);if(!/^[0-9a-fA-F]{4}$/.test(t4))throw this.syntaxError("Invalid unicode escape");this.i+=4,e17+=String.fromCharCode(parseInt(t4,16));break}default:throw this.syntaxError(`Invalid escape '\\${t3}'`)}continue}if(t2<" ")throw this.syntaxError("Invalid control character in string");e17+=t2}throw this.syntaxError("Unterminated string")}parseNumber(){let e17=this.i;this.peek()==="-"&&(this.i+=1),this.peek()==="0"?this.i+=1:this.readDigits(),this.peek()==="."&&(this.i+=1,this.readDigits());let t2=this.peek();if(t2==="e"||t2==="E"){this.i+=1;let e18=this.peek();(e18==="+"||e18==="-")&&(this.i+=1),this.readDigits()}let n=this.src.slice(e17,this.i);if(!(n.indexOf(".")===-1&&n.indexOf("e")===-1&&n.indexOf("E")===-1)){let e18=Number(n);if(!Number.isFinite(e18))throw this.syntaxError("Bad number");return e18}if(!this.bigIntCtor)switch(this.fallbackTo){case"number":{let e18=Number(n);if(!Number.isFinite(e18))throw this.syntaxError("Bad number");return e18}case"string":return n;case"error":throw new b("BigInt is not available in this runtime")}let r=this.bigIntCtor(n),{max:i,min:a}=Le(this.bigIntCtor);return r>i||r<a?r:Number(n)}parseLiteral(e17,t2){if(this.src.slice(this.i,this.i+e17.length)!==e17)throw this.syntaxError(`Unexpected token near '${this.src.slice(this.i,this.i+8)}'`);return this.i+=e17.length,t2}readDigits(){let e17=this.i;for(;this.isDigit(this.peek());)this.i+=1;if(this.i===e17)throw this.syntaxError("Bad number")}skipWhitespace(){for(;!this.isEnd();){let e17=this.peek();if(e17===" "||e17==="\n"||e17==="\r"||e17===" "){this.i+=1;continue}break}}expect(e17){if(this.next()!==e17)throw this.syntaxError(`Expected '${e17}'`)}peek(){return this.src.charAt(this.i)}next(){let e17=this.src.charAt(this.i);return this.i+=1,e17}isDigit(e17){return e17>="0"&&e17<="9"}isEnd(){return this.i>=this.src.length}syntaxError(e17){return SyntaxError(`${e17} at position ${this.i}`)}};function ze(e17,t2,n){Reflect.defineProperty(e17,t2,{value:n,writable:true,enumerable:true,configurable:true})}function Be(e17,t2,n){let r=Array.isArray(e17)?e17[Number(t2)]:e17[t2];if(Array.isArray(r))for(let e18=0;e18<r.length;e18+=1){let t3=Be(r,String(e18),n);t3===void 0?Reflect.deleteProperty(r,e18):ze(r,String(e18),t3)}else if(Fe(r))for(let e18 of Object.keys(r)){let t3=Be(r,e18,n);t3===void 0?delete r[e18]:ze(r,e18,t3)}return n.call(e17,t2,r)}function Ve(e17,t2,n){let r=n?.strict===true,i=n?.fallbackTo??"number";if(i!=="number"&&i!=="string"&&i!=="error")throw new b(`Incorrect value for fallbackTo option, must be "number", "string", "error" or undefined but passed ${String(n?.fallbackTo)}`);let a=new Re(String(e17),r,i,Ie()).parse();return typeof t2=="function"?Be({"":a},"",t2):a}function He(e17){let t2=JSON.stringify(e17);if(typeof t2!="string")throw new b("Failed to stringify string value");return t2}function Ue(e17){return typeof e17=="object"&&!!e17&&"toJSON"in e17&&typeof e17.toJSON=="function"}function We(e17){return e17 instanceof Number||e17 instanceof String||e17 instanceof Boolean?e17.valueOf():e17}function Ge(e17,t2,n){let r="",i="",a=new WeakSet;if(typeof n=="number"?i=" ".repeat(Math.min(10,Math.max(0,Math.floor(n)))):typeof n=="string"&&(i=n.slice(0,10)),t2&&typeof t2!="function"&&!Array.isArray(t2))throw new b("stringify: replacer must be a function or array");let o=Array.isArray(t2)?Array.from(new Set(t2.filter(e18=>typeof e18=="string"||typeof e18=="number").map(e18=>String(e18)))):void 0,s=(e18,n2)=>{let c=e18[n2];switch(c instanceof A?c=c.toBigInt():Ue(c)&&(c=c.toJSON(n2)),typeof t2=="function"&&(c=t2.call(e18,n2,c)),c=We(c),typeof c){case"string":return He(c);case"number":return Number.isFinite(c)?String(c):"null";case"boolean":return c?"true":"false";case"bigint":return String(c);case"undefined":return;case"object":{if(c===null)return"null";if(a.has(c))throw TypeError("Converting circular structure to JSON");a.add(c);let e19=r;r+=i;try{if(Array.isArray(c)){let t4=[],n4=c;for(let e20=0;e20<c.length;e20+=1){let r2=s(n4,String(e20));t4.push(r2??"null")}let i3=t4.length===0?"[]":r?`[
|
|
2427
2427
|
${r}${t4.join(`,
|
|
2428
2428
|
${r}`)}
|
|
2429
2429
|
${e19}]`:`[${t4.join(",")}]`;return r=e19,i3}let t3=c,n3=o??Object.keys(t3),i2=[];for(let e20 of n3){let n4=s(t3,e20);n4!==void 0&&i2.push(`${He(e20)}${r?": ":":"}${n4}`)}let a2=i2.length===0?"{}":r?`{
|
|
2430
2430
|
${r}${i2.join(`,
|
|
2431
2431
|
${r}`)}
|
|
2432
|
-
${e19}}`:`{${i2.join(",")}}`;return r=e19,a2}finally{a.delete(c)}}default:return}};return s({"":e17},"")}function Ke(e17){return e17.trim().replace(/[\t\n\f\r ]+/g,"").replace(/={1,2}$/,"")}function qe(e17){return base643.encode(e17)}function Je(e17){return base64urlnopad.encode(e17)}function Ye(e17){return base64url3.encode(e17)}function Xe(e17){try{return base64urlnopad.decode(Ke(e17))}catch(e18){throw new b("Invalid base64url string",{cause:e18})}}function Ze(e17){try{return base64nopad.decode(Ke(e17))}catch(e18){throw new b("Invalid base64 string",{cause:e18})}}function Qe(e17){try{return Xe(e17)}catch(t2){try{return Ze(e17)}catch{throw t2}}}function et(e17){if(typeof e17!="string"||e17.length===0)return false;let t2=Ke(e17);if(t2.length===0)return false;let n=/[-_]/.test(t2)?base64urlnopad:base64nopad;try{return n.encode(n.decode(t2))===t2}catch{return false}}function st(e17){let t2=[];return ct(e17,t2),new Uint8Array(t2)}function ct(e17,t2){if(e17===null)t2.push(246);else if(e17===void 0)t2.push(247);else if(typeof e17=="boolean")t2.push(e17?245:244);else if(typeof e17=="number")mt(e17,t2);else if(typeof e17=="bigint")ut(e17,t2);else if(typeof e17=="string")gt(e17,t2);else if(Array.isArray(e17))_t(e17,t2);else if(e17 instanceof Uint8Array)ht(e17,t2);else if(typeof e17=="object"&&e17&&!Array.isArray(e17))vt(e17,t2);else throw new b("Unsupported type")}function lt(e17,t2){e17<24?t2.push(e17):e17<256?t2.push(24,e17):e17<65536?t2.push(25,e17>>>8&255,e17&255):e17<4294967296?t2.push(26,e17>>>24&255,e17>>>16&255,e17>>>8&255,e17&255):ut(BigInt(e17),t2)}function ut(e17,t2){e17>=0n?dt(0,e17,t2):dt(1,-1n-e17,t2)}function dt(e17,t2,n){let r=e17<<5;if(t2<24n)n.push(r|Number(t2));else if(t2<256n)n.push(r|24,Number(t2));else if(t2<65536n){let e18=Number(t2);n.push(r|25,e18>>>8&255,e18&255)}else if(t2<4294967296n){let e18=Number(t2);n.push(r|26,e18>>>24&255,e18>>>16&255,e18>>>8&255,e18&255)}else if(t2<18446744073709551616n){let e18=Number(t2>>32n),i=Number(t2&4294967295n);n.push(r|27,e18>>>24&255,e18>>>16&255,e18>>>8&255,e18&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255)}else throw new b("BigInt value out of uint64 range")}function ft(e17,t2){let n=-1-e17;n<24?t2.push(32|n):n<256?t2.push(56,n&255):n<65536?t2.push(57,n>>>8&255,n&255):n<4294967296?t2.push(58,n>>>24&255,n>>>16&255,n>>>8&255,n&255):ut(BigInt(e17),t2)}function pt(e17,t2){let n=new DataView(new ArrayBuffer(8));n.setFloat64(0,e17,false),t2.push(251);for(let e18=0;e18<8;e18++)t2.push(n.getUint8(e18))}function mt(e17,t2){Number.isInteger(e17)?e17>=0?lt(e17,t2):ft(e17,t2):pt(e17,t2)}function ht(e17,t2){let n=e17.length;if(n<24)t2.push(64+n);else if(n<256)t2.push(88,n);else if(n<65536)t2.push(89,n>>8&255,n&255);else if(n<4294967296)t2.push(90,n>>>24&255,n>>>16&255,n>>>8&255,n&255);else throw new b("Byte string too long to encode");for(let n2=0;n2<e17.length;n2++)t2.push(e17[n2])}function gt(e17,t2){let n=new TextEncoder().encode(e17),r=n.length;if(r<24)t2.push(96+r);else if(r<256)t2.push(120,r);else if(r<65536)t2.push(121,r>>>8&255,r&255);else if(r<4294967296)t2.push(122,r>>>24&255,r>>>16&255,r>>>8&255,r&255);else throw new b("String too long to encode");for(let e18=0;e18<n.length;e18++)t2.push(n[e18])}function _t(e17,t2){let n=e17.length;if(n<24)t2.push(128|n);else if(n<256)t2.push(152,n);else if(n<65536)t2.push(153,n>>>8&255,n&255);else throw new b("Unsupported array length");for(let n2 of e17)ct(n2,t2)}function vt(e17,t2){let n=Object.keys(e17),r=n.length;if(r>=4294967296)throw new b("Object has too many keys to encode");r<24?t2.push(160|r):r<256?t2.push(184,r):r<65536?t2.push(185,r>>8&255,r&255):t2.push(186,r>>24&255,r>>16&255,r>>8&255,r&255);for(let r2 of n)gt(r2,t2),ct(e17[r2],t2)}var jt=utf8ToBytes3("Secp256k1_HashToCurve_Cashu_");function Mt(r){let i=sha2565(concatBytes(jt,r)),a=0,o=new Uint8Array(4),s=new DataView(o.buffer),c=2**16;for(let r2=0;r2<c;r2++){s.setUint32(0,a,true);let r3=sha2565(concatBytes(i,o));try{return P(bytesToHex2(concatBytes(new Uint8Array([2]),r3)))}catch{a++}}throw new b("No valid point found")}function Nt(t2){let n=t2.map(e17=>e17.toHex(false)).join("");return sha2565(new TextEncoder().encode(n))}function P(e17){return secp256k1.Point.fromHex(e17)}var Lt=e17=>{let t2,n=e18=>bytesToNumberBE(Qe(e18))%BigInt(2**31-1);if(e17.length===12&&et(e17))t2=n(e17);else if(V(e17))t2=wi(e17)%BigInt(2**31-1);else if(et(e17))t2=n(e17);else throw new b("Invalid keyset id: neither hex nor base64");return t2};function Rt(){return secp256k1.utils.randomSecretKey()}function Vt(e17,t2){let n=Mt(e17);if(t2===void 0)t2=secp256k1.Point.Fn.fromBytes(Rt());else if(t2===0n)throw new b("Blinding factor r must be non-zero");let r=secp256k1.Point.BASE.multiply(t2);return{B_:n.add(r),r:t2,secret:e17}}function Ht(e17,t2,n){return e17.subtract(n.multiply(t2))}function Ut(e17,t2,n,r){let i=Ht(e17.C_,t2,r);return{id:e17.id,secret:n,C:i}}var gn=utf8ToBytes3("Cashu_P2BK_v1");var _n=gn.slice();function vn(e17,n,r=true){let i=+!r,a=e17.length+i;if(a>11)throw new b(`Too many pubkeys, ${a} slots provided, maximum allowed is 11 in total`);if(!e17.length)return{blinded:[],Ehex:""};n=n??secp256k1.utils.randomSecretKey();let o=secp256k1.Point.Fn.fromBytes(n),s=secp256k1.getPublicKey(n,true);return{blinded:e17.map((e18,t2)=>{let n2=P(e18),r2=xn(n2,o,t2+i),a2=n2.add(secp256k1.Point.BASE.multiply(r2));if(a2.equals(secp256k1.Point.ZERO))throw new b("Blinded key at infinity");return a2.toHex(true)}),Ehex:bytesToHex2(s)}}function xn(t2,r,i){if(!Number.isInteger(i)||i<0||i>255)throw new b("P2BK: slot index must be an integer in [0, 255]");let a=t2.multiply(r).toBytes(true).slice(1),o=new Uint8Array([i&255]),s=bytesToNumberBE(sha2565(concatBytes(gn,a,o)));if((s===0n||s>=secp256k1.Point.CURVE().n)&&(s=bytesToNumberBE(sha2565(concatBytes(gn,a,o,new Uint8Array([255])))),s===0n||s>=secp256k1.Point.CURVE().n))throw new b("P2BK: tweak derivation failed");return s}var Sn={SIG_INPUTS:"SIG_INPUTS",SIG_ALL:"SIG_ALL"};var Cn=new Set(Object.values(Sn));function Dn(e17){let t2=e17.toLowerCase();if(t2.length===66&&(t2.startsWith("02")||t2.startsWith("03")))return t2;if(t2.length===64)return`02${t2}`;throw new b(`Invalid pubkey, expected 33 byte compressed or 32 byte x only, got length ${t2.length}`)}function L(e17){let t2=new Set,n=[];for(let r of e17){let e18=Dn(r),i=e18.slice(-64);t2.has(i)||(t2.add(i),n.push(e18))}return n}function On(e17){let t2=L(Array.isArray(e17.pubkey)?e17.pubkey:[e17.pubkey]),n=L(e17.refundKeys??[]),r=typeof e17.hashlock=="string"&&e17.hashlock.length>0;if(t2.length===0&&!r)throw new b("P2PK requires at least one pubkey");let i=+!!r+t2.length+n.length;if(i>11)throw new b(`Too many pubkeys, ${i} slots provided, maximum allowed is 11 in total`);e17.sigFlag!==void 0&&Wn(e17.sigFlag);let a=t2.length>0?e17.requiredSignatures??1:e17.requiredSignatures,o=e17.requiredRefundSignatures;return Kn({mainKeyCount:t2.length,refundKeyCount:n.length,nSigs:a,nSigsRefund:o,hasLocktime:e17.locktime!==void 0}),{pubkey:t2.length===1?t2[0]:t2,...e17.locktime===void 0?{}:{locktime:e17.locktime},...n.length>0?{refundKeys:n}:{},...a!==void 0&&a>1?{requiredSignatures:a}:{},...o!==void 0&&o>1?{requiredRefundSignatures:o}:{},...e17.additionalTags?.length?{additionalTags:e17.additionalTags}:{},...e17.blindKeys?{blindKeys:true}:{},...e17.sigFlag===void 0?{}:{sigFlag:e17.sigFlag},...e17.hashlock?{hashlock:e17.hashlock}:{}}}function Wn(e17){if(!Cn.has(e17))throw new b(`Invalid sigflag "${e17}": must be "SIG_INPUTS" or "SIG_ALL"`)}function Gn(e17,t2){if(!Number.isInteger(e17)||e17<1)throw new b(`${t2} must be a positive integer, got ${e17}`);return e17}function Kn(e17){let{mainKeyCount:t2,refundKeyCount:n,nSigs:r,nSigsRefund:i,hasLocktime:a}=e17;if(r!==void 0&&(Gn(r,"requiredSignatures (n_sigs)"),r>t2))throw new b(`requiredSignatures (n_sigs) (${r}) exceeds available pubkeys (${t2})`);if(i!==void 0){if(Gn(i,"requiredRefundSignatures (n_sigs_refund)"),n===0)throw new b("requiredRefundSignatures (n_sigs_refund) requires refund keys");if(i>n)throw new b(`requiredRefundSignatures (n_sigs_refund) (${i}) exceeds available refund keys (${n})`)}if(n>0&&!a)throw new b("refund keys require a locktime")}var $n=utf8ToBytes3("Cashu_DLEQ_R_v1");var tr=(e17,t2,n,r)=>{let i=secp256k1.Point.Fn.fromBytes(e17.s),a=secp256k1.Point.Fn.fromBytes(e17.e),o=secp256k1.Point.BASE.multiply(i),s=r.multiply(a),c=t2.multiply(i),l=n.multiply(a);return equalBytes2(Nt([o.subtract(s),c.subtract(l),r,n]),e17.e)};var nr=(e17,t2,n,r)=>{if(t2.r===void 0)throw new b("verifyDLEQProof_reblind: Undefined blinding factor");let i=Mt(e17),a=n.add(r.multiply(t2.r)),o=secp256k1.Point.BASE.multiply(t2.r);return tr(t2,i.add(o),a,r)};var ir="m/129372'/0'";var ar=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");var or=(function(e17){return e17[e17.SECRET=0]="SECRET",e17[e17.BLINDING_FACTOR=1]="BLINDING_FACTOR",e17})(or||{});var sr=(function(e17){return e17[e17.DEPRECATED_BIP32=0]="DEPRECATED_BIP32",e17[e17.HMAC_SHA256=1]="HMAC_SHA256",e17})(sr||{});function ur(e17,t2,n){return dr(e17,t2)(n)}function dr(e17,t2){switch(pr(e17),fr(t2)){case sr.DEPRECATED_BIP32:{let n=Lt(t2),r=HDKey.fromMasterSeed(e17).derive(`${ir}/${n}'`);return e18=>mr(r,e18)}case sr.HMAC_SHA256:return n=>hr(e17,t2,n)}}function fr(e17){if(e17.length===12&&et(e17))return sr.DEPRECATED_BIP32;let t2=/^[a-fA-F0-9]+$/.test(e17),n=e17.startsWith("01");if(t2&&n&&e17.length%2!=0)throw new b("Invalid hex string: odd length.");if(!t2&&et(e17)||t2&&e17.startsWith("00"))return sr.DEPRECATED_BIP32;if(t2&&n)return sr.HMAC_SHA256;throw new b(`Unrecognized keyset ID version ${e17.slice(0,2)}`)}function pr(e17){if(!(e17 instanceof Uint8Array)||e17.length<16||e17.length>64)throw new b("seed must be a 16 to 64 byte Uint8Array")}function mr(e17,t2){if(!Number.isInteger(t2)||t2<0||t2>=2147483648)throw new b("Counter must be an integer in the range 0 <= counter < 2^31");let n=e17.deriveChild(HARDENED_OFFSET+t2),r=n.deriveChild(0).privateKey,i=n.deriveChild(1).privateKey;if(r===null||i===null)throw new b("Could not derive private key");return{secret:r,blindingFactor:i}}function hr(e17,t2,n){if(!Number.isSafeInteger(n)||n<0)throw new b("Counter must be an integer in the range 0 <= counter <= 2^53 - 1");return{secret:gr(e17,t2,n,or.SECRET),blindingFactor:gr(e17,t2,n,or.BLINDING_FACTOR)}}function gr(t2,i,o,s){let c=concatBytes(utf8ToBytes3("Cashu_KDF_HMAC_SHA256"),hexToBytes2(i),numberToBytesBE(o,8));switch(s){case or.SECRET:c=concatBytes(c,hexToBytes2("00"));break;case or.BLINDING_FACTOR:c=concatBytes(c,hexToBytes2("01"))}let l=hmac2(sha2565,t2,c);if(s===or.BLINDING_FACTOR){let e17=bytesToNumberBE(l),t3=e17>=ar?e17-ar:e17;if(t3===0n)throw new b("Derived invalid blinding scalar r == 0");return numberToBytesBE(t3,32)}return l}var wr=utf8ToBytes3("Cashu_MintQuoteSig_v1");function B(e17,t2,n,r){let i=Ci(e17,"splitAmount.value",true),a=n?.map(e18=>Ci(e18,"splitAmount.split",true));if(a){if(a.length>8192)throw new b(`Cannot split amount: split would exceed ${ae} outputs`);let e18=A.sum(a);if(i.isZero()&&e18.isZero())return a;let n2=a.filter(e19=>!e19.isZero()),r2=A.sum(n2);if(r2.greaterThan(i))throw new b(`Split is greater than total amount: ${r2.toString()} > ${i.toString()}`);if(n2.some(e19=>!Si(e19,t2)))throw new b("Provided amount preferences do not match the amounts of the mint keyset.");if(r2.equals(i))return n2;a=n2,i=i.subtract(r2)}else a=[];let o=xi(t2,"desc");if(o.length===0)throw new b("Cannot split amount, keyset is inactive or contains no keys");for(let e18 of o){if(e18.isZero())continue;let t3=i.divideBy(e18),n2=ae-a.length;if(n2<=0||t3.greaterThan(n2))throw new b(`Cannot split amount: fill would exceed ${ae} outputs`);let r2=t3.toNumber();for(let t4=0;t4<r2;t4++)a.push(e18);if(i=i.subtract(e18.multiplyBy(t3)),i.isZero())break}if(!i.isZero())throw new b(`Unable to split remaining amount: ${i.toString()}`);return r&&(a=a.sort((e18,t3)=>r==="desc"?t3.compareTo(e18):e18.compareTo(t3))),a}function xi(e17,t2){let n=Object.keys(e17).map(e18=>A.from(e18));return n.sort((e18,n2)=>t2==="desc"?n2.compareTo(e18):e18.compareTo(n2)),n}function Si(e17,t2){let n=Ci(e17,"hasCorrespondingKey.amount",true).toString();return Object.prototype.hasOwnProperty.call(t2,n)}function Ci(e17,t2,n=false){let r=A.from(e17);if(!n&&r.isZero())throw new b(`Amount must be positive: ${r.toString()}, op: ${t2}`);return r}function wi(e17){return e17?BigInt(`0x${e17}`):0n}function Ti(e17){return e17.toString(16).padStart(64,"0")}function V(e17){return typeof e17=="string"&&e17.length%2==0&&/^[a-f0-9]+$/i.test(e17)}function Ei(e17){return Array.isArray(e17)?e17.some(e18=>!V(e18.id)):!V(e17.id)}function Oi(e17){return e17.map(e18=>{let t2={...e18};return t2.id=t2.id.slice(0,16),t2})}function ki(e17,t2){let n=q(e17.proofs);if(Ei(n))throw new b("Proofs contain a legacy keyset ID and cannot be encoded. Swap them at the mint first.");return Ai({...e17,proofs:n},t2?.removeDleq)}function Ai(e17,t2){let n=e17.proofs;if(t2&&(n=Ki(n)),Ei(n))throw new b("can not encode to v4 token if proofs contain non-hex keyset id");return n=Oi(n),"cashuB"+Je(st(Mi({...e17,proofs:n})))}function ji(e17){if(e17.r==null)throw new b("Missing blinding factor in included DLEQ proof");return{e:hexToBytes2(e17.e),s:hexToBytes2(e17.s),r:hexToBytes2(e17.r)}}function Mi(e17){let t2=Object.create(null),n=e17.mint;for(let n2=0;n2<e17.proofs.length;n2++){let r=e17.proofs[n2];t2[r.id]?t2[r.id].push(r):t2[r.id]=[r]}let i={m:n,u:e17.unit||"sat",t:Object.keys(t2).map(e18=>({i:hexToBytes2(e18),p:t2[e18].map(e19=>({a:e19.amount.toBigInt(),s:e19.secret,c:hexToBytes2(e19.C),...e19.dleq&&{d:ji(e19.dleq)},...e19.p2pk_e&&{pe:hexToBytes2(e19.p2pk_e)},...e19.witness&&{w:JSON.stringify(e19.witness)}}))}))};return e17.memo&&(i.d=e17.memo),i}function zi(n,i){for(let e17 of Object.keys(n))if(e17.length>20)throw new b("Invalid keyset denomination: exceeds 20 digits");let o=i?.unit??"sat",s=i?.expiry,c=i?.versionByte??1,l=i?.input_fee_ppk;if(i?.isDeprecatedBase64??false)return qe(sha2565(utf8ToBytes3(Object.entries(n).sort(([e17],[t2])=>A.from(e17).compareTo(t2)).map(([,e17])=>e17).reduce((e17,t2)=>e17+t2,"")))).slice(0,12);switch(c){case 0:return"00"+bytesToHex2(sha2565(Bi(...Object.entries(n).sort(([e17],[t2])=>A.from(e17).compareTo(t2)).map(([,e17])=>hexToBytes2(e17))))).slice(0,14);case 1:{if(!o)throw new b("Cannot compute keyset ID version 01: unit is required.");let r=Object.entries(n).sort(([e17],[t2])=>A.from(e17).compareTo(t2)).map(([e17,t2])=>`${e17}:${t2}`).join(",");return r+=`|unit:${o}`,l&&(r+=`|input_fee_ppk:${l}`),s&&(r+=`|final_expiry:${s}`),"01"+bytesToHex2(sha2565(utf8ToBytes3(r)))}default:throw new b(`Unrecognized keyset ID version: ${c}`)}}function Bi(...e17){let t2=e17.reduce((e18,t3)=>e18+t3.length,0),n=new Uint8Array(t2),r=0;for(let t3 of e17)n.set(t3,r),r+=t3.length;return n}function H(e17){return typeof e17=="object"&&!!e17}function U(e17){return H(e17)&&!Array.isArray(e17)}function W(e17,...t2){for(let n of t2)e17[n]===void 0&&(e17[n]=null)}function G(...e17){return e17.map(e18=>e18.replace(/(^\/+|\/+$)/g,"")).join("/")}function Hi(e17){let t2;try{t2=new URL(e17)}catch(t3){throw new b(`Invalid mint URL: ${e17}`,{cause:t3})}if(t2.protocol!=="http:"&&t2.protocol!=="https:")throw new b(`Invalid mint URL scheme: ${t2.protocol}`);if(t2.username||t2.password)throw new b("Mint URL must not contain credentials");if(t2.search||t2.href.includes("?"))throw new b("Mint URL must not contain query parameters");if(t2.hash||t2.href.includes("#"))throw new b("Mint URL must not contain a fragment");if(/%[0-9a-f]{2}/i.test(t2.pathname))throw new b("Mint URL path must not contain percent-encoded characters");return t2.href.replace(/\/+$/,"")}function q(e17){return e17.map(e18=>({...e18,amount:A.from(e18.amount)}))}function Ki(e17){return e17.map(e18=>{let{dleq:t2,...n}=e18;return n})}function Ji(e17,t2,n){let i=n?.require??true;if(!Si(e17.amount,t2.keys))throw new b(Object.keys(t2.keys).length===0?`No keys loaded for keyset ${t2.id}`:`Undefined key for amount ${e17.amount.toString()} in keyset ${t2.id}`);if(e17?.dleq==null)return!i;if(e17.dleq.r==null)return false;let a=t2.keys[e17.amount.toString()];try{let t3={e:hexToBytes2(e17.dleq.e),s:hexToBytes2(e17.dleq.s),r:wi(e17.dleq.r)};return nr(new TextEncoder().encode(e17.secret),t3,P(e17.C),P(a))}catch{return false}}function J(e17,t2,n){if(e17==null){if(arguments.length>=3)return n;throw new b(`Invalid ${t2}: missing value`)}try{return A.from(e17).toNumber()}catch(e18){throw new b(`Invalid ${t2}: ${e18 instanceof Error?e18.message:String(e18)}`,{cause:e18})}}function ra(e17){return{...e17,input_fee_ppk:J(e17.input_fee_ppk,"keyset.input_fee_ppk",void 0),final_expiry:J(e17.final_expiry,"keyset.final_expiry",void 0)}}function ia(e17){return{...e17,input_fee_ppk:J(e17.input_fee_ppk,"keys.input_fee_ppk",void 0),final_expiry:J(e17.final_expiry,"keys.final_expiry",void 0)}}function aa(e17,t2){let n;try{n=new URL(e17).protocol}catch{throw new b(`OIDCAuth: ${t2} is not a valid URL`)}if(n!=="https:"&&n!=="http:")throw new b(`OIDCAuth: ${t2} must be an http(s) URL`)}var oa=class t{static fromMintInfo(e17,n){let r=e17?.nuts?.["21"];if(!r?.openid_discovery)throw new b("OIDCAuth: mint does not advertise NUT-21 openid_discovery");let i=n?.clientId??r.client_id??"cashu-client";return new t(r.openid_discovery,{...n,clientId:i})}constructor(e17,t2){this.tokenListeners=[],this.inflightRefreshes=new Map,this.discoveryUrl=e17,this.logger=t2?.logger??E,this.clientId=t2?.clientId??"cashu-client",this.scope=t2?.scope??"openid",this.onTokens=t2?.onTokens}setClient(e17){this.clientId=e17}setScope(e17){this.scope=e17??"openid"}addTokenListener(e17){this.tokenListeners=[...this.tokenListeners,e17]}removeTokenListener(e17){this.tokenListeners=this.tokenListeners.filter(t2=>t2!==e17)}async loadConfig(){if(this.config)return this.config;let e17=await fetch(this.discoveryUrl,{method:"GET",headers:{Accept:"application/json"}}),t2=await e17.text(),n,r;try{n=t2?JSON.parse(t2):void 0}catch(e18){r=e18,this.logger.warn("OIDCAuth: bad discovery JSON",{err:e18})}if(!e17.ok||!n)throw new b("OIDCAuth: invalid discovery document",{cause:r});let i=n;if(typeof i.token_endpoint!="string"||i.token_endpoint.length===0)throw new b("OIDCAuth: invalid discovery document, missing token_endpoint");return this.config=i,i}generatePKCE(){let t2=Je(randomBytes3(48));return{verifier:t2,challenge:Je(sha2565(utf8ToBytes3(t2)))}}async buildAuthCodeUrl(e17){let t2=await this.loadConfig(),n=e17.scope??this.scope,r=e17.codeChallengeMethod;r!==void 0&&r!=="S256"&&this.logger.warn(`OIDCAuth: codeChallengeMethod '${typeof r=="string"?r:typeof r}' is not supported by cashu-ts v5, which accepts S256 only.`);let i=new URLSearchParams({response_type:"code",client_id:this.clientId,redirect_uri:e17.redirectUri,scope:n,code_challenge_method:e17.codeChallengeMethod??"S256",code_challenge:e17.codeChallenge});if(e17.state&&i.set("state",e17.state),!t2.authorization_endpoint)throw new b("OIDCAuth: discovery lacks authorization_endpoint");return aa(t2.authorization_endpoint,"authorization_endpoint"),`${t2.authorization_endpoint}?${i.toString()}`}async exchangeAuthCode(e17){let t2=await this.loadConfig(),n=this.toForm({grant_type:"authorization_code",code:e17.code,redirect_uri:e17.redirectUri,client_id:this.clientId,code_verifier:e17.codeVerifier}),r=await this.postFormStrict(t2.token_endpoint,n);return this.handleTokens(r,"signin"),r}async deviceStart(){let e17=(await this.loadConfig()).device_authorization_endpoint;if(!e17)throw new b("OIDCAuth: provider lacks device_authorization_endpoint");let t2=this.toForm({client_id:this.clientId,scope:this.scope}),n=await this.postFormStrict(e17,t2);return aa(n.verification_uri,"verification_uri"),n.verification_uri_complete!==void 0&&aa(n.verification_uri_complete,"verification_uri_complete"),n}async devicePoll(e17,t2=5){let n=await this.loadConfig(),r=Number(t2),i=Number.isFinite(r)?Math.max(1,r):5;for(;;){await this.sleep(i*1e3);let t3=this.toForm({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e17,client_id:this.clientId}),r2=await this.postFormLoose(n.token_endpoint,t3);if(r2.access_token)return this.handleTokens(r2,"signin",this.tokenListeners),r2;let a=(r2.error??"").toString();if(a!=="authorization_pending"){if(a==="slow_down"){i=Math.max(i+5,i*2);continue}throw new b(`OIDCAuth: ${r2.error_description||a||"device authorization failed"}`)}}}async startDeviceAuth(e17=5){let t2=await this.deviceStart(),n=Number(t2.interval),r=Number.isFinite(n)&&n>0?n:1,i=Number(e17),a=Math.max(r,Number.isFinite(i)?i:5),o=new AbortController,s,c=new Promise(e18=>{s=e18}),l=new Set,u=()=>{if(o.signal.aborted)throw new b("OIDCAuth: device polling cancelled")},d=async()=>{let e18=await this.loadConfig(),n2=Math.max(1,a);for(;;){u();let r2;await this.sleep(n2*1e3,e19=>{r2=e19,l.add(e19)}),l.delete(r2),u();let i2=this.toForm({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t2.device_code,client_id:this.clientId}),a2=await this.postFormLoose(e18.token_endpoint,i2,o.signal);if(u(),a2.access_token)return this.handleTokens(a2,"signin"),a2;let s2=(a2.error??"").toString();if(s2!=="authorization_pending"){if(s2==="slow_down"){n2=Math.max(n2+5,n2*2);continue}throw new b(`OIDCAuth: ${a2.error_description||s2||"device authorization failed"}`)}}},f=()=>{o.abort(),s();for(let e18 of l)e18();l.clear()};return{...t2,poll:()=>Promise.race([d(),c.then(()=>{throw new b("OIDCAuth: device polling cancelled")})]),cancel:f}}async refresh(e17){let t2=this.clientId,n=this.tokenListeners,r=this.inflightRefreshes.get(e17);if(r?.listeners===n&&r.clientId===t2)return r.promise;let i=(async()=>{let r2=await this.loadConfig(),i2=this.toForm({grant_type:"refresh_token",refresh_token:e17,client_id:t2}),a=await this.postFormStrict(r2.token_endpoint,i2);return a.refresh_token||(a.refresh_token=e17),this.handleTokens(a,"refresh",n),a})();this.inflightRefreshes.set(e17,{clientId:t2,listeners:n,promise:i});try{return await i}finally{this.inflightRefreshes.get(e17)?.promise===i&&this.inflightRefreshes.delete(e17)}}async passwordGrant(e17,t2){let n=await this.loadConfig(),r=this.toForm({grant_type:"password",client_id:this.clientId,username:e17,password:t2,scope:this.scope}),i=await this.postFormStrict(n.token_endpoint,r);return this.handleTokens(i,"signin"),i}handleTokens(e17,t2,n=this.tokenListeners){if(!e17.access_token)throw new b(`OIDCAuth: ${e17.error_description||e17.error||"token response missing access_token"}`);queueMicrotask(()=>O(e18=>this.onTokens?.(e18,t2),e17,this.logger,{where:"OIDCAuth.handleTokens"}));let r=new Set(this.tokenListeners);for(let i of n)r.has(i)&&queueMicrotask(()=>O(e18=>i(e18,t2),e17,this.logger,{where:"OIDCAuth.handleTokens.listener"}))}toForm(e17){let t2=e18=>encodeURIComponent(e18).replace(/%20/g,"+");return Object.entries(e17).map(([e18,n])=>`${t2(e18)}=${t2(n)}`).join("&")}async postFormStrict(e17,t2){try{let n=await fetch(e17,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t2,redirect:"error"}),r=await n.text(),i,a;try{i=r?JSON.parse(r):void 0}catch(e18){a=e18,this.logger.warn("OIDCAuth: bad JSON (strict)",{err:e18})}if(!n.ok){let e18=i??{};throw new b(`OIDCAuth: ${e18.error_description||e18.error||`HTTP ${n.status}`}`,{cause:a})}return this.logger.debug("OIDCAuth Response",{status:n.status}),i??{}}catch(e18){throw this.logger.error("OIDCAuth: postFormStrict failed",{err:e18}),e18}}async postFormLoose(e17,t2,n){try{let r=await fetch(e17,{method:"POST",signal:n,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t2,redirect:"error"}),i=await r.text(),a;try{a=i?JSON.parse(i):void 0}catch(e18){this.logger.warn("OIDCAuth: bad JSON (loose)",{err:e18})}return this.logger.debug("OIDCAuth Response",{status:r.status}),a??{}}catch(e18){return this.logger.error("OIDCAuth: postFormLoose network error",{err:e18}),{error:"network_error",error_description:String(e18)}}}sleep(e17,t2){let n=Math.min(e17,ue);return new Promise(e18=>{let r=setTimeout(e18,n);t2?.(()=>{clearTimeout(r),e18()})})}};var Y=class e10{constructor(t2,n){let r=n??E;this._mintInfo=e10.normalizeInfo(t2,r),this._maxArrayLength=e10.resolveMaxArrayLength(t2.max_array_length,r);let i=this.toEndpoints(this._mintInfo?.nuts?.[22]?.protected_endpoints,r);this._protected22=this.buildIndex(i);let a=this.toEndpoints(this._mintInfo?.nuts?.[21]?.protected_endpoints,r);this._protected21=this.buildIndex(a)}static normalizeInfo(t2,n=E){if(!U(t2)||!U(t2.nuts))throw n.error("MintInfo: malformed info response",{op:"normalizeInfo"}),new b("Invalid response from mint");return{...t2,...Array.isArray(t2.contact)?{contact:e10.capList(t2.contact,"contact",n)}:{},...Array.isArray(t2.urls)?{urls:e10.capList(t2.urls,"urls",n)}:{},nuts:{...t2.nuts,...t2.nuts[4]?{4:e10.normalizeSwapSection(t2.nuts[4],"nuts.4",n)}:{},...t2.nuts[5]?{5:e10.normalizeSwapSection(t2.nuts[5],"nuts.5",n)}:{},...t2.nuts[15]?{15:e10.normalizeNut15(t2.nuts[15],n)}:{},...t2.nuts[17]?{17:e10.normalizeNut17(t2.nuts[17],n)}:{},...t2.nuts[19]?{19:e10.normalizeNut19(t2.nuts[19],n)}:{},...t2.nuts[21]?{21:e10.normalizeNut21(t2.nuts[21],n)}:{},...t2.nuts[22]?{22:e10.normalizeNut22(t2.nuts[22],n)}:{},...t2.nuts[29]?{29:e10.normalizeNut29(t2.nuts[29],n)}:{}}}}static dropSection(e17,t2){t2.warn(`MintInfo: ${e17} is malformed and was omitted`)}static normalizeSwapSection(t2,n,r){if(!U(t2))throw r.error("MintInfo: malformed info response",{op:n}),new b("Invalid response from mint");return{...t2,methods:e10.normalizeSwapMethods(t2.methods,r)}}static normalizeSwapMethods(t2,n){return Array.isArray(t2)?e10.capList(t2,"nuts.4/5.methods",n).filter(e17=>U(e17)).map(e17=>{let t3={...e17};return W(t3,"min_amount","max_amount"),t3}):(n.warn("MintInfo: nuts.4/5.methods is malformed and was omitted"),[])}static resolveMaxArrayLength(e17,t2){if(e17==null)return 500;let n;try{n=J(e17,"max_array_length")}catch{return t2.warn("MintInfo: max_array_length is malformed, defaulting to internal default",{value:e17}),500}if(n<1||n>1e4){let e18=Math.min(Math.max(n,1),oe);return t2.warn("MintInfo: max_array_length is out of range and was clamped",{advertised:n,clampedTo:e18}),e18}return n}static normalizeNut15(t2,n){return U(t2)?Array.isArray(t2.methods)?{...t2,methods:e10.capList(t2.methods,"nuts.15.methods",n)}:t2:e10.dropSection("nuts.15",n)}static normalizeNut17(t2,n){return U(t2)?Array.isArray(t2.supported)?{...t2,supported:e10.capList(t2.supported,"nuts.17.supported",n)}:t2:e10.dropSection("nuts.17",n)}static normalizeNut19(t2,n){return U(t2)?{...t2,...Array.isArray(t2.cached_endpoints)?{cached_endpoints:e10.capList(t2.cached_endpoints,"nuts.19.cached_endpoints",n)}:{},ttl:J(t2.ttl,"nuts.19.ttl",null)}:e10.dropSection("nuts.19",n)}static normalizeNut21(t2,n){return U(t2)?Array.isArray(t2.protected_endpoints)?{...t2,protected_endpoints:e10.capList(t2.protected_endpoints,"nuts.21.protected_endpoints",n)}:t2:e10.dropSection("nuts.21",n)}static normalizeNut22(t2,n){if(!U(t2))return e10.dropSection("nuts.22",n);let r=100;try{r=J(t2.bat_max_mint,"nuts.22.bat_max_mint",100)}catch{n.warn("MintInfo: nuts.22.bat_max_mint is malformed, defaulting to internal cap",{value:t2.bat_max_mint})}return r>100&&(n.warn("MintInfo: nuts.22.bat_max_mint exceeds internal cap and was clamped",{advertised:r,clampedTo:100}),r=100),{...t2,...Array.isArray(t2.protected_endpoints)?{protected_endpoints:e10.capList(t2.protected_endpoints,"nuts.22.protected_endpoints",n)}:{},bat_max_mint:r}}static normalizeNut29(t2,n){if(!U(t2))return e10.dropSection("nuts.29",n);let r=100;try{r=J(t2.max_batch_size,"nuts.29.max_batch_size",100)}catch{n.warn("MintInfo: nuts.29.max_batch_size is malformed, defaulting to internal cap",{value:t2.max_batch_size})}return r>100&&(n.warn("MintInfo: nuts.29.max_batch_size exceeds internal cap and was clamped",{advertised:r,clampedTo:100}),r=100),{methods:Array.isArray(t2.methods)?e10.capList(t2.methods,"nuts.29.methods",n):t2.methods,max_batch_size:r}}isSupported(e17){switch(e17){case 4:case 5:return this.checkMintMelt(e17);case 7:case 8:case 9:case 10:case 11:case 12:case 14:case 20:return this.checkGenericNut(e17);case 17:return this.checkNut17();case 15:return this.checkNut15();case 19:return this.checkNut19();case 29:return this.checkNut29();default:throw new b("nut is not supported by cashu-ts")}}requiresBlindAuthToken(e17,t2){return this.matchesProtected(this._protected22,e17,t2)}requiresClearAuthToken(e17,t2){return this.matchesProtected(this._protected21,e17,t2)}matchesProtected(e17,t2,n){if(!e17)return false;let r=e17.exact[t2],i=e17.prefix[t2];if(!r||!i)return false;if(e17.exact[t2].has(n))return true;for(let r2 of e17.prefix[t2])if(n.startsWith(r2))return true;return false}checkGenericNut(e17){return this._mintInfo.nuts[e17]?.supported?{supported:true}:{supported:false}}checkMintMelt(t2){let n=this._mintInfo.nuts[t2];return n&&n.methods.length>0&&!n.disabled?{disabled:false,params:e10.snapshot(n.methods)}:{disabled:true,params:e10.snapshot(n?.methods??[])}}checkNut17(){return this._mintInfo.nuts[17]&&this._mintInfo.nuts[17].supported.length>0?{supported:true,params:e10.snapshot(this._mintInfo.nuts[17].supported)}:{supported:false}}checkNut15(){return this._mintInfo.nuts[15]&&this._mintInfo.nuts[15].methods.length>0?{supported:true,params:e10.snapshot(this._mintInfo.nuts[15].methods)}:{supported:false}}checkNut19(){let t2=this._mintInfo.nuts?.[19];if(t2&&(t2?.cached_endpoints?.length||0)>0){let n=J(t2.ttl,"nuts.19.ttl",null);return{supported:true,params:{ttl:n===null?Infinity:Math.max(n,0)*1e3,cached_endpoints:e10.snapshot(t2.cached_endpoints)}}}return{supported:false}}checkNut29(){let t2=this._mintInfo.nuts?.[29];return t2?{supported:true,params:e10.snapshot(t2)}:{supported:false}}static capList(e17,t2,n){return e17.length<=1024?e17:(n.warn(`MintInfo: ${t2} exceeds internal cap and was truncated`,{advertised:e17.length,cap:se}),e17.slice(0,se))}toEndpoints(t2,n){if(!Array.isArray(t2))return[];let r=e10.capList(t2,"nuts.21/22.protected_endpoints",n),i=[];for(let e17 of r)if(e17&&typeof e17=="object"){let t3=e17,n2=t3.method,r2=t3.path;if(typeof n2=="string"&&typeof r2=="string"){let e18=n2.toUpperCase();(e18==="GET"||e18==="POST")&&i.push({method:e18,path:r2})}}return i}buildIndex(e17){if(!e17?.length)return;let t2={GET:new Set,POST:new Set},n={GET:[],POST:[]};for(let r of e17){let e18=r.path;if(e18.startsWith("^")&&(e18=e18.slice(1)),e18.endsWith("$")&&(e18=e18.slice(0,-1)),e18.endsWith(".*")){n[r.method].push(e18.slice(0,-2));continue}if(e18.endsWith("*")){n[r.method].push(e18.slice(0,-1));continue}t2[r.method].add(e18)}return n.GET.sort((e18,t3)=>t3.length-e18.length),n.POST.sort((e18,t3)=>t3.length-e18.length),{exact:t2,prefix:n}}static snapshot(t2,n=0){if(typeof t2!="object"||!t2||t2 instanceof A)return t2;if(n>64)throw new b("Mint info nesting exceeds 64 levels");if(Array.isArray(t2))return t2.map(t3=>e10.snapshot(t3,n+1));let r={};for(let[i,a]of Object.entries(t2))r[i]=e10.snapshot(a,n+1);return r}get cache(){return e10.snapshot(this._mintInfo)}get contact(){return e10.snapshot(this._mintInfo.contact)}get description(){return this._mintInfo.description}get description_long(){return this._mintInfo.description_long}get name(){return this._mintInfo.name}get pubkey(){return this._mintInfo.pubkey}get nuts(){return e10.snapshot(this._mintInfo.nuts)}get version(){return this._mintInfo.version}get motd(){return this._mintInfo.motd}get icon_url(){return this._mintInfo.icon_url}get urls(){return e10.snapshot(this._mintInfo.urls)}get time(){return this._mintInfo.time}get tos_url(){return this._mintInfo.tos_url}get maxArrayLength(){return this._maxArrayLength}supportsNut04Description(e17,t2){return this._mintInfo.nuts[4]?.methods.some(n=>n.method===e17&&(t2?n.unit===t2:true)&&(n.options?.description===true||n.description===true))}supportsMintMeltMethod(e17,t2,n){let{disabled:r,params:i}=this.isSupported(e17==="mint"?4:5);return r?false:i.some(e18=>e18.method===t2&&e18.unit===n)}supportsAmountless(e17="bolt11",t2="sat"){let n=this._mintInfo?.nuts?.[5]?.methods??[];return Array.isArray(n)?n.some(n2=>n2.method===e17&&n2.unit===t2&&n2.options?.amountless===true):false}};var sa={UNPAID:"UNPAID",PAID:"PAID",ISSUED:"ISSUED"};var ca={UNPAID:"UNPAID",PENDING:"PENDING",PAID:"PAID"};function ua(e17){return e17.window!==void 0&&e17.window.document!==void 0?true:e17.WorkerGlobalScope!==void 0&&e17.self!==void 0&&e17.self instanceof e17.WorkerGlobalScope}var da=ua(globalThis);function fa(e17,t2,n=da){return Pa({Accept:"application/json, text/plain, */*",...e17?{"Content-Type":"application/json"}:void 0,...n?void 0:{"User-Agent":"Mozilla/5.0"}},t2)}function pa(e17,t2){return e17 instanceof Error?e17.message:t2}function ma(e17,t2,n,r){if(t2?.signal.aborted)return new Ea(`Request timed out after ${n}ms`,{cause:e17});if(r?.aborted)return new X(pa(e17,"Request aborted by caller"))}async function ha(e17,t2){if(t2?.aborted)throw new b("response body read aborted");let n=e17.text();if(!t2)return n;n.catch(()=>void 0);let r,i=new Promise((e18,n2)=>{r=()=>n2(new b("response body read aborted")),t2.aborted?r():t2.addEventListener("abort",r,{once:true})});i.catch(()=>void 0);try{return await Promise.race([n,i])}finally{r&&t2.removeEventListener("abort",r)}}function ga(e17){if(e17===null)return;let t2=e17.trim();if(t2!==""){if(/^\d+$/.test(t2))return Math.max(Number(t2)*1e3,0);if(/[a-zA-Z]/.test(t2)){let e18=new Date(t2).getTime();if(!Number.isNaN(e18))return Math.max(e18-Date.now(),0)}}}var _a3={endpoint:true,requestBody:true,logger:true,ttl:true,cached_endpoints:true,requestTimeout:true,onResponseMeta:true};var va={};var ya=E;function xa(e17){ya=e17}var Sa=9;var Ca=1e3;var wa=100;var Ta=["blind-auth","clear-auth"];var X=class e11 extends S{constructor(t2){super(t2),this.name="CallerAbortError",Object.setPrototypeOf(this,e11.prototype)}};var Ea=class e12 extends S{constructor(t2,n){super(t2,n),this.name="UncancellableReadError",Object.setPrototypeOf(this,e12.prototype)}};function Da(e17){return e17 instanceof X||e17 instanceof Ea?false:e17 instanceof S?true:e17 instanceof x&&e17.status>=500}function Oa(e17,t2){return t2?new Promise((n,r)=>{if(t2.aborted){r(new X("Request aborted by caller"));return}let i=()=>{clearTimeout(a),t2.removeEventListener("abort",i),r(new X("Request aborted by caller"))};t2.addEventListener("abort",i,{once:true});let a=setTimeout(()=>{t2.removeEventListener("abort",i),n()},e17)}):new Promise(t3=>setTimeout(t3,e17))}function ka(e17){try{return new URL(e17).pathname}catch{return e17.startsWith("/")?e17.split(/[?#]/,1)[0]:void 0}}function Aa(e17,t2){return e17===t2?true:e17.endsWith(t2)}async function ja(e17){let{ttl:t2,cached_endpoints:n,endpoint:r}=e17,i=e17.logger??ya;if(Object.keys(e17.headers??{}).some(e18=>e18.toLowerCase()==="blind-auth"))return await Ma(e17);let a=ka(r),o=e17.method?.toUpperCase()??"GET";if(!(a!==void 0&&n?.some(e18=>Aa(a,e18.path)&&e18.method===o)&&t2))return await Ma(e17);let s=0,c=Date.now(),l=async()=>{try{return await Ma(e17)}catch(n2){if(Da(n2)){let r2=Date.now()-c;if(s<Sa&&(!t2||r2<t2)){let a2=Math.min(2**s*wa,Ca),o2=Math.random()*a2;if(r2+o2>t2)throw i.error(`Network Error: request abandoned after ${s} retries`,{e:n2,retries:s}),n2;return s++,i.info(`Network Error: attempting retry ${s} in ${o2}ms`,{e:n2,retries:s,delay:o2}),await Oa(o2,e17.signal),l()}}throw i.error("Request failed and could not be retried",{e:n2}),n2}};return l()}async function Ma(e17){let{endpoint:t2,requestBody:n,headers:r,requestTimeout:i,onResponseMeta:a,cached_endpoints:o,ttl:s,logger:c,...l}=e17,u=c??ya,d=n?j.stringify(n):void 0,f=fa(d,r),p=Object.keys(f).some(e18=>Ta.includes(e18.toLowerCase())),m=e17.signal??void 0;if(m?.aborted)throw new X("Request aborted by caller");let h=i===void 0?void 0:new AbortController,g=m,_,v;if(h)if(_=setTimeout(()=>h.abort(),i),!m)g=h.signal;else{let e18=new AbortController,t3=()=>e18.abort();m.addEventListener("abort",t3,{once:true}),h.signal.addEventListener("abort",t3,{once:true}),v=()=>{m.removeEventListener("abort",t3),h.signal.removeEventListener("abort",t3)},g=e18.signal}try{let e18;try{e18=await fetch(t2,{body:d,headers:f,cache:"no-store",credentials:"omit",referrer:"",referrerPolicy:"no-referrer",...d===void 0?void 0:{redirect:"error"},...l,...p?{redirect:"error"}:void 0,signal:g})}catch(e19){let t3=!!h?.signal.aborted,n3=!!m?.aborted;throw t3?new S(`Request timed out after ${i}ms`,{cause:e19}):n3?new X(pa(e19,"Request aborted by caller")):e19 instanceof Error&&(e19.name==="AbortError"||e19.name==="TimeoutError")?new S(e19.message,{cause:e19}):new S(pa(e19,"Network request failed"),{cause:e19})}let n2=ga(e18.headers.get("Retry-After"));if(a&&e18.headers&&O(a,{endpoint:t2,status:e18.status,retryAfterMs:n2,rateLimit:e18.headers.get("RateLimit")??void 0,rateLimitPolicy:e18.headers.get("RateLimit-Policy")??void 0,headers:e18.headers},u,{op:"request.onResponseMeta",status:e18.status,endpoint:t2}),!e18.ok){if(e18.status===429){let t4=e18.body;throw t4&&typeof t4.cancel=="function"&&t4.cancel().catch(()=>void 0),new T("429 Too Many Requests",n2)}let t3,r3;try{t3=Na(await ha(e18,g))}catch(e19){let n3=ma(e19,h,i,m);if(n3)throw n3;r3=e19,t3={error:"bad response"}}if(e18.status===400&&"code"in t3&&typeof t3.code=="number"&&"detail"in t3&&typeof t3.detail=="string")throw new te(t3.code,t3.detail);let a2="HTTP request failed";throw"error"in t3&&typeof t3.error=="string"?a2=t3.error:"detail"in t3&&typeof t3.detail=="string"&&(a2=t3.detail),new x(a2,e18.status,{cause:r3})}let r2;try{r2=await ha(e18,g)}catch(t3){throw ma(t3,h,i,m)||(u.error("Failed to read HTTP response",{err:t3}),new x("bad response",e18.status,{cause:t3}))}try{if(!r2)throw new b("Empty response body");return j.parse(r2,void 0,{strict:true})}catch(t3){throw u.error("Failed to parse HTTP response",{err:t3}),new x("bad response",e18.status,{cause:t3})}}finally{clearTimeout(_),v?.()}}function Na(e17){if(!e17)return{detail:"bad response"};let t2;try{t2=j.parse(e17,void 0,{strict:true})}catch{return{detail:e17}}return typeof t2=="object"&&t2&&("detail"in t2||"code"in t2||"error"in t2)?t2:{detail:t2}}function Pa(e17,t2){let n=new Map;for(let r of[e17,t2])for(let[e18,t3]of Object.entries(r??{}))n.set(e18.toLowerCase(),[e18,t3]);return Object.fromEntries(n.values())}async function Fa(e17){let t2=e17.onResponseMeta,n=va.onResponseMeta,r={...e17,...va};for(let t3 of Object.keys(_a3))e17[t3]!==void 0&&(r[t3]=e17[t3]);if(r.headers=Pa(va.headers,e17.headers),t2&&n&&t2!==n){let i=r.logger??ya;r.onResponseMeta=r2=>{O(t2,r2,i,{op:"request.onResponseMeta",scope:"per-request",endpoint:e17.endpoint}),O(n,r2,i,{op:"request.onResponseMeta",scope:"global",endpoint:e17.endpoint})}}return await ja(r)}var Ia;typeof WebSocket<"u"&&(Ia=WebSocket);function Ra(){if(Ia===void 0)throw new b("WebSocket implementation not initialized");return Ia}var za=1006;var Ba=class{constructor(e17){this.next=null,this.value=e17}};var Va=class{constructor(){this._first=null,this._last=null,this.size=0}enqueue(e17){let t2=new Ba(e17);return this._last?this._last.next=t2:this._first=t2,this._last=t2,this.size++,true}dequeue(){if(!this._first)return null;let e17=this._first;return this._first=e17.next,this._first||(this._last=null),this.size--,e17.value}};var Ha=class{constructor(e17,t2){this.subListeners={},this.rpcListeners={},this.rpcId=0,this.onCloseCallbacks=[],this._WS=Ra(),this.url=new URL(e17),this.messageQueue=new Va,this._logger=t2??E}setLogger(e17){this._logger=e17}connect(e17=1e4){return this.connectionPromise||(this.connectionPromise=new Promise((t2,n)=>{let r=false,i=false,a=null,o=e18=>{i||(i=true,a&&clearTimeout(a),this.abandonConnect=void 0,e18())};this.abandonConnect=e18=>o(()=>n(e18));let s=()=>{if(this.ws){try{this.ws.onopen=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.onclose=null}catch{}try{this.ws.close()}catch{}this.ws=void 0,this.stopMessageHandling()}},c=e18=>{this.connectionPromise=void 0,s();let t3=e18 instanceof Error?e18:new b(String(e18),{cause:e18});this.failPendingRpc(t3),o(()=>n(t3))},l;try{l=new this._WS(this.url.toString()),this.ws=l}catch(e18){c(e18);return}let u=()=>this.ws===l;a=setTimeout(()=>{c(new b(`WebSocket connect timeout after ${e17}ms`))},e17),l.onopen=()=>{u()&&(r=true,o(t2))},l.onerror=e18=>{if(u()){if(!r){c(new b("Failed to open WebSocket"));return}this._logger.error("WebSocket error after open",{ev:e18})}},l.onmessage=e18=>{if(u()){if(this.messageQueue.size>=1e4){this._logger.error("WebSocket message queue exceeded its bound, closing connection",{size:this.messageQueue.size});let e19=new b("WebSocket message queue exceeded its bound");c(e19),this.onCloseCallbacks.forEach(t3=>t3({code:za,reason:e19.message,wasClean:false}));return}this.messageQueue.enqueue(e18.data),this.handlingInterval||(this.handlingInterval=setInterval(this.handleNextMessage.bind(this),0))}},l.onclose=e18=>{if(this.ws&&this.ws!==l)return;if(this.connectionPromise=void 0,!r){let t4=e18?.reason?`, ${e18.reason}`:"";c(new b(`WebSocket closed before open (code ${e18?.code??0}${t4})`));return}this.stopMessageHandling();let t3=e18?.reason?`, ${e18.reason}`:"",n2=e18?.code??0;!(typeof e18.wasClean!="boolean"||e18.wasClean)||n2!==1e3&&n2!==1001?this.failPendingRpc(new b(`WebSocket closed (code ${n2}${t3})`)):this.rpcListeners={},this.onCloseCallbacks.forEach(t4=>t4(e18))}})),this.connectionPromise}sendRequest(e17,t2){if(this.ws?.readyState!==this._WS.OPEN){if(e17==="unsubscribe")return;throw this._logger.error("Attempted sendRequest, but socket was not open"),new b("Socket not open")}let n=this.rpcId;this.rpcId++,this.sendRpcMessage(e17,t2,n)}addSubListener(e17,t2){(this.subListeners[e17]=this.subListeners[e17]||[]).push(t2)}stopMessageHandling(){for(this.handlingInterval&&(clearInterval(this.handlingInterval),this.handlingInterval=void 0);this.messageQueue.size>0;)this.messageQueue.dequeue();this.subListeners={}}failPendingRpc(e17){let t2=this.rpcListeners;this.rpcListeners={};for(let n of Object.keys(t2))try{t2[n].errorCallback(e17)}catch{}}sendRpcMessage(e17,t2,n){if(this.ws?.readyState!==this._WS.OPEN)throw new b("Socket not open");let r=JSON.stringify({jsonrpc:"2.0",method:e17,params:t2,id:n});try{this.ws.send(r)}catch(e18){this._logger.error("WebSocket send failed",{e:e18}),this.connectionPromise=void 0;try{this.ws.close()}catch{}this.ws=void 0,this.stopMessageHandling();let t3=e18 instanceof Error?e18:new b(String(e18),{cause:e18});throw this.failPendingRpc(t3),t3}}addRpcListener(e17,t2,n){this.rpcListeners[n]={callback:e17,errorCallback:t2}}removeRpcListener(e17){delete this.rpcListeners[e17]}removeListener(e17,t2){if(this.subListeners[e17]){if(this.subListeners[e17].length===1){delete this.subListeners[e17];return}this.subListeners[e17]=this.subListeners[e17].filter(e18=>e18!==t2)}}async ensureConnection(e17){this.ws?.readyState!==this._WS.OPEN&&await this.connect(e17)}handleNextMessage(){for(;this.messageQueue.size>0;){let e17=this.messageQueue.dequeue();try{let t2=j.parse(e17,void 0,{strict:true});if("result"in t2&&t2.id!=null)this.rpcListeners[t2.id]&&(this.rpcListeners[t2.id].callback(),this.removeRpcListener(t2.id));else if("error"in t2&&t2.id!=null)this.rpcListeners[t2.id]&&(this.rpcListeners[t2.id].errorCallback(new b(t2.error.message)),this.removeRpcListener(t2.id));else if("method"in t2&&!("id"in t2)){let e18=t2.params?.subId;if(!e18)continue;if(this.subListeners[e18]?.length>0){let n=t2;this.subListeners[e18].forEach(e19=>{try{let t3=e19(n.params?.payload);t3&&typeof t3.then=="function"&&Promise.resolve(t3).catch(e20=>{this._logger.error("Subscription handler threw",{e:e20})})}catch(e20){this._logger.error("Subscription handler threw",{e:e20})}})}}}catch(e18){this._logger.error("Error doing handleNextMessage",{e:e18})}}this.handlingInterval&&(clearInterval(this.handlingInterval),this.handlingInterval=void 0)}createSubscription(e17,t2,n){if(this.ws?.readyState!==this._WS.OPEN)throw this._logger.error("Attempted createSubscription, but socket was not open"),new b("Socket is not open");let r=(Math.random()+1).toString(36).substring(7),i=this.rpcId;this.addRpcListener(()=>{this.addSubListener(r,t2)},n,i);try{this.sendRequest("subscribe",{...e17,subId:r})}catch(e18){throw this.removeRpcListener(i),e18}return r}cancelSubscription(e17,t2,n){if(this.removeListener(e17,t2),this.ws?.readyState!==this._WS.OPEN){this._logger.info("Socket not open, removed listener locally {subId}",{subId:e17});return}let r=this.rpcId;this.rpcId++,this.addRpcListener(()=>{this._logger.info("Unsubscribed {subId}",{subId:e17})},n||(e18=>this._logger.error("Unsubscribe failed",{e:e18})),r);try{this.sendRpcMessage("unsubscribe",{subId:e17},r)}catch(e18){throw this.removeRpcListener(r),e18}}get activeSubscriptions(){return Object.keys(this.subListeners)}close(){let e17=new b("WebSocket closed");if(this.abandonConnect?.(e17),this.ws){try{this.ws.close()}catch{}this.ws=void 0}this.connectionPromise=void 0,this.failPendingRpc(e17),this.stopMessageHandling()}onClose(e17){this.onCloseCallbacks.push(e17)}};function Ua(e17){return Array.isArray(e17)?"array":typeof e17}var Wa=class{constructor(e17,t2){this._lastResponseMetadata=void 0,this._captureResponseMetadata=e18=>{this._lastResponseMetadata=e18},this._mintUrl=Hi(e17),this._request=t2?.customRequest??Fa,this._authProvider=t2?.authProvider,this._logger=t2?.logger??E,xa(this._logger)}get mintUrl(){return this._mintUrl}get lastResponseMetadata(){return this._lastResponseMetadata}async oidcAuth(e17){let t2=(await this.getLazyMintInfo()).nuts[21];if(!t2?.openid_discovery)throw new b("Mint: no NUT-21 openid_discovery");return new oa(t2.openid_discovery,{...e17,clientId:e17?.clientId??t2.client_id??"cashu-client"})}async getInfo(e17){let t2=await(e17??this._request)({endpoint:G(this._mintUrl,"/v1/info"),onResponseMeta:this._captureResponseMetadata,logger:this._logger});return Y.normalizeInfo(t2,this._logger)}async getLazyMintInfo(e17){if(this._mintInfo)return this._mintInfo;let t2=await this.getInfo(e17);return this._mintInfo=new Y(t2,this._logger),this._mintInfo}setMintInfo(e17){this._mintInfo=e17 instanceof Y?e17:new Y(e17,this._logger)}async swap(e17,t2){D(!Array.isArray(e17?.inputs),"swap: inputs must be an array of proofs",this._logger);let n=await this.requestWithAuth("POST","/v1/swap",{requestBody:{...e17,inputs:this.stripWalletFields(e17.inputs)}},t2);if(!H(n)||!Array.isArray(n?.signatures))throw this._logger.error("Invalid response from mint...",{data:n,op:"swap"}),new b("Invalid response from mint");return this.assertSignatureCount(n.signatures,e17.outputs,"swap"),n.signatures=this.normalizeSignatureAmounts(n.signatures),n}async createMintQuote(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint quote method: ${e17}`,this._logger);let r=await this.requestWithAuth("POST",`/v1/mint/quote/${e17}`,{requestBody:t2},n?.customRequest);return this.normalizeMintQuoteResponse(e17,r,n?.normalize)}async createMintQuoteBolt11(e17,t2){return this.createMintQuote("bolt11",{...e17,amount:A.from(e17.amount).toBigInt()},{customRequest:t2})}async createMintQuoteBolt12(e17,t2){let n={...e17};return e17.amount!==void 0&&(n.amount=A.from(e17.amount).toBigInt()),this.createMintQuote("bolt12",n,{customRequest:t2})}async createMintQuoteOnchain(e17,t2){return this.createMintQuote("onchain",e17,{customRequest:t2})}async checkMintQuote(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint quote method: ${e17}`,this._logger);let r=await this.requestWithAuth("GET",`/v1/mint/quote/${e17}/${t2}`,{},n?.customRequest),i=this.normalizeMintQuoteResponse(e17,r,n?.normalize);if(i.quote!==t2)throw this._logger.error("Invalid response from mint...",{op:`checkMintQuote.${e17}`}),new b("Mint quote response is for a different quote");return i}async checkMintQuoteBolt11(e17,t2){return this.checkMintQuote("bolt11",e17,{customRequest:t2})}async checkMintQuoteBolt12(e17,t2){return this.checkMintQuote("bolt12",e17,{customRequest:t2})}async checkMintQuoteOnchain(e17,t2){return this.checkMintQuote("onchain",e17,{customRequest:t2})}async checkMintQuoteBatch(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint quote method: ${e17}`,this._logger),D(t2.length===0,"checkMintQuoteBatch: no quote ids provided",this._logger),D(new Set(t2).size!==t2.length,"checkMintQuoteBatch: duplicate quote ids provided",this._logger);let r=await this.requestWithAuth("POST",`/v1/mint/quote/${e17}/check`,{requestBody:{quotes:t2}},n?.customRequest);if(!Array.isArray(r)||r.length!==t2.length)throw this._logger.error("Invalid response from mint...",{expectedCount:t2.length,actualCount:Array.isArray(r)?r.length:void 0,op:`checkMintQuoteBatch.${e17}`}),new b("Invalid response from mint");return r.map((r2,i)=>{if(r2.quote!==t2[i])throw this._logger.error("Invalid response from mint...",{index:i,op:`checkMintQuoteBatch.${e17}`}),new b("Invalid response from mint");return this.normalizeMintQuoteResponse(e17,r2,n?.normalize)})}async checkMintQuoteBatchBolt11(e17,t2){return this.checkMintQuoteBatch("bolt11",e17,{customRequest:t2})}async checkMintQuoteBatchBolt12(e17,t2){return this.checkMintQuoteBatch("bolt12",e17,{customRequest:t2})}async mintBolt11(e17,t2){return this.mint("bolt11",e17,{customRequest:t2})}async mintBolt12(e17,t2){return this.mint("bolt12",e17,{customRequest:t2})}async mintOnchain(e17,t2){return this.mint("onchain",e17,{customRequest:t2})}async mint(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint method: ${e17}`,this._logger);let r=await this.requestWithAuth("POST",`/v1/mint/${e17}`,{requestBody:t2},n?.customRequest);if(!H(r)||!Array.isArray(r?.signatures))throw this._logger.error("Invalid response from mint...",{data:r,op:`mint.${e17}`}),new b("Invalid response from mint");return this.assertSignatureCount(r.signatures,t2.outputs,`mint.${e17}`),r.signatures=this.normalizeSignatureAmounts(r.signatures),n?.normalize?n.normalize(r):r}async mintBatchBolt11(e17,t2){return this.mintBatch("bolt11",e17,{customRequest:t2})}async mintBatchBolt12(e17,t2){return this.mintBatch("bolt12",e17,{customRequest:t2})}async mintBatch(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint method: ${e17}`,this._logger);let r={...t2,quote_amounts:t2.quote_amounts.map(e18=>A.from(e18).toBigInt())},i=await this.requestWithAuth("POST",`/v1/mint/${e17}/batch`,{requestBody:r},n?.customRequest);if(!H(i)||!Array.isArray(i?.signatures))throw this._logger.error("Invalid response from mint...",{data:i,op:`mintBatch.${e17}`}),new b("Invalid response from mint");return this.assertSignatureCount(i.signatures,t2.outputs,`mintBatch.${e17}`),i.signatures=this.normalizeSignatureAmounts(i.signatures),n?.normalize?n.normalize(i):i}async createMeltQuote(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid melt quote method: ${e17}`,this._logger);let r=await this.requestWithAuth("POST",`/v1/melt/quote/${e17}`,{requestBody:t2},n?.customRequest);return this.normalizeMeltQuoteResponse(e17,r,n?.normalize)}async createMeltQuoteBolt11(e17,t2){let n=await this.createMeltQuote("bolt11",this.normalizeMeltQuoteRequestOptions(e17),{customRequest:t2});return D(n.request!==""&&n.request.toLowerCase()!==e17.request.toLowerCase(),"Melt quote is for a different payment request",this._logger),n}async createMeltQuoteBolt12(e17,t2){return this.createMeltQuote("bolt12",this.normalizeMeltQuoteRequestOptions(e17),{customRequest:t2})}async createMeltQuoteOnchain(e17,t2){return this.createMeltQuote("onchain",{...e17,amount:A.from(e17.amount).toBigInt()},{customRequest:t2})}async checkMeltQuote(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid melt quote method: ${e17}`,this._logger);let r=await this.requestWithAuth("GET",`/v1/melt/quote/${e17}/${t2}`,{},n?.customRequest),i=this.normalizeMeltQuoteResponse(e17,r,n?.normalize);if(i.quote!==t2)throw this._logger.error("Invalid response from mint...",{data:i,op:`checkMeltQuote.${e17}`}),new b("Melt quote response is for a different quote");return i}async checkMeltQuoteBolt11(e17,t2){return this.checkMeltQuote("bolt11",e17,{customRequest:t2})}async checkMeltQuoteBolt12(e17,t2){return this.checkMeltQuote("bolt12",e17,{customRequest:t2})}async checkMeltQuoteOnchain(e17,t2){return this.checkMeltQuote("onchain",e17,{customRequest:t2})}async melt(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid melt method: ${e17}`,this._logger),D(!Array.isArray(t2?.inputs),"melt: inputs must be an array of proofs",this._logger);let r=await this.requestWithAuth("POST",`/v1/melt/${e17}`,{requestBody:{...t2,inputs:this.stripWalletFields(t2.inputs)}},n?.customRequest),i=this.normalizeMeltQuoteResponse(e17,r,n?.normalize,true);return i.quote!==t2.quote&&(this._logger.warn("Melt response reports a different quote id",{op:`melt.${e17}`,expected:t2.quote,received:i.quote}),i.quote=t2.quote),i}async meltBolt11(e17,t2){return this.melt("bolt11",e17,t2)}async meltBolt12(e17,t2){return this.melt("bolt12",e17,t2)}async meltOnchain(e17,t2){return this.melt("onchain",e17,t2)}async check(e17,t2){let n=await this.requestWithAuth("POST","/v1/checkstate",{requestBody:e17},t2);if(!H(n)||!Array.isArray(n?.states)||n.states.length>e17.Ys.length)throw this._logger.error("Invalid response from mint...",{data:n,op:"check"}),new b("Invalid response from mint");this.assertRecordEntries(n.states,"check");for(let e18 of n.states)W(e18,"witness");return n}async getKeys(e17,t2,n){let r=t2||this._mintUrl;e17&&(e17=e17.replace(/\//g,"_").replace(/\+/g,"-"));let i=await(n??this._request)({endpoint:e17?G(r,"/v1/keys",e17):G(r,"/v1/keys"),onResponseMeta:this._captureResponseMetadata,logger:this._logger});if(!H(i)||!Array.isArray(i.keysets))throw this._logger.error("Invalid response from mint...",{data:i,op:"getKeys"}),new b("Invalid response from mint");return this.assertKeysetList(i.keysets,"getKeys"),{...i,keysets:i.keysets.map(e18=>ia(e18))}}async getKeySets(e17){let t2=await(e17??this._request)({endpoint:G(this._mintUrl,"/v1/keysets"),onResponseMeta:this._captureResponseMetadata,logger:this._logger});if(!H(t2)||!Array.isArray(t2.keysets))throw this._logger.error("Invalid response from mint...",{data:t2,op:"getKeySets"}),new b("Invalid response from mint");return this.assertKeysetList(t2.keysets,"getKeySets"),{...t2,keysets:t2.keysets.map(e18=>ra(e18))}}async restore(e17,t2){let n=await(t2??this._request)({endpoint:G(this._mintUrl,"/v1/restore"),method:"POST",requestBody:e17,onResponseMeta:this._captureResponseMetadata,logger:this._logger});if(!H(n)||!Array.isArray(n?.outputs)||!Array.isArray(n?.signatures)||n.outputs.length!==n.signatures.length||n.outputs.length>e17.outputs.length)throw this._logger.error("Invalid response from mint...",{data:n,op:"restore"}),new b("Invalid response from mint");return n.outputs=this.normalizeMessageAmounts(n.outputs),n.signatures=this.normalizeSignatureAmounts(n.signatures),n}async connectWebSocket(){try{let e17=new URL(this._mintUrl),t2="v1/ws";e17.pathname.endsWith("/")?e17.pathname+=t2:e17.pathname+="/"+t2,e17.protocol=e17.protocol==="https:"?"wss:":"ws:";let n=e17.toString();this.ws||(this.ws=new Ha(n,this._logger)),await this.ws.ensureConnection()}catch(e17){this._logger.error("Failed to connect to WebSocket...",{e:e17});try{this.ws?.close()}catch{}throw this.ws=void 0,new b("Failed to connect to WebSocket...",{cause:e17})}}disconnectWebSocket(){this.ws&&this.ws.close()}get webSocketConnection(){return this.ws}async handleClearAuth(e17,t2,n){if(this._authProvider&&(n??await this.getLazyMintInfo()).requiresClearAuthToken(e17,t2))return this._authProvider.ensureCAT?this._authProvider.ensureCAT():this._authProvider.getCAT()}async handleBlindAuth(e17,t2,n){if(this._authProvider&&(n??await this.getLazyMintInfo()).requiresBlindAuthToken(e17,t2))return await this._authProvider.getBlindAuthToken({method:e17,path:t2})}async requestWithAuth(e17,t2,n={},r){let i=r??this._request,a=this._mintInfo;this._authProvider&&(a=await this.getLazyMintInfo(r));let o=await this.handleBlindAuth(e17,t2,a),s=await this.handleClearAuth(e17,t2,a),c={...n.headers??{},...o?{"Blind-auth":o}:{},...s?{"Clear-auth":s}:{}},l=a?.isSupported(19);return i({...n,endpoint:G(this._mintUrl,t2),method:e17,headers:c,...o||s||n.requestBody?{redirect:"error"}:{},...l?.supported&&l.params?l.params:{},onResponseMeta:this._captureResponseMetadata,logger:n.logger??this._logger})}normalizeMeltQuoteRequestOptions(e17){if(!e17.options)return{...e17};let t2={...e17.options};return e17.options.amountless&&(t2.amountless={amount_msat:A.from(e17.options.amountless.amount_msat).toBigInt()}),"mpp"in e17.options&&e17.options.mpp&&(t2.mpp={amount:A.from(e17.options.mpp.amount).toBigInt()}),{...e17,options:t2}}isValidMethodString(e17){return!!(typeof e17=="string"&&/^[a-z0-9_-]+$/.test(e17))}normalizeSignatureAmounts(e17){return this.assertRecordEntries(e17,"signatures"),e17.map(e18=>({...e18,amount:A.from(e18.amount)}))}normalizeMessageAmounts(e17){return this.assertRecordEntries(e17,"outputs"),e17.map(e18=>({...e18,amount:A.from(e18.amount)}))}stripWalletFields(e17){return e17.map(e18=>{let{dleq:t2,p2pk_e:n,...r}=e18;return r})}assertRecordEntries(e17,t2){if(!e17.every(e18=>U(e18)))throw this._logger.error("Invalid response from mint...",{entries:e17.length,op:t2}),new b("Invalid response from mint")}assertSignatureCount(e17,t2,n){if(!(e17.length<=t2.length))throw this._logger.error("Invalid response from mint...",{signatures:e17.length,outputs:t2.length,op:n}),new b(`Invalid response from mint: ${e17.length} signatures, expected ${t2.length}. The operation may already have been applied; if the wallet is seeded, try restoring (NUT-09) to recover.`)}assertKeysetList(e17,t2){if(e17.length>1e4)throw this._logger.error("Invalid response from mint...",{keysets:e17.length,op:t2}),new b("Invalid response from mint");this.assertRecordEntries(e17,t2)}normalizeMintQuoteResponse(e17,t2,n){let r=`${e17} mint quote`;if(!U(t2))throw this._logger.error("Invalid response from mint...",{type:Ua(t2),op:r}),new b("Invalid response from mint");let i={...t2};return this.normalizeMintBaseFields(i),e17==="bolt11"?this.normalizeMintQuoteBolt11Fields(i):e17==="bolt12"?this.normalizeMintQuoteBolt12Fields(i):e17==="onchain"&&this.normalizeMintQuoteOnchainFields(i),n?n(i):i}normalizeMintBaseFields(e17){e17.amount_paid!=null&&e17.amount_issued!=null&&(e17.amount_paid=A.from(e17.amount_paid),e17.amount_issued=A.from(e17.amount_issued)),e17.updated_at=J(e17.updated_at,"mintQuote.updated_at",null)}deriveMintQuoteState(e17,t2){return e17.isZero()&&t2.isZero()?sa.UNPAID:e17.greaterThan(t2)?sa.PAID:sa.ISSUED}normalizeMintQuoteBolt11Fields(e17){e17.amount=A.from(e17.amount),e17.expiry=J(e17.expiry,"mintQuoteBolt11.expiry",null),(typeof e17.state!="string"||!Object.values(sa).includes(e17.state))&&e17.amount_paid instanceof A&&e17.amount_issued instanceof A&&(e17.state=this.deriveMintQuoteState(e17.amount_paid,e17.amount_issued))}normalizeMintQuoteBolt12Fields(e17){W(e17,"amount"),e17.amount=e17.amount===null?null:A.from(e17.amount),e17.expiry=J(e17.expiry,"mintQuoteBolt12.expiry",null),e17.amount_paid=A.from(e17.amount_paid),e17.amount_issued=A.from(e17.amount_issued)}normalizeMintQuoteOnchainFields(e17){e17.expiry=J(e17.expiry,"mintQuoteOnchain.expiry",null),e17.amount_paid=A.from(e17.amount_paid),e17.amount_issued=A.from(e17.amount_issued)}normalizeMeltQuoteResponse(e17,t2,n,r=false){let i=`${e17} melt quote`;if(!U(t2))throw this._logger.error("Invalid response from mint...",{type:Ua(t2),op:i}),new b("Invalid response from mint");let a={...t2};return r&&((a.request==null||a.request==="")&&delete a.request,a.fee_reserve??delete a.fee_reserve),this.normalizeMeltBaseFields(a,i),e17==="bolt11"||e17==="bolt12"?this.normalizeMeltBoltFields(a,i,r):e17==="onchain"&&this.normalizeMeltOnchainFields(a,r),n?n(a):a}normalizeMeltBaseFields(e17,t2){if(e17.amount=A.from(e17.amount),e17.expiry=J(e17.expiry,"meltQuote.expiry",void 0),e17.change){if(!Array.isArray(e17.change)||e17.change.length>1024)throw this._logger.error("Invalid response from mint...",{type:Ua(e17.change),op:t2}),new b("Invalid response from mint");e17.change=this.normalizeSignatureAmounts(e17.change)}if(!H(e17)||typeof e17.quote!="string"||!(e17.amount instanceof A)||typeof e17.unit!="string"||typeof e17.state!="string"||typeof e17.expiry!="number"||!Object.values(ca).includes(e17.state))throw this._logger.error("Invalid response from mint...",{op:t2}),new b("Invalid response from mint")}normalizeMeltBoltFields(e17,t2,n){let r=t3=>n&&e17[t3]===void 0;if(!r("fee_reserve")&&e17.fee_reserve!=null&&(e17.fee_reserve=A.from(e17.fee_reserve)),typeof e17.request!="string"&&!r("request")||!(e17.fee_reserve instanceof A)&&!r("fee_reserve"))throw this._logger.error("Invalid response from mint...",{op:t2}),new b("Invalid response from mint");W(e17,"payment_preimage")}normalizeMeltOnchainFields(e17,t2){if(t2&&e17.fee_options===void 0){W(e17,"selected_fee_index","outpoint");return}if(!Array.isArray(e17.fee_options)||e17.fee_options.length===0||e17.fee_options.length>1024||(e17.fee_options=e17.fee_options.map(e18=>{let t3=e18;if(!Number.isSafeInteger(t3.fee_index))throw this._logger.error("Invalid response from mint...",{op:"onchain melt quote"}),new b("Invalid response from mint");return{...t3,fee_index:t3.fee_index,fee_reserve:A.from(t3.fee_reserve),estimated_blocks:t3.estimated_blocks}}),W(e17,"selected_fee_index","outpoint"),typeof e17.request!="string"||e17.selected_fee_index!==null&&!Number.isSafeInteger(e17.selected_fee_index)||e17.outpoint!==null&&typeof e17.outpoint!="string"))throw this._logger.error("Invalid response from mint...",{op:"onchain melt quote"}),new b("Invalid response from mint")}};var Ga=class e13{constructor(e17,t2,n,r,i){this._keys={},this._id=e17,this._unit=t2,this._active=n,this._input_fee_ppk=r,this._final_expiry=i}get id(){return this._id}get unit(){return this._unit}get isActive(){return this._active}get fee(){return this._input_fee_ppk??0}get expiry(){return this._final_expiry}get hasKeys(){return Object.keys(this._keys).length>0}get hasHexId(){return V(this._id)}get version(){return this.hasHexId?hexToBytes2(this._id)[0]:-1}get keys(){return this._keys}set keys(e17){this._keys=e17}toMintKeyset(){return{id:this._id,unit:this._unit,active:this._active,input_fee_ppk:this._input_fee_ppk,final_expiry:this._final_expiry}}toMintKeys(){return this.hasKeys?{id:this._id,unit:this._unit,active:this._active,input_fee_ppk:this._input_fee_ppk,final_expiry:this._final_expiry,keys:this._keys}:null}verify(){return this.hasKeys?e13.verifyKeysetId(this.toMintKeys()):false}static verifyKeysetId(e17){try{let t2=e17.keys?Object.keys(e17.keys).length:0;if(t2===0||t2>256||new Set(Object.values(e17.keys).map(e18=>e18.toLowerCase())).size!==t2)return false;let n=et(e17.id)&&!V(e17.id),i=V(e17.id)?hexToBytes2(e17.id)[0]:0;return zi(e17.keys,{input_fee_ppk:e17.input_fee_ppk,expiry:e17.final_expiry,unit:e17.unit,versionByte:i,isDeprecatedBase64:n})===e17.id}catch{return false}}static fromMintApi(t2,n){let r=ra(t2),i=n?ia(n):void 0,a=new e13(r.id,r.unit,r.active,r.input_fee_ppk,r.final_expiry);if(i){if(i.id!==r.id)throw new b(`Mismatched keyset ids: meta=${r.id}, keys=${i.id}`);if(i.unit!==r.unit)throw new b(`Mismatched keyset units: meta=${r.unit}, keys=${i.unit}`);if(i.final_expiry!==void 0&&r.final_expiry!==void 0&&i.final_expiry!==r.final_expiry)throw new b(`Mismatched keyset expiry for id=${r.id}`);a.keys=i.keys}return a}};var Ka=class e14{assertInitialized(){if(Object.keys(this.keysets).length===0)throw new b("KeyChain not initialized")}constructor(e17,t2,n=E){this.keysets=Object.create(null),this.pendingKeyFetches=new Map,this.generation=0,this.refreshSeq=0,this.mint=typeof e17=="string"?new Wa(e17):e17,this.unit=t2,this._logger=n}static fromCache(t2,n,r,i){let a=new e14(t2,n,i);return a.loadFromCache(r),a}static mintToCacheDTO(e17,t2,n){let r=new Map(n.map(e18=>[e18.id,e18]));return{keysets:t2.map(e18=>{let t3=r.get(e18.id),n2={...e18};return t3&&(n2.keys={...t3.keys}),n2}),mintUrl:e17,savedAt:Date.now()}}static cacheToMintDTO(e17){return{keysets:e17.keysets.map(e18=>({id:e18.id,unit:e18.unit,active:e18.active,input_fee_ppk:e18.input_fee_ppk,final_expiry:e18.final_expiry})),keys:e17.keysets.filter(e18=>!!e18.keys).map(e18=>({id:e18.id,unit:e18.unit,active:e18.active,input_fee_ppk:e18.input_fee_ppk,final_expiry:e18.final_expiry,keys:{...e18.keys}}))}}async init(e17){if(Object.keys(this.keysets).length>0&&!e17)return;let t2=++this.refreshSeq,[n,r]=await Promise.all([this.mint.getKeySets(),this.mint.getKeys()]);if(t2!==this.refreshSeq){this._logger.debug("Discarding keychain refresh superseded by a later one",{seq:t2});return}this.buildKeychain(n.keysets,r.keysets),this.savedAt=Date.now()}loadFromCache(t2){let n;try{n=Hi(String(t2.mintUrl))}catch{n=void 0}n!==this.mint.mintUrl&&this._logger.warn(`KeyChain cache is for a different mint: ${n??"unknown"} (expected ${this.mint.mintUrl}). This will become an error in cashu-ts v5.`,{cacheMintUrl:t2.mintUrl,mintUrl:this.mint.mintUrl});let{keysets:r,keys:i}=e14.cacheToMintDTO(t2);this.buildKeychain(r,i),this.savedAt=t2.savedAt}buildKeychain(e17,t2){let n=this.keysets,r=Object.create(null),i=new Map(t2.map(e18=>[e18.id,e18]));for(let t3 of e17){let e18=i.get(t3.id),a=e18?Ga.fromMintApi(t3,e18):Ga.fromMintApi(t3);a.verify()||(a.hasKeys&&this._logger.warn("Discarding keys that do not derive their keyset id",{id:a.id}),a.keys={});let o=n[t3.id];!a.hasKeys&&o?.hasKeys&&o.unit===a.unit&&(a.keys={...o.keys},a.verify()||(this._logger.warn("Dropping carried keys: fresh metadata no longer derives the keyset id",{id:a.id}),a.keys={})),r[a.id]=a}this.keysets=r,this.generation++}getKeyset(e17){let t2=e17?this.keysets[e17]:this.getCheapestKeyset();if(!t2)throw new b(`Keyset '${e17}' not found`);return t2}getCheapestKeyset(){if(Object.keys(this.keysets).length===0)throw new b("KeyChain not initialized");let e17=Object.values(this.keysets).filter(e18=>e18.unit===this.unit&&e18.isActive&&e18.hasHexId&&e18.hasKeys);if(e17.length===0)throw new b(`No active keyset found for unit: ${this.unit}`);let t2=2**53-1;return e17.sort((e18,n)=>n.version-e18.version||e18.fee-n.fee||(n.expiry??t2)-(e18.expiry??t2))[0]}async ensureKeysetKeys(e17){let t2=this.keysets[e17];if(!t2)throw new b(`Keyset '${e17}' not found`);if(t2.hasKeys)return t2;let n=this.pendingKeyFetches.get(e17);if(n)return await n;let r=(async()=>{let n2=this.generation,r2=(await this.mint.getKeys(e17)).keysets.find(t3=>t3.id===e17);if(!r2||!r2.keys||Object.keys(r2.keys).length===0)throw new b(`Mint returned no keys for keyset '${e17}'`);let i=t2.toMintKeyset(),a=Ga.fromMintApi(i,r2);if(!a.verify())throw new b(`Keyset verification failed for ID ${e17}`);if(this.generation!==n2){this._logger.debug("Keychain refreshed during key fetch; returning the live keyset",{id:e17});let t3=this.keysets[e17];if(!t3)throw new b(`Keyset '${e17}' not found`);return t3}return this.keysets[e17]=a,a})();this.pendingKeyFetches.set(e17,r);try{return await r}finally{this.pendingKeyFetches.delete(e17)}}getKeysets(){this.assertInitialized();let e17=Object.values(this.keysets).filter(e18=>e18.unit===this.unit);if(e17.length===0)throw new b(`No keysets found for unit: ${this.unit}`);return e17}isUnitKeyset(e17){if(!e17)return false;let t2=this.keysets[e17];return t2!==void 0&&t2.unit===this.unit}hasKeyset(e17){return!!e17&&this.keysets[e17]!==void 0}getAllKeys(){return this.assertInitialized(),Object.values(this.keysets).map(e17=>e17.toMintKeys()).filter(e17=>e17!==null)}getAllKeysetIds(){return this.assertInitialized(),Object.keys(this.keysets)}get cache(){let t2=Object.values(this.keysets),n=t2.map(e17=>e17.toMintKeyset()),r=t2.map(e17=>e17.toMintKeys()).filter(e17=>e17!==null),i=e14.mintToCacheDTO(this.mint.mintUrl,n,r);return i.savedAt=this.savedAt,i}};var qa=class{constructor(e17,t2,n){this.amountValue=A.from(e17),this.B_=t2,this.id=n}get amount(){return this.amountValue}getSerializedBlindedMessage(){return{amount:this.amountValue,B_:this.B_.toHex(true),id:this.id}}};var Ja=new Set(["locktime","pubkeys","n_sigs","refund","n_sigs_refund","sigflag"]);function Ya(e17){if(!e17||typeof e17!="string")throw new b("tag key must be a non empty string");if(Ja.has(e17))throw new b(`additionalTags must not use reserved key "${e17}"`)}var Z=class e15{constructor(e17,t2,n,r){if(typeof t2!="bigint"||t2<=0n)throw new b("OutputData: blindingFactor must be a positive bigint");if(!(n instanceof Uint8Array)||n.length===0)throw new b("OutputData: secret must be a non-empty Uint8Array");if(e17==null)throw new b("OutputData: blindedMessage is required");this.secret=n,this.blindingFactor=t2,this.blindedMessage=e17,this.ephemeralE=r}toProof(e17,n){if(e17==null)throw new b("Mint response is missing a signature for one of the outputs. Inputs may already be spent; if the wallet is seeded, try restoring (NUT-09) to recover.");if(!this.blindedMessage.amount.isZero()&&e17.id!==this.blindedMessage.id)throw new b(`Mint signature keyset id ${e17.id} does not match output ${this.blindedMessage.id}`);let i;e17.dleq&&(i={s:hexToBytes2(e17.dleq.s),e:hexToBytes2(e17.dleq.e),r:this.blindingFactor});let a=e17.amount.toString(),o=P(n.keys[a]);if(i){let t2=P(this.blindedMessage.B_),n2=P(e17.C_);if(!tr(i,t2,n2,o))throw new b("DLEQ verification failed on mint response")}let s=Ut({id:e17.id,C_:P(e17.C_)},this.blindingFactor,this.secret,o),c={id:e17.id,amount:e17.amount,C:s.C.toHex(true),secret:xe(s.secret),...i&&{dleq:{s:bytesToHex2(i.s),e:bytesToHex2(i.e),r:Ti(this.blindingFactor)}}};return this.ephemeralE&&(c.p2pk_e=this.ephemeralE),c}static createP2PKData(e17,t2,n,r){let i=B(t2,n.keys,r),a=e17.blindKeys&&e17.sigFlag==="SIG_ALL"?Rt():void 0;return i.map(t3=>this.createSingleP2PKData(e17,t3,n.id,a))}static createSingleP2PKData(n,r,a,o){let s=A.from(r),c=On(n),l=Array.isArray(c.pubkey)?c.pubkey:[c.pubkey],u=c.refundKeys??[],d=c.requiredSignatures??1,f=c.requiredRefundSignatures??1,p=c.hashlock,m=typeof p=="string"&&p.length>0,h=m?p:l[0],g=m?l:l.slice(1),_=u,v;if(n.blindKeys){let{blinded:e17,Ehex:t2}=vn([...l,...u],o,!m);m?g=e17.slice(0,l.length):(h=e17[0],g=e17.slice(1,l.length)),_=e17.slice(l.length),v=t2}let y=[],x2=c.locktime??NaN;if(Number.isSafeInteger(x2)&&x2>=0&&y.push(["locktime",String(x2)]),g.length>0&&(y.push(["pubkeys",...g]),d>1&&y.push(["n_sigs",String(d)])),_.length>0&&(y.push(["refund",..._]),f>1&&y.push(["n_sigs_refund",String(f)])),c.sigFlag=="SIG_ALL"&&y.push(["sigflag","SIG_ALL"]),c.additionalTags?.length){let e17=c.additionalTags.map(([e18,...t2])=>(Ya(e18),[e18,...t2.map(String)]));y.push(...e17)}let S2=[m?"HTLC":"P2PK",{nonce:bytesToHex2(randomBytes3(32)),data:h,tags:y}],C=JSON.stringify(S2),ee=[...C].length;if(ee>1024)throw new b(`Secret too long (${ee} characters), maximum is ${ce}`);let w=new TextEncoder().encode(C),{r:T2,B_:te2}=Vt(w);return new e15(new qa(s,te2,a).getSerializedBlindedMessage(),T2,w,v)}static createRandomData(e17,t2,n){return B(e17,t2.keys,n).map(e18=>this.createSingleRandomData(e18,t2.id))}static createSingleRandomData(n,r){let a=A.from(n),o=bytesToHex2(randomBytes3(32)),s=new TextEncoder().encode(o),{r:c,B_:l}=Vt(s);return new e15(new qa(a,l,r).getSerializedBlindedMessage(),c,s)}static createDeterministicData(e17,t2,n,r,i){let a=B(e17,r.keys,i),o=dr(t2,r.id);return a.map((e18,t3)=>Xa(e18,r.id,o(n+t3)))}static createSingleDeterministicData(e17,t2,n,r){return Xa(e17,r,ur(t2,r,n))}static sumOutputAmounts(e17){return A.sum(e17.map(e18=>e18.blindedMessage.amount))}static serialize(e17){return{blindedMessage:{amount:e17.blindedMessage.amount.toString(),B_:e17.blindedMessage.B_,id:e17.blindedMessage.id},blindingFactor:e17.blindingFactor.toString(),secret:bytesToHex2(e17.secret),...e17.ephemeralE&&{ephemeralE:e17.ephemeralE}}}static deserialize(t2){try{if(!/^(0|[1-9]\d*)$/.test(t2.blindingFactor))throw new b("blindingFactor must be a canonical decimal integer");let n=hexToBytes2(t2.secret);xe(n);let i=BigInt(t2.blindingFactor),{B_:a}=Vt(n,i);if(a.toHex(true)!==t2.blindedMessage.B_.toLowerCase())throw new b("stored output does not match its secret. Inputs may already be spent; if the wallet is seeded, try restoring (NUT-09) to recover.");return new e15({amount:A.from(t2.blindedMessage.amount),B_:t2.blindedMessage.B_,id:t2.blindedMessage.id},i,n,t2.ephemeralE?P(t2.ephemeralE).toHex(true):void 0)}catch(e17){throw new b(`Invalid SerializedOutputData: ${e17 instanceof Error?e17.message:String(e17)}`,{cause:e17})}}};function Xa(e17,n,r){let i=A.from(e17),a=bytesToHex2(r.secret),o=new TextEncoder().encode(a),{r:s,B_:c}=Vt(o,bytesToNumberBE(r.blindingFactor));return new Z(new qa(i,c,n).getSerializedBlindedMessage(),s,o)}var Mo;var No=class e16{constructor(e17,t2){this.tokenGeneration=0,this.sessionGeneration=0,this.tokens={},this.pool=[],this.desiredPoolSize=100,this.maxPerMint=100,this.mintUrl=e17,this.req=t2?.request??Fa,this.logger=t2?.logger??E;let n=Math.max(1,t2?.desiredPoolSize??this.desiredPoolSize),r=Math.max(1,t2?.maxPerMint??this.maxPerMint);this.desiredPoolSize=Math.min(n,100),this.maxPerMint=Math.min(r,100),this.desiredPoolSize!==n&&this.logger.warn("AuthManager: desiredPoolSize exceeds internal cap and was clamped",{configured:n,clampedTo:this.desiredPoolSize}),this.maxPerMint!==r&&this.logger.warn("AuthManager: maxPerMint exceeds internal cap and was clamped",{configured:r,clampedTo:this.maxPerMint})}attachOIDC(e17){return this.oidc&&this.oidcListener&&this.oidc.removeTokenListener(this.oidcListener),this.oidc&&this.oidc!==e17&&(this.tokens={}),this.tokenGeneration++,this.sessionGeneration++,this.oidc=e17,this.bindOIDC(),this}bindOIDC(){let e17=this.oidc;if(!e17)return;this.oidcListener&&e17.removeTokenListener(this.oidcListener);let t2=(n,r)=>{if(this.oidc!==e17||r==="refresh"&&this.oidcListener!==t2){this.logger.warn("AuthManager: ignoring tokens from an earlier session");return}this.updateFromOIDC(n,r)};this.oidcListener=t2,e17.addTokenListener(t2)}get poolSize(){return this.pool.length}get poolTarget(){return this.desiredPoolSize}get activeAuthKeysetId(){try{return this.keychain?.getCheapestKeyset().id}catch{return}}get hasCAT(){return!!this.tokens.accessToken}getCAT(){return this.tokens.accessToken}setCAT(e17){this.tokenGeneration++,this.sessionGeneration++,this.tokens={accessToken:e17},this.bindOIDC()}async ensureCAT(e17){if(this.validForAtLeast(e17)||!this.oidc||!this.tokens.refreshToken)return this.tokens.accessToken;if(this.inflightRefresh?.session!==this.sessionGeneration){let e18=this.tokenGeneration,t3=this.sessionGeneration,n=(async()=>{try{let t4=await this.oidc.refresh(this.tokens.refreshToken);this.tokenGeneration===e18&&this.updateFromOIDC(t4,"refresh")}catch(e19){this.logger.warn("AuthManager: CAT refresh failed",{err:e19})}})();this.inflightRefresh={session:t3,promise:n}}let t2=this.inflightRefresh;try{await t2.promise}finally{this.inflightRefresh===t2&&(this.inflightRefresh=void 0)}return this.validForAtLeast(0)?this.tokens.accessToken:void 0}validForAtLeast(t2=e16.MIN_VALID_SECS){let{accessToken:n,expiresAt:r}=this.tokens;return n?r?Date.now()+t2*1e3<r:true:false}updateFromOIDC(e17,t2){if(!e17.access_token)return;this.tokenGeneration++,t2==="signin"&&this.sessionGeneration++;let n=Date.now();if(this.tokens.accessToken=e17.access_token,this.tokens.refreshToken=e17.refresh_token||(t2==="refresh"?this.tokens.refreshToken:void 0),typeof e17.expires_in=="number"&&e17.expires_in>0)this.tokens.expiresAt=n+e17.expires_in*1e3;else{let t3=this.parseJwtExpSec(e17.access_token);this.tokens.expiresAt=t3?t3*1e3:void 0}this.bindOIDC(),this.logger.debug("AuthManager: OIDC tokens updated",{expiresAt:this.tokens.expiresAt})}async ensure(e17){if(await this.init(),this.pool.length>=e17)return;let t2=Math.max(this.desiredPoolSize,e17),n=this.getBatMaxMint(),r=Math.min(t2-this.pool.length,n);r<=0||await this.topUp(r)}async getBlindAuthToken({method:e17,path:t2}){return this.info&&!this.info.requiresBlindAuthToken(e17,t2)&&this.logger.warn("Endpoint is not marked as protected by NUT-22; still issuing BAT",{method:e17,path:t2}),this.withLock(async()=>{if(await this.ensure(1),this.pool.length===0)throw new b("AuthManager: no BATs available and minting failed");let n=this.pool.pop();return this.logger.debug("AuthManager: BAT requested",{method:e17,path:t2,remaining:this.pool.length}),Po(n)})}importPool(e17,t2="replace"){t2==="replace"&&(this.pool=[]);let n=new Map(this.pool.map(e18=>[e18.secret,e18]));for(let t3 of e17)!t3||!t3.secret||!t3.C||!t3.id||n.has(t3.secret)||(this.pool.push(t3),n.set(t3.secret,t3))}exportPool(){return this.pool.map(e17=>({...e17,dleq:e17.dleq?{...e17.dleq}:void 0}))}parseJwtExpSec(e17){if(!e17)return;let t2=e17.split(".");if(t2.length===3)try{let e18=new TextDecoder("utf-8").decode(Xe(t2[1])),n=JSON.parse(e18),r=typeof n.exp=="number"?n.exp:Number(n.exp);if(Number.isFinite(r)&&r>0)return r}catch{this.logger.warn("JWT access token was malformed.")}}async withLock(e17){let t2=this.lockChain??Promise.resolve(),n,r=new Promise(e18=>{n=e18}),i=t2.then(()=>r);this.lockChain=i;try{return await t2,await e17()}finally{n(),this.lockChain===i&&(this.lockChain=void 0)}}async init(){if(!this.info){let e17=await this.req({endpoint:G(this.mintUrl,"/v1/info"),method:"GET",logger:this.logger});this.info=new Y(e17,this.logger)}if(!this.keychain){let[e17,t2]=await Promise.all([this.req({endpoint:G(this.mintUrl,"/v1/auth/blind/keysets"),method:"GET",logger:this.logger}),this.req({endpoint:G(this.mintUrl,"/v1/auth/blind/keys"),method:"GET",logger:this.logger})]);if(!Array.isArray(e17.keysets)||!Array.isArray(t2.keysets))throw new b("AuthManager: mint returned malformed auth keysets");if(e17.keysets.length>1e4||t2.keysets.length>1e4)throw new b("AuthManager: mint returned more auth keysets than can be processed");let n=e17.keysets.map(e18=>ra(e18)),r=t2.keysets.map(e18=>ia(e18)),i=Ka.mintToCacheDTO(this.mintUrl,n,r);this.keychain=Ka.fromCache(this.mintUrl,"auth",i),this.keychain.getCheapestKeyset()}}getBatMaxMint(){if(!this.info)throw new b("AuthManager: mint info not loaded");let e17=this.info.nuts[22],t2=J(e17?.bat_max_mint,"nuts.22.bat_max_mint",this.maxPerMint);return Math.max(1,Math.min(this.maxPerMint,t2))}getActiveKeys(){if(!this.keychain)throw new b("AuthManager: keyset not loaded for active keyset");return this.keychain.getCheapestKeyset()}async topUp(e17){if(!this.info)throw new b("AuthManager: mint info not loaded");let t2=this.info.requiresClearAuthToken("POST","/v1/auth/blind/mint"),n=this.sessionGeneration,r;if(t2){if(r=await this.ensureCAT(),this.sessionGeneration!==n)throw new b("AuthManager: session changed while obtaining BATs");if(!r)throw new b("AuthManager: Clear-auth token required for /v1/auth/blind/mint but not available. Authenticate with the mint to obtain a CAT first.")}let i=this.getActiveKeys(),a=Z.createRandomData(e17,i),o={outputs:a.map(e18=>e18.blindedMessage)},s={};r&&(s["Clear-auth"]=r);let c=await this.req({endpoint:G(this.mintUrl,"/v1/auth/blind/mint"),method:"POST",headers:s,...r?{redirect:"error"}:{},requestBody:o,logger:this.logger});if(!Array.isArray(c?.signatures)||c.signatures.length!==a.length)throw new b("AuthManager: bad BAT mint response");let l=c.signatures.map(e18=>({...e18,amount:A.from(e18.amount)})),u=a.map((e18,t3)=>e18.toProof(l[t3],i));for(let e18 of u)if(!Ji(e18,i))throw new b("AuthManager: mint returned BAT with invalid DLEQ");if(t2&&this.sessionGeneration!==n)throw new b("AuthManager: session changed while obtaining BATs");this.pool.push(...u),this.logger.debug("AuthManager: performed topUp",{minted:u.length,pool:this.pool.length})}};Mo=No,Mo.MIN_VALID_SECS=30;function Po(e17){return`authA${Ye(utf8ToBytes3(JSON.stringify({id:e17.id,secret:e17.secret,C:e17.C})))}`}import{computeSmartDenominations,getWallet,lookupInvoice,maxKeysetDenomination,missingDleqRecoveryDiagnostic,NwcError,parseNwcUri,payInvoiceReconciling,prepareP2PKMint,restoreProofsFromOutputs,serializeOutputData,swapFeeForProofs,toLockPubkey as toLockPubkey2}from"@dvmkit/sdk/internal";import{DRAIN_DELIVERY_RESERVE_SATS}from"@dvmkit/sdk/server";init_defaults();import{appendFileSync as appendFileSync2,chmodSync as chmodSync6,existsSync as existsSync11,mkdirSync as mkdirSync9,readFileSync as readFileSync12,writeFileSync as writeFileSync9}from"fs";function appendSwapped(entry){appendEntry2({...entry,kind:"swapped",ts:Date.now()})}function appendParked(entry){appendEntry2({...entry,kind:"parked",ts:Date.now()})}function appendMintQuote(entry){appendEntry2({...entry,kind:"mint_quote",ts:Date.now()})}function appendMintPaid(entry){appendEntry2({...entry,kind:"mint_paid",ts:Date.now()})}function appendMintPaymentAttempt(entry){appendEntry2({...entry,kind:"mint_payment_attempt",ts:Date.now()})}function appendMintPaymentRejected(entry){appendEntry2({...entry,kind:"mint_payment_rejected",ts:Date.now()})}function appendMintOutputs(entry){appendEntry2({...entry,kind:"mint_outputs",ts:Date.now()})}function appendMintAbandoned(entry){appendEntry2({...entry,kind:"mint_abandoned",ts:Date.now()})}function readUnparked(dvmId){return scan(dvmId).unparked}function readOpenMintQuotes(dvmId){return scan(dvmId).openQuotes}function scan(dvmId){if(!existsSync11(DRAIN_PARK_LOG_FILE))return{unparked:[],openQuotes:[]};const raw2=readFileSync12(DRAIN_PARK_LOG_FILE,"utf-8");const swapped=new Map;const parked=new Set;const quotes=new Map;const paid=new Map;const paymentRejected=new Map;const outputs=new Map;const abandoned=new Set;for(const line of raw2.split("\n")){if(!line)continue;let entry;try{entry=JSON.parse(line)}catch{continue}if(entry.dvm_id!==dvmId)continue;const key=`${entry.dvm_id}|${entry.credit_id}|${entry.drain_id}`;switch(entry.kind){case"swapped":swapped.set(key,entry);break;case"parked":parked.add(key);break;case"mint_quote":quotes.set(key,entry);break;case"mint_paid":paid.set(key,entry);break;case"mint_payment_attempt":if(paymentRejected.get(key)?.quote_id===entry.quote_id)paymentRejected.delete(key);break;case"mint_payment_rejected":paymentRejected.set(key,entry);break;case"mint_outputs":outputs.set(key,entry);break;case"mint_abandoned":abandoned.add(`${key}|${entry.quote_id}`);break}}const openQuotes=[];for(const[key,quote]of quotes){if(parked.has(key)||swapped.has(key)||abandoned.has(`${key}|${quote.quote_id}`))continue;const paidEntry=paid.get(key);const paymentRejectedEntry=paymentRejected.get(key);const outputsEntry=outputs.get(key);openQuotes.push({quote,...paidEntry?.quote_id===quote.quote_id?{paid:paidEntry}:{},...paymentRejectedEntry?.quote_id===quote.quote_id?{paymentRejected:paymentRejectedEntry}:{},...outputsEntry?.quote_id===quote.quote_id?{outputs:outputsEntry}:{}})}return{unparked:[...swapped.entries()].filter(([k2])=>!parked.has(k2)).map(([,e17])=>e17),openQuotes}}function appendEntry2(entry){if(!existsSync11(BUILDER_CONFIG_DIR)){mkdirSync9(BUILDER_CONFIG_DIR,{recursive:true,mode:448})}if(!existsSync11(DRAIN_PARK_LOG_FILE)){writeFileSync9(DRAIN_PARK_LOG_FILE,"",{mode:384})}else{chmodSync6(DRAIN_PARK_LOG_FILE,384)}appendFileSync2(DRAIN_PARK_LOG_FILE,JSON.stringify(entry)+"\n")}function bolt11AmountMsats(bolt11){const trimmed=bolt11.trim();const separator=trimmed.lastIndexOf("1");if(separator<=0)return null;const match=/^ln(?:bcrt|bc|tbs|tb|sb)(\d+)([munp])?$/i.exec(trimmed.slice(0,separator));if(!match)return null;const digits=Number(match[1]);if(!Number.isFinite(digits))return null;const multiplier=match[2]?.toLowerCase()??"";switch(multiplier){case"m":return digits*1e8;case"u":return digits*1e5;case"n":return digits*100;case"p":return Math.round(digits/10);default:return digits*1e11}}async function serviceDrains(ctx){const summary={fetched:false,drains_seen:0,drains_parked:0,drains_jit_minted:0,drains_failed:0,drains_queued:0,drains_manual:0,drains_channel:0,recovered:0,cashu_liability_sats_after:0};const recovery=new Map;summary.recovered+=await recoverParks(ctx,summary,recovery);await recoverMintQuotes(ctx,summary,recovery);let pending3;try{pending3=await ctx.client.getPendingDrains()}catch(err){rethrowIfBadSignature(err);rethrowIfAdminStateUnavailable(err);if(isMissingDrainSurface(err)){return{...summary,fetched:true}}logDrain(ctx,"drain_pending_fetch_failed",{error:err instanceof Error?err.message:String(err)});return summary}summary.fetched=true;summary.drains_seen=pending3.drains.length;const stillPending=new Set((await refreshedPendingIds(ctx,pending3.drains,summary)).map(d=>`${d.credit_id}|${d.drain_id}`));let cashuOutstandingSats=0;for(const drain of pending3.drains){if(!stillPending.has(`${drain.credit_id}|${drain.drain_id}`))continue;if(drain.method==="cashu"){const key=`${drain.credit_id}|${drain.drain_id}`;const recovered=recovery.get(key);if(recovered==="resolved"){continue}if(recovered){if(recovered==="failed")summary.drains_failed++;else summary.drains_queued++;cashuOutstandingSats+=drain.amount_sats??0;continue}const outcome=await parkOne(ctx,drain,pending3.mints??[]);if(outcome==="parked"||outcome==="jit_minted"){summary.drains_parked++;if(outcome==="jit_minted")summary.drains_jit_minted++}else{if(outcome==="queued")summary.drains_queued++;else summary.drains_failed++;cashuOutstandingSats+=drain.amount_sats??0}}else if(drain.settlement==="channel"){summary.drains_channel++;logDrain(ctx,"drain_channel_settlement_pending",{credit_id:drain.credit_id,drain_id:drain.drain_id,method:drain.method,channel_id:drain.channel_id,amount_micro:drain.amount_micro,hint:"Usually nothing to do \u2014 the caller's channel close settles this one, and their next drain poll finishes the reconciliation. It is not on `dvmctl credit drains-owed`. The exception is a Tempo close that landed on chain and refunded less than the ledger extinguished: that one never clears on a poll, and `dvmctl credit tempo-wedged` is where it shows up (tracked change)."})}else{summary.drains_manual++;logDrain(ctx,"drain_manual_settlement_required",{credit_id:drain.credit_id,drain_id:drain.drain_id,method:drain.method,payout:drain.payout,amount_micro:drain.amount_micro,amount_native:drain.amount_native,hint:`No builder-held on-chain send keys exist; send this refund yourself and record it with \`dvmctl credit drain-settle ${ctx.handle} ${drain.credit_id} ${drain.drain_id} --tx <hash>\`. \`dvmctl credit drains-owed ${ctx.handle}\` lists everything outstanding.`})}}summary.cashu_liability_sats_after=cashuOutstandingSats;return summary}async function recoverParks(ctx,summary,recovery){const unparked=readUnparked(ctx.dvmId);let recovered=0;for(const entry of unparked){const key=`${entry.credit_id}|${entry.drain_id}`;recovery.set(key,"queued");try{await ctx.client.parkDrain({credit_id:entry.credit_id,drain_id:entry.drain_id,token:entry.token,consumed_row_ids:entry.consumed_row_ids,keep_proofs:entry.keep_proofs,...entry.mint_evidence?{mint_evidence:entry.mint_evidence}:{}});appendParked({dvm_id:ctx.dvmId,credit_id:entry.credit_id,drain_id:entry.drain_id});recovered++;recovery.set(key,"resolved");if(entry.mint_evidence)summary.drains_jit_minted++;logDrain(ctx,"drain_park_recovered",{credit_id:entry.credit_id,drain_id:entry.drain_id})}catch(err){rethrowIfAdminStateUnavailable(err);logDrain(ctx,"drain_park_recovery_failed",{credit_id:entry.credit_id,drain_id:entry.drain_id,error:err instanceof Error?err.message:String(err)})}}return recovered}async function refreshedPendingIds(ctx,drains,summary){if(summary.recovered===0)return drains;try{const fresh=await ctx.client.getPendingDrains();return fresh.drains}catch(err){rethrowIfAdminStateUnavailable(err);return drains}}async function parkOne(ctx,drain,mints){const amountSats=drain.amount_sats;const refundPubkey=drain.payout.refund_pubkey;if(!amountSats||amountSats<=0||!refundPubkey){logDrain(ctx,"drain_park_unpriceable",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats});return"failed"}let batches;try{batches=(await ctx.client.getPendingBatches()).batches}catch(err){rethrowIfAdminStateUnavailable(err);logDrain(ctx,"drain_park_batches_fetch_failed",{error:err instanceof Error?err.message:String(err)});return"failed"}const jitAvailable=ctx.refundNwc!==void 0;const selected=await selectCoveringBatch(ctx,drain,amountSats,batches,jitAvailable);if(!selected){return jitMintOne(ctx,drain,amountSats,refundPubkey,mints)}const{batch,wallet,inputProofs,keypair}=selected;let send;let keep;try{const result=await wallet.ops.send(amountSats,inputProofs).asLocked({pubkey:refundPubkey}).keepAsLocked({pubkey:batch.lock_pubkey}).privkey(keypair.privkey).includeFees(false).run();send=result.send;keep=result.keep}catch(err){const recoveryDiagnostic=missingDleqRecoveryDiagnostic(inputProofs,err);logDrain(ctx,"drain_swap_failed",{credit_id:drain.credit_id,drain_id:drain.drain_id,mint_url:batch.mint_url,error:err instanceof Error?err.message:String(err),...recoveryDiagnostic?{recovery:recoveryDiagnostic}:{}});return"failed"}const inputIndexBySecret=new Map(batch.proofs.map((p,i)=>[p.secret,i]));const untouchedInputs=new Set;const change=[];for(const p of keep){const index=inputIndexBySecret.get(p.secret);if(index===void 0)change.push(p);else untouchedInputs.add(index)}const consumedRowIds=batch.row_ids.filter((_,i)=>!untouchedInputs.has(i));const keepProofs=change.map(p=>({id:p.id,amount:amountForJson(p.amount),secret:p.secret,C:p.C,...p.dleq?{dleq:{...p.dleq}}:{}}));if(consumedRowIds.length===0){logDrain(ctx,"drain_park_no_consumed_rows",{credit_id:drain.credit_id,drain_id:drain.drain_id,mint_url:batch.mint_url,batch_rows:batch.row_ids.length});return"failed"}const encoded=ki({mint:batch.mint_url,proofs:rehydrateLocalProofs(send)});appendSwapped({dvm_id:ctx.dvmId,credit_id:drain.credit_id,drain_id:drain.drain_id,token:encoded,consumed_row_ids:consumedRowIds,keep_proofs:keepProofs});try{await ctx.client.parkDrain({credit_id:drain.credit_id,drain_id:drain.drain_id,token:encoded,consumed_row_ids:consumedRowIds,keep_proofs:keepProofs})}catch(err){rethrowIfAdminStateUnavailable(err);logDrain(ctx,"drain_park_post_failed",{credit_id:drain.credit_id,drain_id:drain.drain_id,error:err instanceof Error?err.message:String(err)});return"failed"}appendParked({dvm_id:ctx.dvmId,credit_id:drain.credit_id,drain_id:drain.drain_id});logDrain(ctx,"drain_parked",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats,mint_url:batch.mint_url});return"parked"}async function jitMintOne(ctx,drain,amountSats,refundPubkey,mints){const ids={credit_id:drain.credit_id,drain_id:drain.drain_id};if(!ctx.refundNwc){logDrain(ctx,"drain_jit_unconfigured",{...ids,amount_sats:amountSats,display:"This refund needs sats bought from the hub, and no send wallet is configured to buy them.",hint:"Pass `--refund-nwc <wallet connection URI>` (or set DVMKIT_REFUND_NWC_URL) with a send-capable NWC connection on the wallet holding your Bitcoin deposits. The refund waits, visible in `dvmctl credit drains-owed`, until one is wired."});return"queued"}const keypair=ctx.currentKeypair;if(!keypair){logDrain(ctx,"drain_jit_no_lock_key",{...ids,display:"This refund needs to be minted, and no current builder lock key was resolved to sign the mint quote.",hint:"The mint quote is locked to your builder key (NUT-20) so nobody else can redeem the invoice you pay for. Check `~/.dvmkit/builder.mnemonic` is present and that this DVM is registered in `~/.dvmkit/builder.json`."});return"queued"}let conn;try{conn=parseNwcUri(ctx.refundNwc.uri)}catch(err){logDrain(ctx,"drain_jit_nwc_invalid",{...ids,error:err instanceof Error?err.message:String(err),display:"The refund send wallet's connection string could not be read, so nothing was paid.",hint:"Re-copy the `wallet connection URI` URI from the wallet that holds your Bitcoin deposits. The refund stays owed and retries on the next tick."});return"queued"}const tried=[];for(const mintUrl of mints){tried.push(mintUrl);let wallet;let quote;try{wallet=await(ctx.walletProvider??getWallet)(mintUrl);quote=await wallet.createLockedMintQuote(amountSats,keypair.pubkey)}catch(err){logDrain(ctx,"drain_jit_quote_failed",{...ids,mint_url:mintUrl,amount_sats:amountSats,error:err instanceof Error?err.message:String(err)});continue}const invoiceMsats=bolt11AmountMsats(quote.request);const ceilingMsats=(amountSats+DRAIN_DELIVERY_RESERVE_SATS)*1e3;if(invoiceMsats===null||invoiceMsats>ceilingMsats){logDrain(ctx,"drain_jit_quote_refused",{...ids,mint_url:mintUrl,quote_id:quote.quote,reason:invoiceMsats===null?"invoice_unreadable":"above_ceiling",face_sats:amountSats,invoice_msats:invoiceMsats,ceiling_msats:ceilingMsats,display:invoiceMsats===null?`${mintUrl} asked for this refund's ecash with an invoice whose amount could not be read, so nothing was paid.`:`${mintUrl} wants more for this refund's ecash than the refund is worth, so nothing was paid.`,hint:"Nothing left the wallet, and the unpaid quote simply expires at the mint. Another accepted mint is tried next; if every one of them is refused this way, check the mints' own fee settings before adding one that is cheaper."});continue}const entry={dvm_id:ctx.dvmId,credit_id:drain.credit_id,drain_id:drain.drain_id,mint_url:mintUrl,quote_id:quote.quote,bolt11:quote.request,invoice_msats:invoiceMsats,face_sats:amountSats,reserve_sats:DRAIN_DELIVERY_RESERVE_SATS,expires_at:quote.expiry??null,refund_pubkey:refundPubkey};appendMintQuote(entry);logDrain(ctx,"drain_jit_quoted",{...ids,mint_url:mintUrl,quote_id:quote.quote,face_sats:amountSats,invoice_msats:entry.invoice_msats});return advanceMintQuote(ctx,conn,keypair,{quote:{...entry,kind:"mint_quote",ts:Date.now()}})}logDrain(ctx,"drain_jit_no_mint",{...ids,amount_sats:amountSats,mints_tried:tried,display:tried.length===0?"This refund has to be bought at a Cashu mint and this DVM has none configured, so nothing could be minted.":"No accepted mint would quote for this refund, so nothing was bought and nothing was paid.",hint:tried.length===0?"Set DVMKIT_CASHU_MINTS on the DVM. A non-channel Bitcoin refund is P2PK-locked ecash and nothing else, so without a mint there is no shape it can take.":`Each mint's own error is on the \`drain_jit_quote_failed\` line above it. The refund stays owed and retries every tick \u2014 nothing here needs undoing, and no payment was attempted.`});return"queued"}async function advanceMintQuote(ctx,conn,keypair,open){const entry=open.quote;const refundPubkey=entry.refund_pubkey;const ids={credit_id:entry.credit_id,drain_id:entry.drain_id};const base3={...ids,mint_url:entry.mint_url,quote_id:entry.quote_id};let wallet;try{wallet=await(ctx.walletProvider??getWallet)(entry.mint_url)}catch(err){logDrain(ctx,"drain_jit_mint_unreachable",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint holding this refund's quote is not answering, so the refund is still on its way.",hint:"Nothing is lost and nothing needs undoing \u2014 the quote is recorded and the next tick picks it up where it left off. If the mint stays down, its own status page is the place to look."});return"queued"}let paid=Boolean(open.paid);let feesPaidMsats=open.paid?.fees_paid_msats??null;let checked;if(!paid){if(quoteDead(entry)){appendMintAbandoned({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id,reason:"quote_expired_unpaid"});logDrain(ctx,"drain_jit_quote_abandoned",{...base3,reason:"quote_expired_unpaid",display:"The mint's quote for this refund ran out before it could be paid, so it was dropped unpaid.",hint:"Nothing left the wallet \u2014 the refund is still owed and the next tick asks for a fresh quote. If this repeats, the wallet is the place to look: an exhausted budget or an empty balance keeps a quote from being paid until it expires."});return"queued"}appendMintPaymentAttempt({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id});try{const outcome=await(ctx.payInvoice??payInvoiceReconciling)(conn,entry.bolt11);paid=true;feesPaidMsats=outcome.feesPaidMsats??null;appendMintPaid({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id,preimage:outcome.preimage,...outcome.feesPaidMsats!==void 0?{fees_paid_msats:outcome.feesPaidMsats}:{},...outcome.outcome==="paid"?{}:{recovered:true}});logDrain(ctx,"drain_jit_invoice_paid",{...base3,pay_outcome:outcome.outcome,invoice_msats:entry.invoice_msats,fees_paid_msats:outcome.feesPaidMsats??null})}catch(err){const code=err instanceof NwcError?err.code:"pay_failed";const definitivelyRejected=err instanceof NwcError&&err.method==="pay_invoice"&&code.toLowerCase()!=="payment_unknown";if(definitivelyRejected){appendMintPaymentRejected({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id,error_code:code})}logDrain(ctx,code==="payment_unknown"?"drain_jit_payment_unknown":"drain_jit_payment_failed",{...base3,error_code:code,error:err instanceof Error?err.message:String(err),display:code==="payment_unknown"?"The wallet buying this refund never answered, so we cannot yet say whether the payment went out.":"The wallet could not pay for this refund's ecash, so no money left and the refund is still owed.",hint:code==="payment_unknown"?"Nothing is retried until this resolves \u2014 the next tick asks the wallet about this exact invoice, so it cannot be paid twice. Check the wallet is online and reachable over its relays.":"The wallet's own error is on this line. A balance too low or a budget exhausted are the usual two; the same invoice is retried on the next tick once the wallet can pay it."});return"queued"}}try{checked=await wallet.checkMintQuoteBolt11(entry.quote_id)}catch(err){logDrain(ctx,"drain_jit_quote_state_failed",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint would not say whether it has been paid for this refund yet, so it stays in flight.",hint:"The payment is recorded, so nothing is re-sent. The next tick asks again."});return"queued"}let proofs;if(checked.state===sa.ISSUED){if(!open.outputs){logDrain(ctx,"drain_jit_issued_unrecoverable",{...base3,display:"This refund's ecash was already issued by the mint, but this machine has no record of the outputs needed to collect it.",hint:"Do not re-run the refund \u2014 the drain is deliberately held so it cannot be bought twice. This means another host minted the same quote, or `~/.dvmkit/drain-park.log` lost a line. Check for a second worker against this DVM before doing anything else."});return"failed"}try{proofs=await restoreProofsFromOutputs(wallet,open.outputs.keyset_id,open.outputs.outputs)}catch(err){logDrain(ctx,"drain_jit_restore_failed",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint has this refund's ecash and would not hand back the signatures for it this time.",hint:"The outputs are on disk, so this is recoverable \u2014 the next tick asks the mint again. Nothing was paid twice."});return"queued"}logDrain(ctx,"drain_jit_restored",{...base3,proofs:proofs.length})}else if(checked.state===sa.PAID){const denominations=computeSmartDenominations(entry.face_sats,{maxDenomination:maxKeysetDenomination(wallet),includeTinyTail:false});let preview;try{preview=await prepareP2PKMint(wallet,entry.face_sats,checked,keypair.privkey,refundPubkey,denominations)}catch(err){logDrain(ctx,"drain_jit_prepare_failed",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint has been paid for this refund but would not prepare the notes this time.",hint:"The payment stands and is not repeated \u2014 the next tick prepares them again."});return"queued"}const previewKeysetId=preview.outputData[0]?.blindedMessage.id;if(!previewKeysetId||preview.outputData.some(output=>output.blindedMessage.id!==previewKeysetId)){logDrain(ctx,"drain_jit_prepare_failed",{...base3,error:"The prepared Cashu outputs do not share one keyset.",display:"The mint has been paid for this refund but returned malformed note metadata this time.",hint:"The payment stands and is not repeated \u2014 the next tick prepares the notes again."});return"queued"}appendMintOutputs({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id,keyset_id:previewKeysetId,outputs:serializeOutputData(preview.outputData)});try{proofs=await wallet.completeMint(preview)}catch(err){logDrain(ctx,"drain_jit_mint_failed",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint has been paid for this refund and did not return the notes, so it is still in flight.",hint:"The blinded outputs are recorded, so the next tick can collect the same notes from the mint \u2014 nothing is bought twice."});return"queued"}}else{if(quoteExpired(checked)){logDrain(ctx,"drain_jit_quote_expired_paid",{...base3,invoice_msats:entry.invoice_msats,display:"The hub paid for this refund's ecash and the mint's quote expired before it credited the payment.",hint:`Do not re-run the refund \u2014 the drain is held so it cannot be bought twice. Ask ${entry.mint_url} about quote ${entry.quote_id}; the payment either sits with them or was returned by Lightning. Settle it there, then remove this quote's lines from \`~/.dvmkit/drain-park.log\` to release the drain.`});return"failed"}logDrain(ctx,"drain_jit_awaiting_credit",{...base3,quote_state:checked.state,display:"The hub has paid for this refund's ecash and the mint has not credited the payment yet.",hint:"Ordinary for a moment after a Lightning payment. The next tick collects the notes; nothing is paid again in the meantime."});return"queued"}const evidence={source:"jit_mint",mint_url:entry.mint_url,quote_id:entry.quote_id,face_sats:entry.face_sats,reserve_sats:entry.reserve_sats,invoice_msats:entry.invoice_msats,routing_fee_msats:feesPaidMsats};const encoded=ki({mint:entry.mint_url,proofs:rehydrateLocalProofs(proofs)});appendSwapped({dvm_id:ctx.dvmId,...ids,token:encoded,consumed_row_ids:[],keep_proofs:[],mint_evidence:evidence});try{await ctx.client.parkDrain({...ids,token:encoded,consumed_row_ids:[],keep_proofs:[],mint_evidence:evidence})}catch(err){rethrowIfAdminStateUnavailable(err);logDrain(ctx,"drain_park_post_failed",{...base3,error:err instanceof Error?err.message:String(err)});return"queued"}appendParked({dvm_id:ctx.dvmId,...ids});logDrain(ctx,"drain_jit_parked",{...base3,face_sats:entry.face_sats,reserve_sats:entry.reserve_sats,invoice_msats:entry.invoice_msats,routing_fee_msats:feesPaidMsats,reserve_remainder_msats:entry.reserve_sats*1e3-deliveryCostMsats(entry,feesPaidMsats)});return"jit_minted"}var MINT_QUOTE_STALE_MS=24*60*60*1e3;function quoteDead(entry){if(entry.expires_at!==null)return entry.expires_at*1e3<Date.now();return Date.now()-entry.ts>MINT_QUOTE_STALE_MS}function quoteExpired(quote){return typeof quote.expiry==="number"&"e.expiry*1e3<Date.now()}function deliveryCostMsats(entry,routingFeeMsats){return entry.invoice_msats-entry.face_sats*1e3+(routingFeeMsats??0)}async function recoverMintQuotes(ctx,summary,recovery){const open=readOpenMintQuotes(ctx.dvmId);if(open.length===0)return;const keypair=ctx.currentKeypair;let conn;if(ctx.refundNwc){try{conn=parseNwcUri(ctx.refundNwc.uri)}catch{conn=void 0}}for(const item of open){const key=`${item.quote.credit_id}|${item.quote.drain_id}`;recovery.set(key,"queued");if(!conn||!keypair){logDrain(ctx,"drain_jit_recovery_unconfigured",{credit_id:item.quote.credit_id,drain_id:item.quote.drain_id,quote_id:item.quote.quote_id,display:"A refund purchase from a previous run is unfinished and cannot be checked without the send wallet.",hint:"Re-wire `--refund-nwc` (or DVMKIT_REFUND_NWC_URL) before the next tick. The refund is deliberately held until then, because the earlier payment may already have gone out."});continue}let carried=item;if(!item.paid){const settled=await reconcileQuotePayment(ctx,conn,item.quote,item.paymentRejected);if(settled==="unknown")continue;if(settled!=="unpaid")carried={...item,paid:settled}}const outcome=await advanceMintQuote(ctx,conn,keypair,carried);if(outcome==="jit_minted"){summary.recovered++;summary.drains_jit_minted++;recovery.set(key,"resolved")}else if(outcome==="failed"){recovery.set(key,"failed")}}}async function reconcileQuotePayment(ctx,conn,entry,paymentRejected){const base3={credit_id:entry.credit_id,drain_id:entry.drain_id,quote_id:entry.quote_id,mint_url:entry.mint_url};let tx;try{tx=await(ctx.lookupInvoiceImpl??lookupInvoice)(conn,{invoice:entry.bolt11})}catch(err){const code=err instanceof NwcError?err.code:"lookup_failed";if(code==="NOT_FOUND"){logDrain(ctx,"drain_jit_payment_never_sent",base3);return"unpaid"}logDrain(ctx,"drain_jit_recovery_lookup_failed",{...base3,error_code:code,error:err instanceof Error?err.message:String(err),display:"A refund purchase from a previous run could not be checked, so it is being left alone.",hint:"Nothing is re-sent while this is unanswered \u2014 that is what stops a refund being bought twice. The next tick asks the wallet again."});return"unknown"}if(tx.settledAt){const paid={dvm_id:ctx.dvmId,credit_id:entry.credit_id,drain_id:entry.drain_id,quote_id:entry.quote_id,preimage:tx.preimage??"",...tx.feesPaidMsats!==void 0?{fees_paid_msats:tx.feesPaidMsats}:{},recovered:true};appendMintPaid(paid);logDrain(ctx,"drain_jit_payment_recovered",{...base3,fees_paid_msats:tx.feesPaidMsats??null});return{...paid,kind:"mint_paid",ts:Date.now()}}if(tx.expiresAt&&tx.expiresAt*1e3<Date.now()){logDrain(ctx,"drain_jit_payment_expired_unpaid",base3);return"unpaid"}if(paymentRejected){logDrain(ctx,"drain_jit_payment_retrying",{...base3,error_code:paymentRejected.error_code,display:"The wallet rejected the previous attempt and confirms this refund invoice is still unpaid, so the same invoice is being retried.",hint:"No new mint quote was opened. If the wallet rejects this attempt too, its error is reported and the same safe check runs again next tick."});return"unpaid"}logDrain(ctx,"drain_jit_payment_in_flight",{...base3,display:"A refund purchase from a previous run is still in flight, so nothing new was attempted for it.",hint:"The refund is held until the wallet reports one way or the other \u2014 that is what keeps it from being paid for twice."});return"unknown"}function rehydrateLocalProofs(proofs){return proofs.map(proof=>({...proof,amount:localAmount(proof.amount)}))}function amountForJson(amount2){return localAmount(amount2).toNumber()}function localAmount(amount2){if(typeof amount2==="number"||typeof amount2==="bigint"||typeof amount2==="string"){return A.from(amount2)}if(amount2&&typeof amount2==="object"&&"toBigInt"in amount2){const toBigInt3=amount2.toBigInt;if(typeof toBigInt3==="function"){const value=toBigInt3.call(amount2);if(typeof value==="bigint")return A.from(value)}}throw new TypeError("Cashu proof amount must be a primitive AmountLike or expose toBigInt()")}async function selectCoveringBatch(ctx,drain,amountSats,batches,jitAvailable){const nextStep=jitAvailable?"The refund is minted just in time from the hub instead \u2014 see the `drain_jit_*` lines below.":"";let closestShortfall;const unpriceableMints=new Set;for(const batch of batches){const keypair=ctx.keypairsByPubkey.get(toLockPubkey2(batch.lock_pubkey));if(!keypair)continue;if(batch.total_sats<amountSats)continue;let wallet;let inputProofs;let reserveSats;try{wallet=await(ctx.walletProvider??getWallet)(batch.mint_url);inputProofs=batch.proofs.map(p=>({id:p.id,amount:p.amount,secret:p.secret,C:p.C,...p.dleq?{dleq:{...p.dleq}}:{}}));reserveSats=swapFeeForProofs(wallet,inputProofs)}catch(err){unpriceableMints.add(batch.mint_url);logDrain(ctx,"drain_park_batch_unpriceable",{credit_id:drain.credit_id,drain_id:drain.drain_id,mint_url:batch.mint_url,error:err instanceof Error?err.message:String(err)});continue}const requiredSats=amountSats+reserveSats;if(batch.total_sats>=requiredSats)return{batch,wallet,inputProofs,keypair};if(!closestShortfall||requiredSats-batch.total_sats<closestShortfall.requiredSats-closestShortfall.batch.total_sats){closestShortfall={batch,requiredSats}}}if(closestShortfall){const{batch,requiredSats}=closestShortfall;const shortBySats=requiredSats-batch.total_sats;logDrain(ctx,"drain_park_batch_below_swap_cost",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats,mint_url:batch.mint_url,total_sats:batch.total_sats,required_sats:requiredSats,short_by_sats:shortBySats,batches_seen:batches.length,unpriceable_mints:[...unpriceableMints],hint:`A batch at ${batch.mint_url} holds ${batch.total_sats} sats, which covers the ${amountSats}-sat refund but not the ${requiredSats-amountSats} sats that mint charges to swap it. ${nextStep||`It parks automatically once ${shortBySats} more sats land on that lock key; to intervene, fund the DVM or settle manually.`}`});return void 0}if(unpriceableMints.size>0){const mints=[...unpriceableMints];logDrain(ctx,"drain_park_no_priceable_batch",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats,batches_seen:batches.length,unpriceable_mints:mints,hint:`No accumulator batch could be priced: ${mints.join(", ")} would not answer for its keyset, so the refund's swap cost is unknown. This is a mint problem, not a funding one${nextStep?`. ${nextStep}`:" \u2014 the drain retries on the next tick"}, and the per-batch \`drain_park_batch_unpriceable\` lines carry each mint's error.`});return void 0}logDrain(ctx,"drain_park_insufficient_batch",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats,batches_seen:batches.length,hint:`No single accumulator batch covers this refund yet. ${nextStep||"It parks automatically once enough value accumulates on one lock key at one mint; to intervene, fund the DVM or settle manually."}`});return void 0}function isMissingDrainSurface(err){return err instanceof AdminApiError&&err.status===404}function logDrain(ctx,level,fields){console.log(JSON.stringify({level,ts:new Date().toISOString(),dvm_id:ctx.dvmId,handle:ctx.handle,...fields}))}var DEFAULT_INTERVAL_SECONDS=60;var MIN_INTERVAL_SECONDS=10;var MAX_INTERVAL_SECONDS=3600;var DEFAULT_HOLD_ALARM_AFTER="24h";async function meltPending(handle2,opts){const ctx=await resolveContext(handle2,opts);if(!opts.watch){const summary=await runTick(ctx);emitTickSummary(summary,!!opts.human,ctx.handle);const failure=runFailure(ctx,summary);if(failure)throw failure;recordCleanRun(ctx,summary);return}await runWatchLoop(ctx,opts)}async function resolveContext(handle2,opts){const selected=opts.endpoint?void 0:await resolveDvm(handle2,opts);const{canonicalDvmId,currentKeypair,keypairsByPubkey}=selected?resolveBuilderLockKeyring(selected.dvmId):await resolveBuilderLockKeyringByHandle(handle2,opts.endpoint);const endpoint=await resolveEndpoint(handle2,opts.endpoint,selected);const drainsOnly=!!opts.drainsOnly;const payoutLnAddress=opts.payout??getBuilderDvm(canonicalDvmId)?.payout_ln_address;const payoutNwc=parsePayoutNwc(opts.payoutNwc??process.env.DVMKIT_MELT_PAYOUT_NWC_URL);if(!payoutLnAddress&&!payoutNwc&&!drainsOnly){throw new DvmError27("no_payout_destination","No payout destination configured.","Pass `--payout <ln-address>` or set a default with `dvmctl set-payout "+handle2+" <ln-address>`. To melt into a wallet reachable over NWC instead, pass `--payout-nwc <wallet connection URI>` or set DVMKIT_MELT_PAYOUT_NWC_URL.")}const refundNwcUri=opts.refundNwc??process.env.DVMKIT_REFUND_NWC_URL;const client=new AdminCashuClient({endpoint,dvmId:canonicalDvmId,privkeyHex:currentKeypair.privkey});return{handle:handle2,dvmId:canonicalDvmId,endpoint,currentKeypair,keypairsByPubkey,payoutLnAddress:payoutLnAddress??"",...payoutNwc?{payoutNwc}:{},drainsOnly,holdAlarmAfterMs:resolveHoldAlarmAfterMs(opts.holdAlarmAfter),client,drainCtx:{dvmId:canonicalDvmId,handle:handle2,client,keypairsByPubkey,currentKeypair,...refundNwcUri?{refundNwc:{uri:refundNwcUri}}:{}},fetchImpl:globalThis.fetch.bind(globalThis),human:!!opts.human}}function parsePayoutNwc(uri){if(!uri)return void 0;try{return parseNwcUri2(uri)}catch(err){throw new DvmError27("invalid_payout_nwc",`Melt payout NWC connection could not be read: ${err instanceof Error?err.message:String(err)}`,"Re-copy the `wallet connection URI` URI from the wallet the melt should land in. Nothing was melted \u2014 the run refuses rather than paying the Lightning address you did not name.")}}async function payoutInvoice(ctx,msats){if(ctx.payoutNwc){const invoice=await makeInvoice(ctx.payoutNwc,{amountMsats:msats,description:`dvmkit melt \xB7 ${ctx.handle}`});if(!invoice.invoice){throw new DvmError27("payout_invoice_missing","The payout wallet returned no bolt11 for the melt.","The wallet answered `make_invoice` without an invoice. Check the connection permits `make_invoice`, then re-run \u2014 nothing has melted.")}return invoice.invoice}return fetchLnurlPayInvoice(ctx.payoutLnAddress,msats)}function resolveHoldAlarmAfterMs(input){try{return parseDurationMs(input??DEFAULT_HOLD_ALARM_AFTER)}catch(err){throw new DvmError27("invalid_duration",err instanceof Error?err.message:String(err),"`--hold-alarm-after` takes one count and one unit \u2014 e.g. `6h`, `2d`. Raise it to give a flaky DVM more rope; lower it to hear about a stalled melt sooner.")}}async function resolveEndpoint(handle2,override,selected){if(override)return override.replace(/\/+$/,"");const{token,platformUrl}=selected??requireAuth();const{dvm}=await getDvm(platformUrl,token,selected?.dvmId??handle2);if(!dvm.url){throw new DvmError27("dvm_url_unset",`DVM "${handle2}" has no platform URL yet.`,"If the DVM is still deploying, wait for the deploy to finish. Otherwise pass `--endpoint <url>` (e.g. for self-hosted DVMs).")}return dvm.url.replace(/\/+$/,"")}async function runTick(ctx){const recovered=await runRecovery(ctx);const drains=await serviceDrains(ctx.drainCtx);const meltHeld=!drains.fetched||drains.cashu_liability_sats_after>0;const unknownSince=recordDrainState(ctx.dvmId,drains.fetched);const heldForMs=drainHoldElapsedMs(unknownSince);if(heldForMs!==null&&heldForMs>=ctx.holdAlarmAfterMs){logErr(ctx,"melt_pending_drain_hold_sustained",new Error(`Pending drains have been unreadable since ${unknownSince}; the payout melt has been held ever since.`),{drain_state_unknown_since:unknownSince,hold_alarm_after_ms:ctx.holdAlarmAfterMs})}const summaryBase={tick:new Date().toISOString(),dvm_id:ctx.dvmId,endpoint:ctx.endpoint,recovered,drains_seen:drains.drains_seen,drains_parked:drains.drains_parked,drains_jit_minted:drains.drains_jit_minted,drains_failed:drains.drains_failed,drains_queued:drains.drains_queued,drains_manual:drains.drains_manual,drains_channel:drains.drains_channel,drains_recovered:drains.recovered,drain_state_known:drains.fetched,drain_state_unknown_since:unknownSince,melt_held:meltHeld};const noBatches={batches_seen:0,batches_melted:0,batches_skipped:0,batches_failed:0,sats_melted:0};if(ctx.drainsOnly){logEvent(ctx,"melt_pending_skipped_drains_only",{drain_liability_sats:drains.cashu_liability_sats_after,drain_state_known:drains.fetched});return{...summaryBase,...noBatches,melt_skipped:"drains_only"}}if(meltHeld){logEvent(ctx,"melt_pending_held_for_drains",{drain_liability_sats:drains.cashu_liability_sats_after,drain_state_known:drains.fetched});return{...summaryBase,...noBatches,melt_skipped:null}}let res;try{res=await ctx.client.getPendingBatches()}catch(err){rethrowIfBadSignature(err);rethrowIfAdminStateUnavailable(err);throw new DvmError27("pending_batches_fetch_failed","Failed to fetch pending batches from the DVM admin endpoint.",err instanceof Error?err.message:String(err))}let melted=0;let skipped=0;let failed=0;let satsMelted=0;for(const batch of res.batches){const outcome=await meltBatch(ctx,batch);if(outcome==="melted"){melted++;satsMelted+=batch.total_sats}else if(outcome==="skipped")skipped++;else failed++}return{...summaryBase,batches_seen:res.batches.length,batches_melted:melted,batches_skipped:skipped,batches_failed:failed,sats_melted:satsMelted,melt_skipped:null}}async function meltBatch(ctx,batch){const batchKeypair=ctx.keypairsByPubkey.get(toLockPubkey3(batch.lock_pubkey));if(!batchKeypair){logEvent(ctx,"melt_pending_skip_unknown_lock",{mint_url:batch.mint_url,lock_pubkey:batch.lock_pubkey,row_ids:batch.row_ids,total_sats:batch.total_sats});return"skipped"}let inputFees;try{inputFees=await getInputFeesForProofs(batch.mint_url,batch.proofs)}catch(err){logErr(ctx,"melt_pending_input_fee_lookup_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids});return"failed"}if(batch.total_sats<=inputFees){logEvent(ctx,"melt_pending_input_fees_exceed_batch",{mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,input_fees:inputFees});return"skipped"}let bolt11;try{bolt11=await payoutInvoice(ctx,(batch.total_sats-inputFees)*1e3)}catch(err){logErr(ctx,"melt_pending_payout_invoice_failed",err,{destination:ctx.payoutNwc?"nwc":"lnurl",mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,input_fees:inputFees});return"failed"}let quote;try{quote=await fetchMeltQuote(batch.mint_url,bolt11)}catch(err){logErr(ctx,"melt_pending_quote_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids});return"failed"}if(batch.total_sats<quote.amountSats+quote.feeReserveSats+inputFees){const target=batch.total_sats-quote.feeReserveSats-inputFees;if(target<=0){logEvent(ctx,"melt_pending_fee_reserve_exceeds_batch",{mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,fee_reserve_sats:quote.feeReserveSats,input_fees:inputFees});return"skipped"}try{bolt11=await payoutInvoice(ctx,target*1e3)}catch(err){logErr(ctx,"melt_pending_payout_invoice_failed",err,{destination:ctx.payoutNwc?"nwc":"lnurl",mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,target_sats:target});return"failed"}try{quote=await fetchMeltQuote(batch.mint_url,bolt11)}catch(err){logErr(ctx,"melt_pending_quote_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids});return"failed"}if(batch.total_sats<quote.amountSats+quote.feeReserveSats+inputFees){logEvent(ctx,"melt_pending_fee_reserve_too_high",{mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,amount_sats:quote.amountSats,fee_reserve_sats:quote.feeReserveSats,input_fees:inputFees,retry:true});return"skipped"}}const proofs=batch.proofs.map(p=>({id:p.id,amount:p.amount,secret:p.secret,C:p.C,...p.dleq?{dleq:{...p.dleq}}:{}}));appendPreMelt({dvm_id:ctx.dvmId,row_ids:batch.row_ids,mint_url:batch.mint_url,quote_id:quote.rawQuote.quote,lock_pubkey:batch.lock_pubkey,total_sats:batch.total_sats});let preimage;try{const meltResult=await meltProofsWithQuoteSigned(batch.mint_url,proofs,quote,batchKeypair.privkey);preimage=meltResult.preimage}catch(err){const recoveryDiagnostic=missingDleqRecoveryDiagnostic2(proofs,err);appendPostMelt({dvm_id:ctx.dvmId,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote,status:"failed",error:err instanceof Error?err.message:String(err)});logErr(ctx,"melt_pending_melt_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote,...recoveryDiagnostic?{recovery:recoveryDiagnostic}:{}});return"failed"}if(!preimage){logErr(ctx,"melt_pending_missing_preimage_after_success",new Error("mint returned PAID without payment_preimage"),{mint_url:batch.mint_url,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote});return"failed"}try{await ctx.client.markMelted({row_ids:batch.row_ids,melt_quote_id:quote.rawQuote.quote,payment_preimage:preimage})}catch(err){rethrowIfAdminStateUnavailable(err);logErr(ctx,"melt_pending_mark_melted_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote});return"failed"}appendPostMelt({dvm_id:ctx.dvmId,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote,status:"success",preimage});logEvent(ctx,"melt_pending_batch_melted",{mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,quote_id:quote.rawQuote.quote});return"melted"}async function meltProofsWithQuoteSigned(mintUrl,proofs,quote,privkeyHex){const{getWallet:getWallet2}=await import("@dvmkit/sdk/internal");const wallet=await getWallet2(mintUrl);const{quote:melted}=await wallet.meltProofsBolt11(quote.rawQuote,proofs,{privkey:privkeyHex});return{preimage:melted.payment_preimage??null}}async function runRecovery(ctx){const inFlight=readInFlight(ctx.dvmId);if(inFlight.length===0)return 0;let recovered=0;for(const entry of inFlight){const result=await recoverOne(ctx,entry);if(result==="recovered")recovered++}return recovered}async function recoverOne(ctx,entry){let quote;try{quote=await checkMeltQuoteState(entry.mintUrl,entry.quoteId)}catch(err){logErr(ctx,"melt_pending_recovery_check_failed",err,{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"pending"}if(quote.state==="PENDING"){logEvent(ctx,"melt_pending_recovery_pending",{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"pending"}if(quote.state==="UNPAID"){appendPostMelt({dvm_id:ctx.dvmId,row_ids:entry.rowIds,quote_id:entry.quoteId,status:"failed",error:"ln_unpaid_on_recovery"});logEvent(ctx,"melt_pending_recovery_abandoned",{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"abandoned"}const preimage=quote.payment_preimage;if(!preimage){logErr(ctx,"melt_pending_recovery_paid_no_preimage",new Error("mint returned PAID without payment_preimage"),{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"pending"}try{await ctx.client.markMelted({row_ids:entry.rowIds,melt_quote_id:entry.quoteId,payment_preimage:preimage})}catch(err){rethrowIfAdminStateUnavailable(err);logErr(ctx,"melt_pending_recovery_mark_melted_failed",err,{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"pending"}appendPostMelt({dvm_id:ctx.dvmId,row_ids:entry.rowIds,quote_id:entry.quoteId,status:"success",preimage});logEvent(ctx,"melt_pending_recovery_marked_melted",{mint_url:entry.mintUrl,quote_id:entry.quoteId,row_ids:entry.rowIds});return"recovered"}async function runWatchLoop(ctx,opts){const requestedInterval=opts.interval??DEFAULT_INTERVAL_SECONDS;const intervalSeconds=Math.min(Math.max(MIN_INTERVAL_SECONDS,requestedInterval),MAX_INTERVAL_SECONDS);let stopping=false;let inFlight=null;const fatalHolder={err:null};logEvent(ctx,"melt_pending_watch_started",{interval_seconds:intervalSeconds,endpoint:ctx.endpoint});async function tick(){if(stopping)return;if(inFlight){logEvent(ctx,"melt_pending_tick_skipped_in_flight",{});return}inFlight=(async()=>{try{const summary=await runTick(ctx);emitTickSummary(summary,ctx.human,ctx.handle);const failure=runFailure(ctx,summary);if(failure){logErr(ctx,"melt_pending_tick_not_recorded",failure)}else{recordCleanRun(ctx,summary)}}catch(err){if(err instanceof DvmError27&&err.code==="admin_bad_signature"){fatalHolder.err=err;shutdown();return}logErr(ctx,"melt_pending_tick_error",err)}finally{inFlight=null}})();await inFlight}const timer=setInterval(()=>{void tick()},intervalSeconds*1e3);const shutdown=()=>{if(stopping)return;stopping=true;clearInterval(timer);logEvent(ctx,"melt_pending_watch_stopping",{})};process.on("SIGTERM",shutdown);process.on("SIGINT",shutdown);await tick();await new Promise(resolve10=>{const poll=setInterval(()=>{if(stopping&&!inFlight){clearInterval(poll);resolve10()}},100);if(typeof poll.unref==="function")poll.unref()});if(fatalHolder.err)throw fatalHolder.err}function runFailure(ctx,summary){if(summary.batches_failed>0){return new DvmError27("batches_failed",`${summary.batches_failed} batch(es) failed during this sweep.`,"Inspect the per-batch logs above. Transient failures retry on next run.")}if(ctx.drainsOnly)return drainsUnsettled(summary);return holdSustained(summary,ctx.holdAlarmAfterMs)}function recordCleanRun(ctx,summary){recordMeltSuccess(ctx.dvmId,ctx.drainsOnly?"drains_only":"sweep",{handle:ctx.handle,batches_melted:summary.batches_melted,sats_melted:summary.sats_melted,drains_parked:summary.drains_parked})}function drainsUnsettled(summary){if(!summary.drain_state_known){return new DvmError27("drain_state_unknown",`Could not read this DVM's pending credit drains, so ${settledBeforeFetchFailed(summary)} and this run cannot say what it still owes.`,"See `drain_pending_fetch_failed` above for the underlying error, then check the DVM is reachable and still advertises the lock pubkey this mnemonic derives. Every drain counter except `drains_recovered` reads zero for want of an answer, not for want of work.")}const unsettled=summary.drains_failed+summary.drains_manual+summary.drains_queued;if(unsettled===0)return null;return new DvmError27("drains_unsettled",`${unsettled} credit drain(s) went unsettled (failed=${summary.drains_failed}, manual=${summary.drains_manual}, queued=${summary.drains_queued}).`,unsettledDrainHint(summary))}function holdSustained(summary,holdAlarmAfterMs){const heldForMs=drainHoldElapsedMs(summary.drain_state_unknown_since);if(heldForMs===null||heldForMs<holdAlarmAfterMs)return null;return new DvmError27("drain_state_unknown_sustained",`This DVM's pending credit drains have been unreadable since ${summary.drain_state_unknown_since} (${Math.floor(heldForMs/36e5)}h), so the payout melt has been held that whole time and no owed refund has parked.`,"See `drain_pending_fetch_failed` above for the underlying error. Check the DVM is up and its admin endpoint reachable \u2014 nothing melts and no caller gets refunded until it answers. Raise `--hold-alarm-after` if this DVM is expected to be offline this long.")}function settledBeforeFetchFailed(summary){if(summary.drains_recovered===0)return"nothing was settled";return`only the ${summary.drains_recovered} park(s) replayed from the local log were settled`}function unsettledDrainHint(summary){const hints=[];if(summary.drains_failed>0){hints.push("`failed`: inspect the per-drain logs above \u2014 `drain_park_insufficient_batch` means no single accumulator batch covers the refund yet, so fund the DVM or wait for accumulation and it parks on a later run.")}if(summary.drains_manual>0){hints.push("`manual`: x402/tempo refunds have no builder-held send keys \u2014 list them with `dvmctl credit drains-owed <handle>`, send each one yourself, and record it with `dvmctl credit drain-settle <handle> <credit-id> <drain-id> --tx <hash>`.")}if(summary.drains_queued>0){hints.push("`queued`: nothing was attempted for these \u2014 the `drain_jit_*` lines above say why. `drain_jit_unconfigured` means no send wallet is wired to buy the refund's ecash; `drain_jit_no_mint` means no accepted mint would quote; anything naming a payment in flight is being held on purpose so the refund cannot be bought twice.")}return hints.join(" ")}function emitTickSummary(summary,human,slug){if(human){info(`[${summary.tick}] dvm=${summary.dvm_id} seen=${summary.batches_seen} melted=${summary.batches_melted} skipped=${summary.batches_skipped} failed=${summary.batches_failed} sats=${summary.sats_melted} recovered=${summary.recovered} drains=${summary.drains_seen} parked=${summary.drains_parked} drain_failed=${summary.drains_failed} drain_queued=${summary.drains_queued} drain_manual=${summary.drains_manual}${drainStateNote(summary)}${meltNote(summary)}`)}else{json({...summary,dvmId:summary.dvm_id,slug})}}function drainStateNote(summary){if(summary.drain_state_known)return"";if(!summary.drain_state_unknown_since)return" (drain state unknown)";return` (drain state unknown since ${summary.drain_state_unknown_since})`}function meltNote(summary){if(summary.melt_skipped==="drains_only")return" (melt skipped: --drains-only)";return summary.melt_held?" (melt held for drains)":""}function logEvent(ctx,level,fields){console.log(JSON.stringify({level,ts:new Date().toISOString(),dvm_id:ctx.dvmId,handle:ctx.handle,...fields}))}function logErr(ctx,level,err,fields={}){console.error(JSON.stringify({level,ts:new Date().toISOString(),dvm_id:ctx.dvmId,handle:ctx.handle,error:err instanceof Error?err.message:String(err),...err instanceof DvmError27?{code:err.code,...err.hint?{hint:err.hint}:{},...err.display?{display:err.display}:{}}:err instanceof AdminApiError?{status:err.status,reason:err.body.reason,code:err.body.error}:{},...fields}))}import{DvmError as DvmError28}from"@dvmkit/sdk/internal";init_builder_store();init_defaults();init_output();function meltStatus(handle2,opts){const maxAgeMs=resolveMaxAgeMs(opts.maxAge);const records=readMeltSuccesses();const nowMs=Date.now();const except=validatedExcept(opts.except??[]);const configured=configuredTargets();const all=targets(handle2,configured);refuseAmbiguousExcept(all,except);const watched=all.filter(target=>!except.has(target.handle));const excepted=all.filter(target=>except.has(target.handle)).map(t2=>t2.handle);const configuredIds=new Set(configured.map(target=>target.dvmId));const orphaned=[...records.keys()].filter(dvmId=>!configuredIds.has(dvmId)).sort();const dvms=all.map(target=>{const record2=records.get(target.dvmId)??null;return entryFor(target,record2,except.has(target.handle)?null:maxAgeMs,nowMs)});emit(dvms,{maxAgeMs,excepted,orphaned,human:!!opts.human});if(maxAgeMs!==null&&watched.length===0)nothingToWatch(all.length>0);const stale=dvms.filter(entry=>entry.stale);if(stale.length>0)throw staleError(stale,opts.maxAge??"")}function entryFor(target,record2,maxAgeMs,nowMs){const sweep=record2?.sweep??null;const drainsOnly=record2?.drains_only??null;const sweepAgeMs=meltRunAgeMs(sweep,nowMs);const drainsOnlyAgeMs=meltRunAgeMs(drainsOnly,nowMs);return{handle:target.handle,dvm_id:target.dvmId,last_success_at:sweep?.at??null,age_seconds:sweepAgeMs===null?null:Math.floor(sweepAgeMs/1e3),stale:maxAgeMs!==null&&(sweepAgeMs===null||sweepAgeMs>maxAgeMs),batches_melted:sweep?.batches_melted??null,sats_melted:sweep?.sats_melted??null,drains_parked:sweep?.drains_parked??null,last_drains_only_at:drainsOnly?.at??null,drains_only_age_seconds:drainsOnlyAgeMs===null?null:Math.floor(drainsOnlyAgeMs/1e3)}}var HANDLE_PATTERN=/^[a-z0-9][a-z0-9-]{0,62}$/;function validatedExcept(handles){for(const handle2 of handles){if(HANDLE_PATTERN.test(handle2))continue;throw new DvmError28("invalid_except_handle",`\`--except ${handle2||"<empty>"}\` is not a DVM handle.`,"A handle is lowercase letters, digits and hyphens. This most often means the value was swallowed from the next flag \u2014 `--except --max-age 30h` reads `--max-age` as the handle and leaves no window, which turns the alarm into a plain read that always exits 0. Put a handle after every `--except`, and repeat the flag for each one.")}return new Set(handles)}function refuseAmbiguousExcept(all,except){for(const handle2 of except){const matches2=all.filter(target=>target.handle===handle2);if(matches2.length<=1)continue;throw new DvmError28("ambiguous_dvm_handle",`${matches2.length} builder.json entries claim the handle "${handle2}", so \`--except ${handle2}\` cannot pick between them.`,`Excepting by handle would drop every one of them from the alarm, including a DVM that is still melting. Candidates: ${matches2.map(target=>target.dvmId).join(", ")}. Remove the entry you no longer operate from ${BUILDER_FILE}, then except the handle.`)}}function targets(handle2,configured){if(handle2){const entry=requireBuilderDvmByHandle(handle2);return[{handle:entry.handle,dvmId:entry.canonical_dvm_id}]}return configured}function configuredTargets(){return Object.values(loadBuilderStore().dvms).map(entry=>({handle:entry.handle,dvmId:entry.canonical_dvm_id})).sort((a,b2)=>a.handle.localeCompare(b2.handle))}function nothingToWatch(allExcepted){throw new DvmError28("no_dvms_recorded",allExcepted?"Every DVM on this machine was excluded by `--except`, so `--max-age` has nothing to check.":`No DVMs are recorded in ${BUILDER_FILE}, so \`--max-age\` has nothing to check.`,allExcepted?"Exiting 0 here would be an alarm that can never fire, so this refuses instead. Drop an `--except` flag, or drop `--max-age` if you only wanted to read the record.":"Exiting 0 here would be an alarm that can never fire, so this refuses instead. The usual cause is the command running against the wrong state directory rather than a machine with no DVMs \u2014 a cron or launchd job runs in a minimal environment, so check `HOME` is the account that deployed these DVMs, or set `DVMKIT_CONFIG_DIR` explicitly in the job.")}function resolveMaxAgeMs(input){if(!input)return null;try{return parseDurationMs(input)}catch(err){throw new DvmError28("invalid_duration",err instanceof Error?err.message:String(err),"`--max-age` takes one count and one unit \u2014 e.g. `30h`, `2d`. Set it a little longer than your melt cadence so a single late run is not an alarm.")}}function staleError(stale,maxAge){const named=stale.map(entry=>entry.last_success_at?`${entry.handle} (last swept ${entry.last_success_at})`:`${entry.handle} (never swept on this machine)`).join(", ");return new DvmError28("melt_stale",`${stale.length} DVM(s) have not melted successfully within ${maxAge}: ${named}.`,"Nothing is being swept to your payout destination and no caller refund is parking for these DVMs. Check the scheduled `dvmctl melt-pending` is still running at all \u2014 a cron that stopped firing or a `--watch` daemon that was killed is the usual cause \u2014 then run it by hand and read the error it gives you. A `--drains-only` run does not count here: it settles refunds and sweeps nothing. If one of these DVMs has no Cashu rail and is never meant to melt, exclude it with `--except <handle>`.")}function emit(dvms,ctx){if(!ctx.human){json({dvms,max_age_seconds:ctx.maxAgeMs===null?null:Math.floor(ctx.maxAgeMs/1e3),excepted:ctx.excepted,orphaned:ctx.orphaned,state_file:MELT_SUCCESS_FILE});return}if(dvms.length===0){info("No configured DVMs to report on.")}else{for(const entry of dvms){info(`${entry.handle}: ${entry.last_success_at?`last clean sweep ${entry.last_success_at} (${describeAge(entry.age_seconds)} ago)`:"no clean sweep recorded on this machine"}${entry.stale?" \u2014 STALE":""}${entry.last_drains_only_at?` \xB7 last drains-only ${describeAge(entry.drains_only_age_seconds)} ago`:""}`)}}if(ctx.excepted.length>0)info(`Excepted: ${ctx.excepted.join(", ")}`);if(ctx.orphaned.length>0){info(`Orphaned melt records (not watched): ${ctx.orphaned.join(", ")}`)}info(`Record: ${MELT_SUCCESS_FILE}`)}function describeAge(seconds2){if(seconds2===null)return"unknown";if(seconds2<3600)return`${Math.floor(seconds2/60)}m`;if(seconds2<86400)return`${Math.floor(seconds2/3600)}h`;return`${Math.floor(seconds2/86400)}d`}init_output();async function metrics(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const hours2=opts.hours?Number(opts.hours):24;const result=await getMetrics(platformUrl,token,dvmId,hours2);if(opts.human){if(result.length===0){info(`No metrics for "${slug}" in the last ${hours2} hours.`);return}let total=0;let ok=0;let clientErr=0;let serverErr=0;let latencyMs=0;for(const m of result){total+=m.totalRequests;ok+=m.status2xx;clientErr+=m.status4xx;serverErr+=m.status5xx;latencyMs+=m.totalLatencyMs}const pct=n=>total>0?(n/total*100).toFixed(1):"0.0";const avgLatency=total>0?Math.round(latencyMs/total):0;info(` Last ${hours2} hours:`);info(` Total requests: ${total.toLocaleString()}`);info(` Success (2xx): ${ok.toLocaleString()} (${pct(ok)}%)`);info(` Client err (4xx): ${clientErr.toLocaleString()} (${pct(clientErr)}%)`);info(` Server err (5xx): ${serverErr.toLocaleString()} (${pct(serverErr)}%)`);info(` Avg latency: ${avgLatency}ms`)}else{json({dvmId,slug,hours:hours2,metrics:result})}}init_output();async function orgs(opts){const{token,platformUrl}=requireAuth();const activeOrg=loadActiveOrg();const memberships=await listBuilderOrgs(platformUrl,token);if(opts.human){printHuman(memberships,activeOrg);return}const sharedCount=memberships.filter(membership=>!membership.isPersonal).length;json({activeOrg,memberships:memberships.map(membership=>outputMembership(membership,activeOrg)),display:sharedCount===0?`No shared org memberships. Active context: ${activeOrg??"personal"}.`:`${sharedCount} shared org membership${sharedCount===1?"":"s"}. Active context: ${activeOrg??"personal"}.`,hint:sharedCount===0?"Create or join a shared org in the dashboard. After you join, run `dvmctl switch <handle>`.":"Run `dvmctl switch <handle>` to choose a shared org, or `dvmctl switch --personal` for your personal context."})}function outputMembership(membership,activeOrg){const active=membership.isPersonal?activeOrg===null:membership.handle===activeOrg;if(membership.isPersonal){return{displayName:membership.displayName,role:membership.role,personal:true,active}}return{handle:membership.handle,displayName:membership.displayName,role:membership.role,personal:false,active}}function printHuman(memberships,activeOrg){info(`Active context: ${activeOrg??"personal"}`);const shared=memberships.filter(membership=>!membership.isPersonal);if(shared.length===0)info("No shared org memberships.");if(memberships.length===0)return;const rows=memberships.map(membership=>({handle:membership.isPersonal?"\u2014":membership.handle,name:membership.isPersonal?`${membership.displayName??"Personal context"} (personal)`:membership.displayName??"\u2014",role:membership.role,active:membership.isPersonal?activeOrg===null:membership.handle===activeOrg}));const handleW=Math.max(6,...rows.map(row=>row.handle.length));const nameW=Math.max(4,...rows.map(row=>row.name.length));const roleW=Math.max(4,...rows.map(row=>row.role.length));info("");info(` ${"HANDLE".padEnd(handleW)} ${"NAME".padEnd(nameW)} ${"ROLE".padEnd(roleW)} ACTIVE`);for(const row of rows){info(` ${row.handle.padEnd(handleW)} ${row.name.padEnd(nameW)} ${row.role.padEnd(roleW)} ${row.active?"yes":"no"}`)}}init_output();async function pause(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await pauseDvm(platformUrl,token,dvmId);if(opts.human){for(const m of result.machines){info(`${m.id}: ${m.state}`)}info(`Paused "${slug}". It's no longer serving traffic and its machines are stopping. Data, secrets and database are untouched \u2014 run \`dvmctl resume ${slug}\` to bring it back.`)}else{json({...result,dvmId,slug})}}init_output();async function restart(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await restartMachines(platformUrl,token,dvmId,{machine:opts.machine});if(opts.human){for(const m of result.machines){info(`${m.id}: ${m.state}`)}info(`Restarted ${result.restarted} machine${result.restarted===1?"":"s"}.`)}else{json({...result,dvmId,slug})}}init_output();async function resume(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await resumeDvm(platformUrl,token,dvmId);if(opts.human){for(const m of result.machines){info(`${m.id}: ${m.state}`)}info(`Resumed "${slug}". It's serving traffic again on the same image.`)}else{json({...result,dvmId,slug})}}import{writeFileSync as writeFileSync10}from"fs";init_output();async function revenueCsv(opts){const{token,platformUrl}=requireAuth();const{csv,org}=await getRevenueCsv(platformUrl,token,{from:opts.from,to:opts.to,currency:opts.currency,rail:opts.rail,org:resolveOrgScope(opts)});info(` Org: ${org}`);if(opts.out){writeFileSync10(opts.out,csv,"utf-8");info(` CSV written to ${opts.out}`)}else{process.stdout.write(csv)}}init_output();async function revenueEvents(opts){const{token,platformUrl}=requireAuth();const result=await getRevenueEvents(platformUrl,token,{from:opts.from,to:opts.to,rail:opts.rail,limit:opts.limit!==void 0?Number(opts.limit):void 0,org:resolveOrgScope(opts)});if(opts.human){info(` Org: ${scopeLabel(result.org)}`);if(result.events.length===0){info(` No revenue events found for ${scopeLabel(result.org)}.`);return}info(` ${result.total} total events (showing ${result.events.length})`);info("");const dateW=10;const railW=Math.max(4,...result.events.map(e17=>e17.rail.length));const typeW=Math.max(4,...result.events.map(e17=>e17.source_type.length));const slugW=Math.max(3,...result.events.map(e17=>e17.dvm_slug.length));info(` ${"DATE".padEnd(dateW)} ${"RAIL".padEnd(railW)} ${"TYPE".padEnd(typeW)} ${"DVM".padEnd(slugW)} ${"AMOUNT".padStart(12)} DESCRIPTION`);for(const e17 of result.events){const cur=e17.fiat_currency.toUpperCase();info(` ${e17.date.padEnd(dateW)} ${e17.rail.padEnd(railW)} ${e17.source_type.padEnd(typeW)} ${e17.dvm_slug.padEnd(slugW)} ${formatMinor(e17.net_fiat_minor,cur).padStart(12)} ${e17.line_description}`)}}else{json(result)}}function formatMinor(minor,currency){const major=(minor/100).toFixed(2);const symbols={GBP:"\xA3",EUR:"\u20AC",USD:"$",CHF:"CHF "};const sym=symbols[currency]??`${currency} `;return`${sym}${major}`}init_output();async function revenueSummary(opts){const{token,platformUrl}=requireAuth();const result=await getRevenueSeries(platformUrl,token,{from:opts.from,to:opts.to,currency:opts.currency,org:resolveOrgScope(opts)});if(opts.human){const s=result.summary;const cur=s.fiat_currency.toUpperCase();info(` Revenue summary for ${scopeLabel(result.org)} (${s.period.from} to ${s.period.to})`);info("");info(` Total: ${formatMinor2(s.total_gross_fiat_minor,cur)} (${s.total_count} events)`);info("");if(s.by_source_type_rail.length>0){const typeW=Math.max(4,...s.by_source_type_rail.map(r=>r.source_type.length));const railW=Math.max(4,...s.by_source_type_rail.map(r=>r.rail.length));info(` ${"TYPE".padEnd(typeW)} ${"RAIL".padEnd(railW)} ${"AMOUNT".padStart(12)} COUNT`);for(const row of s.by_source_type_rail){info(` ${row.source_type.padEnd(typeW)} ${row.rail.padEnd(railW)} ${formatMinor2(row.gross_fiat_minor,cur).padStart(12)} ${row.count}`)}}if(s.cross_rate_note){info("");info(` Note: ${s.cross_rate_note}`)}for(const w of result.stale_fx_warnings){info(` ! ${w}`)}}else{json(result)}}function formatMinor2(minor,currency){const major=(minor/100).toFixed(2);const symbols={GBP:"\xA3",EUR:"\u20AC",USD:"$",CHF:"CHF "};const sym=symbols[currency]??`${currency} `;return`${sym}${major}`}init_output();async function rollback(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const{deployId,rolledBackTo}=await rollbackDvm(platformUrl,token,dvmId,{to:opts.to});if(opts.human){info(`Rolling back ${slug} to deploy ${rolledBackTo}...`);info(` Deploy queued: ${deployId}`)}else{progress({event:"queued",deploy_id:deployId,rolled_back_to:rolledBackTo})}const result=await streamDeployLogs(platformUrl,token,deployId,{onLog:line=>{if(opts.human)info(` ${line}`);else progress({event:"log",line})},onPhase:({status:status2,elapsedMs})=>{if(opts.human)info(` ${status2}... (${fmtElapsed(elapsedMs)})`);else progress({event:"phase",phase:status2,elapsed_ms:elapsedMs})}});if(opts.human){info(`
|
|
2433
|
-
Rolled back to ${result.url}`);if(result.dvmkitUrl)info(` Public URL: ${result.dvmkitUrl}`);info("")}else{json({status:"deployed",url:result.url,dvmkitUrl:result.dvmkitUrl,slug,dvmId,deployId,rolledBackTo})}}import{deriveBuilderLockKeypair as deriveBuilderLockKeypair3,DvmError as DvmError29}from"@dvmkit/sdk/internal";init_builder_mnemonic();init_builder_lock_identity();init_builder_store();init_output();async function rotate(handle2,opts){const mnemonic=readBuilderMnemonic();if(!mnemonic){throw new DvmError29("no_builder_mnemonic","No builder mnemonic found.","Run `dvmctl lock create` first to generate or import a mnemonic.")}const selected=opts.endpoint?void 0:await resolveDvm(handle2,opts);let directKeyring;let builderEntry;if(selected){builderEntry=requireSelectedBuilderDvm(selected.dvmId)}else{directKeyring=await resolveBuilderLockKeyringByHandle(handle2,opts.endpoint);builderEntry=requireSelectedBuilderDvm(directKeyring.canonicalDvmId)}const currentIndex=builderEntry.current_rotation_index;const nextIndex=currentIndex+1;const nextKeypair=deriveBuilderLockKeypair3(mnemonic,builderEntry.canonical_dvm_id,nextIndex);const target=await resolveRotationTarget(handle2,builderEntry.canonical_dvm_id,opts.endpoint,!!builderEntry.self_hosted,selected);let response;let resyncedFrom409=false;let platformSyncWarning;if(target.kind==="platform-isolate"){try{const platformResponse=await rotateDvmLockPubkey(target.platformUrl,target.token,builderEntry.canonical_dvm_id,nextKeypair.pubkey);response={current:platformResponse.current,retired:platformResponse.retired};if(platformResponse.lock_pubkey_sync_warning){platformSyncWarning=platformResponse.lock_pubkey_sync_warning}}catch(err){if(err instanceof DvmError29&&err.code==="no_op_rotation"){response={current:nextKeypair.pubkey,retired:[]};resyncedFrom409=true}else{throw err}}}else{const currentKeypair=directKeyring?.currentKeypair??deriveBuilderLockKeypair3(mnemonic,builderEntry.canonical_dvm_id,currentIndex);const client=new AdminCashuClient({endpoint:target.endpoint,dvmId:builderEntry.canonical_dvm_id,privkeyHex:currentKeypair.privkey});try{response=await client.rotateLockPubkey({new_pubkey:nextKeypair.pubkey})}catch(err){if(err instanceof AdminApiError&&err.isBadSignature){throw new DvmError29("admin_bad_signature","DVM admin endpoint rejected our signed challenge (bad_signature).","The DVM's currently-published lock pubkey does not match the privkey derived from this mnemonic + current rotation_index. Confirm `~/.dvmkit/builder.json` is in sync with the DVM.")}if(err instanceof AdminApiError&&err.status===409){response={current:nextKeypair.pubkey,retired:[]};resyncedFrom409=true}else{throw err}}if(!builderEntry.self_hosted){try{const{token,platformUrl}=requireAuth();await setDvmLockPubkey(platformUrl,token,builderEntry.canonical_dvm_id,nextKeypair.pubkey)}catch(err){throw new DvmError29("platform_lock_sync_failed",`Rotated "${handle2}" on the DVM, but could not update the platform's record of its lock pubkey: ${err instanceof Error?err.message:String(err)}`,`The rotation itself landed and builder.json is at index ${nextIndex}. Re-run this command from a machine with platform auth, or run \`dvmctl rotate ${handle2}\` without \`--endpoint\`, before the next \`dvmctl deploy\` \u2014 a deploy against the stale record re-injects the old pubkey and every melt then fails admin_bad_signature.`)}}}patchBuilderDvm(builderEntry.canonical_dvm_id,{current_rotation_index:nextIndex});if(opts.human){info(resyncedFrom409?`Resynced builder.json \u2014 DVM was already at rotation_index ${nextIndex} (prior rotate landed without bumping the local index).`:`Rotated lock pubkey for "${handle2}".`);info(` rotation_index: ${currentIndex} \u2192 ${nextIndex}`);info(` new pubkey: ${response.current}`);if(response.retired.length>0){info(` retired pubkeys in grace window:`);for(const r of response.retired){info(` ${r.pubkey} (retired ${new Date(r.retired_at_ms).toISOString()})`)}}if(platformSyncWarning){info(` Warning: platform bookkeeping sync failed \u2014 ${platformSyncWarning}`);info(" Re-run `dvmctl rotate` once the platform is reachable, or update via dashboard.")}}else{json({status:resyncedFrom409?"resynced":"rotated",handle:handle2,dvmId:builderEntry.canonical_dvm_id,slug:handle2,canonical_dvm_id:builderEntry.canonical_dvm_id,previous_rotation_index:currentIndex,current_rotation_index:nextIndex,current_pubkey:response.current,retired:response.retired,platform_sync_warning:platformSyncWarning})}}async function resolveRotationTarget(handle2,dvmId,override,selfHosted,selected){if(override){return{kind:"sdk-admin",endpoint:override.replace(/\/+$/,"")}}if(selfHosted){throw new DvmError29("endpoint_required",`Self-hosted DVM "${handle2}" needs an explicit \`--endpoint <url>\`.`,"Platform lookup is skipped for self-hosted DVMs \u2014 pass the DVM's public URL.")}if(!resolveAuth()){throw new DvmError29("auth_required","Not authenticated.","Set DVMKIT_API_KEY or run `dvmctl auth` so the CLI can resolve the DVM endpoint via the platform.")}const{token,platformUrl}=selected??requireAuth();const{dvm}=await getDvm(platformUrl,token,dvmId);if(dvm.runtime==="isolate"){return{kind:"platform-isolate",platformUrl,token}}if(!dvm.url){throw new DvmError29("dvm_url_unset",`DVM "${handle2}" has no platform URL yet.`,"If the DVM is still deploying, wait for it to finish. Otherwise pass `--endpoint <url>`.")}return{kind:"sdk-admin",endpoint:dvm.url.replace(/\/+$/,"")}}import{DvmError as DvmError30}from"@dvmkit/sdk/internal";init_output();async function scale(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);if(opts.count===void 0&&opts.size===void 0){throw new DvmError30("bad_request","Nothing to scale.",`Pass --count <n> and/or --size <vm-size>, e.g. dvmctl scale ${slug} --count 2.`)}let count;if(opts.count!==void 0){count=Number(opts.count);if(!Number.isInteger(count)||count<1||count>8){throw new DvmError30("bad_request","--count must be an integer between 1 and 8.")}}const result=await scaleDvm(platformUrl,token,dvmId,{count,size:opts.size});if(opts.human){const{before,after}=result;info(`Scaled ${result.slug}:`);if(before.maxMachines!==after.maxMachines){info(` machines: ${before.maxMachines} \u2192 ${after.maxMachines}`)}const sizeBefore=`${before.cpuCount}\xD7 ${before.cpuKind} CPU, ${before.memoryMb} MB`;const sizeAfter=`${after.cpuCount}\xD7 ${after.cpuKind} CPU, ${after.memoryMb} MB`;if(sizeBefore!==sizeAfter){info(` size: ${sizeBefore} \u2192 ${sizeAfter}`)}}else{json({...result,dvmId,slug})}}init_output();async function secretsList(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const secrets=await listSecrets(platformUrl,token,dvmId);if(opts.human){if(secrets.length===0){info("No secrets set.")}else{for(const s of secrets){info(` ${s.name} (applied ${s.last_applied_at})`)}}}else{json({dvmId,slug,secrets})}}init_builder_store();init_output();import{DvmError as DvmError31,validateLnAddress}from"@dvmkit/sdk/internal";async function setPayout(handle2,lnAddress,opts){if(opts.selfHosted&&opts.org){throw new DvmError31("invalid_scope","--self-hosted cannot be combined with --org.","Use --self-hosted for the local DVM created by `dvmctl init`, or omit it to select a platform DVM with --org.")}const selected=opts.selfHosted?void 0:await resolveDvm(handle2,opts);const existing=selected?requireSelectedBuilderDvm(selected.dvmId):requireBuilderDvmByHandle(handle2);const dvmId=selected?.dvmId??existing.canonical_dvm_id;if(!opts.skipPreflight){await validateLnAddress(lnAddress)}patchBuilderDvm(dvmId,{payout_ln_address:lnAddress});if(opts.human){info(`Payout address for "${handle2}" set to ${lnAddress}.`);info("\n`dvmctl melt-pending "+handle2+"` now melts to this address by default. Override per-run with `--payout <addr>`.")}else{json({status:"set",handle:handle2,dvmId,slug:handle2,payout_ln_address:lnAddress})}}init_output();async function ssh(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);if(!opts.command){const code=await openSshSession(platformUrl,token,dvmId,{machine:opts.machine});process.exit(code)}const result=await execCommand(platformUrl,token,dvmId,opts.command,{machine:opts.machine});if(opts.human){if(result.stdout)raw(result.stdout.replace(/\n$/,""));if(result.stderr)info(result.stderr.replace(/\n$/,""));if(result.exit_code!==0)info(`(exit code ${result.exit_code})`)}else{json({...result,dvmId,slug})}process.exit(result.exit_code)}init_output();async function status(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await getMachineStatus(platformUrl,token,dvmId);if(opts.human){if(result.suspensionReason==="builder_pause"){info(`"${slug}" is paused. Run \`dvmctl resume ${slug}\` to bring it back online.`)}else if(result.suspensionReason==="free_tier_idle"){info(`"${slug}" is idle \u2014 the platform stopped its machines after a quiet spell. The next request wakes it automatically; nothing to fix. Run \`dvmctl resume ${slug}\` to bring it back now.`)}else if(result.status==="suspended"){const reason=result.suspensionReason??"operator";const pause2=result.paused?` Your pause is still on record \u2014 "${slug}" returns to paused once the suspension is lifted.`:"";info(`"${slug}" is suspended by the platform (${reason}); \`dvmctl resume\` won't lift it.${pause2}`)}if(result.machines.length===0){info("No machines (DVM is not currently running any).")}for(const m of result.machines){info("");info(` Machine: ${m.id}`);info(` State: ${m.state}`);info(` Region: ${m.region??"\u2014"}`);info(` Image: ${m.image.version??"\u2014"}`);info(` Created: ${fmtDate5(m.created)}`);info(` Started: ${fmtDate5(m.started)}`);if(m.checks.length>0){info(" Checks:");for(const check2 of m.checks){const endpoint=check2.endpoint?` (${check2.endpoint})`:"";info(` ${check2.name??"?"}: ${check2.status??"?"}${endpoint}`)}}}info("");const vm=result.scale.vm_size;const size4=vm?`${vm.cpus??"?"}\xD7 ${vm.cpu_kind??"?"}, ${vm.memory_mb??"?"}MB`:"\u2014";info(` Scale: ${result.scale.count} machine${result.scale.count===1?"":"s"} (${size4})`)}else{json({...result,dvmId,slug})}}function fmtDate5(iso){if(!iso)return"\u2014";const ms=Date.parse(iso);if(Number.isNaN(ms))return iso;return new Date(ms).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}import{DvmError as DvmError32}from"@dvmkit/sdk/internal";init_output();async function switchCmd(handle2,opts){if(opts.personal&&handle2!=null){throw new DvmError32("bad_arguments","Cannot pass both <handle> and --personal.","Use `dvmctl switch <handle>` to set, or `dvmctl switch --personal` to clear.")}if(opts.personal){clearActiveOrg();if(opts.human){info("Switched to personal context.")}else{json({activeOrg:null})}return}if(handle2==null){const active=loadActiveOrg();if(opts.human){info(active?`Active org: ${active}`:"Active context: personal")}else{json({activeOrg:active})}return}const creds=resolveAuth();if(!creds){throw new DvmError32("auth_required","Not authenticated.","Set DVMKIT_API_KEY or run `dvmctl auth`.")}const platformUrl=process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev";const membership=await getOrgMembership(platformUrl,creds.token,handle2);saveActiveOrg(membership.handle);if(opts.human){info(`Switched to ${membership.handle} (${membership.role}).`);info("Subsequent `dvmctl` commands read from this org, and deploys create DVMs under it.")}else{json({activeOrg:membership.handle,role:membership.role})}}init_output();import{DvmError as DvmError33}from"@dvmkit/sdk/internal";var MAX_LIMIT2=50;async function tempoLosses(handle2,opts){const limit=resolveLimit2(opts.limit);const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.getTempoCreditLosses({limit}));if(opts.human){if(res.losses.length===0){info("No Tempo-backed credits have been closed for lost collection.");return}for(const loss of res.losses){raw(`${loss.credit_id} ${loss.currency} former=${String(loss.former_balance_micro)} micro settled=${loss.settled_on_chain_native} voucher=${loss.highest_voucher_native} channel=${loss.channel_id}`)}info("These are audit records. The credits expose no drawable or reclaimable balance.");return}json({op:"credit_tempo_losses",handle:handle2,dvmId,slug:handle2,losses:res.losses,loss_count:res.losses.length,display:res.losses.length===0?"No Tempo-backed credits have been closed for lost collection.":`${res.losses.length} Tempo-backed credit loss record(s). These credits are terminal and expose no drawable or reclaimable balance.`,hint:"This is a read-only audit surface; there is no refund, retry, or mark-sent action."})}async function tempoWedged(handle2,opts){const limit=resolveLimit2(opts.limit);const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.getTempoDrains({limit,...opts.after===void 0?{}:{after:opts.after},...opts.includeResolved?{includeResolved:true}:{},...opts.minAgeMs===void 0?{}:{minAgeMs:opts.minAgeMs},...opts.evidence===false?{evidence:false}:{}}));const unresolved=res.drains.filter(d=>d.written_off_at===null);const awaitingClose=unresolved.filter(d=>d.chain?.chain==="unconfirmed");const wedged=unresolved.filter(d=>d.chain?.chain!=="unconfirmed");const repairable=wedged.filter(d=>coversDebit(d));const short=wedged.filter(d=>isShortRefund(d));if(opts.human){if(res.drains.length===0){info("No Tempo closes are stuck between chain and ledger. Nothing to repair.");return}for(const drain of res.drains){raw(`${drain.credit_id} ${drain.drain_id} ${drain.status} ${describeChain(drain)} owed=${drain.amount_native??"-"} native (${String(drain.amount_micro)} ${drain.currency} micro)`+(drain.written_off_at===null?"":` written-off${noteSuffix(drain.write_off_note)}`))}info(`${wedged.length} awaiting a decision, ${repairable.length} whose on-chain refund covers the debit. Finish one with \`dvmctl credit tempo-reconcile ${handle2} <credit-id> <drain-id>\`.`);if(short.length>0){info(`${short.length} refunded the caller less than the ledger extinguished. A reconcile refuses those; \`dvmctl credit tempo-write-off\` is how one is closed.`)}if(awaitingClose.length>0){info(`${awaitingClose.length} more have no confirmed close on chain yet \u2014 those are the caller's to finish, not yours, and are not counted above.`)}if(!opts.includeResolved){info("A written-off close still holds its caller's debited balance, and is not on this page \u2014 `--include-resolved` lists those too.")}if(res.next_after)info(`More rows: re-run with \`--after ${res.next_after}\`.`);return}json({op:"credit_tempo_wedged",handle:handle2,dvmId,slug:handle2,drains:res.drains,wedged_count:wedged.length,repairable_count:repairable.length,short_refund_count:short.length,awaiting_close_count:awaitingClose.length,...res.next_after?{next_after:res.next_after}:{},display:wedged.length===0?awaitingClose.length===0?"No Tempo channel closes are waiting on an operator decision.":`No Tempo close is waiting on an operator decision. ${awaitingClose.length} pending drain(s) have no confirmed close on chain yet, which is the caller's to finish rather than yours.`:`${wedged.length} Tempo close(s) landed on chain without the caller's credit balance being booked as paid. ${repairable.length} paid enough to cover the debit and can be finished.`+(short.length>0?` ${short.length} refunded the caller less than was extinguished \u2014 those cannot be reconciled and need a decision.`:"")+(awaitingClose.length>0?` A further ${awaitingClose.length} pending drain(s) have no confirmed close on chain yet and are not counted here.`:""),hint:"Finish one with `dvmctl credit tempo-reconcile <handle> <credit-id> <drain-id>` \u2014 the amount comes off the close receipt, not from you. If the refund was genuinely short, close it with `dvmctl credit tempo-write-off`."+(opts.includeResolved?"":" Drains you have already written off are not counted here; re-run with `--include-resolved` to see those.")})}async function tempoReconcile(handle2,creditId,drainId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.reconcileTempoDrain({credit_id:creditId,drain_id:drainId}));if(opts.human){info(res.replayed?`Already booked (drain ${res.drain_id} on ${res.credit_id}) \u2014 nothing moved.`:`Booked the ${res.settled_amount??"on-chain"} refund against drain ${res.drain_id} on ${res.credit_id}.`);return}json({op:"credit_tempo_reconcile",handle:handle2,dvmId,slug:handle2,credit_id:res.credit_id,drain_id:res.drain_id,channel_id:res.channel_id,transaction:res.transaction,settled_amount:res.settled_amount,amount_micro:res.amount_micro,amount_native:res.amount_native,currency:res.currency,replayed:res.replayed,display:res.replayed?`This drain was already booked. Nothing moved.`:`Booked drain ${res.drain_id} on ${res.credit_id} against the refund the channel close already paid (${res.transaction??"no transaction recorded"}).`,hint:"The reclaim is reported to the platform on the DVM's own retry loop, so its liability view catches up without another command."})}async function tempoWriteOff(handle2,creditId,drainId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.writeOffTempoDrain({credit_id:creditId,drain_id:drainId,...opts.note===void 0?{}:{note:opts.note}}));if(opts.human){info(res.replayed?`Already written off (drain ${res.drain_id} on ${res.credit_id})${noteSuffix(res.note)}. Nothing changed.`:`Wrote off drain ${res.drain_id} on ${res.credit_id}. Nothing was booked.`);return}json({op:"credit_tempo_write_off",handle:handle2,dvmId,slug:handle2,credit_id:res.credit_id,drain_id:res.drain_id,channel_id:res.channel_id,amount_micro:res.amount_micro,amount_native:res.amount_native,currency:res.currency,note:res.note,replayed:res.replayed,display:res.replayed?`This drain was already written off${res.note?`, with the note "${res.note}"`:""}. Nothing changed, and your note was not recorded over it.`:"Closed this drain without booking it. No ledger row moved: the caller keeps the on-chain refund the close paid them, and the shortfall against what was extinguished is not expressible here \u2014 make it good out of band if you owe it.",hint:"Reversible: `dvmctl credit tempo-reconcile` still accepts a written-off drain if you change your mind."})}function coversDebit(drain){return compareRefund(drain)==="covers"}function isShortRefund(drain){return compareRefund(drain)==="short"}function compareRefund(drain){if(drain.chain?.chain!=="found"||drain.amount_native===null)return"incomparable";try{return BigInt(drain.chain.refundedToPayer)>=BigInt(drain.amount_native)?"covers":"short"}catch{return"incomparable"}}function describeChain(drain){const evidence=drain.chain;if(!evidence)return"chain=not-checked";switch(evidence.chain){case"found":return`chain=refunded:${evidence.refundedToPayer}${isShortRefund(drain)?" (short)":""}`;case"unreported":return"chain=no-receipt";case"unconfirmed":return"chain=no-close";default:return"chain=unreachable"}}function noteSuffix(note){return note?` \u2014 note on record: "${note}"`:""}function resolveLimit2(limit){if(limit===void 0)return 20;if(!Number.isSafeInteger(limit)||limit<1||limit>MAX_LIMIT2){throw new DvmError33("invalid_limit",`--limit must be an integer in 1..${MAX_LIMIT2} (got ${limit}).`,"Leave it unset for the default page of 20, then follow `next_after` for the rest. The ceiling is low because every row on the page may cost a chain read.")}return limit}function renderTrace(trace,opts){const lines=[];const c=opts.color?ansi:noColor;const statusLabel=trace.status==="error"?c.red("ERROR"):c.green("OK");const dimParts=[];for(const key of["builder_id","dvm_id","dvm_slug","rail"]){const val=trace.dimensions[key];if(val!=null)dimParts.push(`${key.replace("_id","")} ${stringify2(val)}`)}lines.push(`trace ${trace.trace_id} duration ${fmtMs(trace.duration_ms)} status ${statusLabel}`+(dimParts.length>0?` ${dimParts.join(" ")}`:""));lines.push("");if(trace.truncated){lines.push(c.yellow("WARNING: trace contains more than 10000 spans; showing first 10000 ordered by start time."));lines.push(c.yellow("This usually means a runaway span emitter (e.g. a tight loop logging)."));lines.push("")}const childrenOf=new Map;for(const span of trace.spans){const key=span.parent_span_id;let list2=childrenOf.get(key);if(!list2){list2=[];childrenOf.set(key,list2)}list2.push(span)}for(const list2 of childrenOf.values()){list2.sort((a,b2)=>a.started_at_ms-b2.started_at_ms)}const flat=[];function walk3(parentId,prefixStack){const children=childrenOf.get(parentId);if(!children)return;for(let i=0;i<children.length;i++){const span=children[i];const isLast=i===children.length-1;const hasChildren=childrenOf.has(span.span_id);let glyph;if(prefixStack.length===0){glyph=hasChildren?"\u2500\u252C\u2500 ":"\u2500\u2500\u2500 "}else{const connector=isLast?"\u2514":"\u251C";const branch=hasChildren?"\u2500\u252C\u2500 ":"\u2500\u2500 ";glyph=connector+branch}const prefix=prefixStack.join("")+glyph;flat.push({span,prefix});const continuation=prefixStack.length===0?"":isLast?" ":"\u2502 ";walk3(span.span_id,[...prefixStack,continuation])}}walk3(null,[]);const rendered=new Set(flat.map(e17=>e17.span.span_id));for(const span of trace.spans){if(!rendered.has(span.span_id)){flat.push({span,prefix:"\u2500\u2500\u2500 "})}}const traceStart=trace.started_at_ms;for(const{span,prefix}of flat){const offset=span.started_at_ms-traceStart;const offsetStr=c.dim(`${String(offset).padStart(5)}ms `);const isLog=span.duration_ms===0;let line;if(isLog){const icon=levelIcon(span.level,c);const attrs=inlineKV(span.dimensions,span.attributes);line=`${offsetStr}${c.dim(prefix)}${icon} ${span.name}${attrs}`}else{const dur=`[${fmtMs(span.duration_ms).padStart(7)}]`;const statusWord=span.status==="error"?c.red("error"):span.status==="ok"?c.green("ok"):"";const attrs=inlineKV(span.dimensions,span.attributes);line=`${offsetStr}${c.dim(prefix)}${span.name}${attrs} ${dur} ${statusWord}`}lines.push(line)}if(Object.keys(trace.dimensions).length>0){lines.push("");lines.push("attributes:");const maxKeyLen=Math.max(...Object.keys(trace.dimensions).map(k2=>k2.length));for(const[k2,v]of Object.entries(trace.dimensions)){lines.push(` ${k2.padEnd(maxKeyLen+2)}${String(v)}`)}}return lines.join("\n")}function fmtMs(ms){if(ms<1e3)return`${ms}ms`;if(ms<6e4)return`${(ms/1e3).toFixed(1)}s`;return`${(ms/6e4).toFixed(1)}m`}function levelIcon(level,c){switch(level){case"error":return c.red("\u2716");case"warn":return c.yellow("\u26A0");default:return c.blue("\u2139")}}function inlineKV(dims,attrs){const headerKeys=new Set(["builder_id","dvm_id","dvm_slug","rail"]);const merged=[];for(const[k2,v]of Object.entries(dims)){if(!headerKeys.has(k2))merged.push([k2,v])}for(const[k2,v]of Object.entries(attrs)){merged.push([k2,v])}if(merged.length===0)return"";const parts=merged.map(([k2,v])=>{const s=stringify2(v);return`${k2}: ${s.length>60?s.slice(0,57)+"...":s}`});return` {${parts.join(", ")}}`}function stringify2(val){if(typeof val==="object"&&val!==null)return JSON.stringify(val);return String(val)}var ansi={red:s=>`\x1B[31m${s}\x1B[0m`,green:s=>`\x1B[32m${s}\x1B[0m`,yellow:s=>`\x1B[33m${s}\x1B[0m`,blue:s=>`\x1B[34m${s}\x1B[0m`,dim:s=>`\x1B[2m${s}\x1B[0m`};var noColor={red:s=>s,green:s=>s,yellow:s=>s,blue:s=>s,dim:s=>s};init_output();async function traceGet(traceId,opts){const{token,platformUrl}=requireAuth();const result=await getBuilderTrace(platformUrl,token,traceId,{org:resolveOrgScope(opts)});if(opts.human){const useColor=opts.color!==false&&process.stdout.isTTY;info(renderTrace(result,{color:useColor}))}else{json(result)}}import{DvmError as DvmError34}from"@dvmkit/sdk/internal";init_output();async function transfer(slug,to,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const body=opts.createOrg?{to:{create:{handle:to,displayName:opts.displayName}}}:{to};const result=await transferDvm(platformUrl,token,dvmId,body);if(result.status==="noop"){throw new DvmError34("noop",`DVM "${slug}" is already in the target destination.`)}if(opts.human){if(result.org){info(`Created org "${result.org.handle}" and transferred ${slug} into it.`)}else{info(`Transferred ${slug} \u2192 ${result.to}`)}if(result.treasuryRekeyPending){info("Warning: Treasury re-key pending \u2014 redeploy the DVM (`dvmctl deploy`) to update the Cashu lock pubkey under the new org.")}}else{json({...result,dvmId,slug})}}init_builder_store();init_output();async function whoami(opts){const{token,platformUrl}=requireAuth();const activeOrg=loadActiveOrg();const identity=readLocalIdentity();const[builder,memberships]=await Promise.all([getAuthenticatedBuilderProfile(platformUrl,token),listBuilderOrgs(platformUrl,token)]);if(opts.human){printHuman2(builder,memberships,activeOrg,identity);return}json({identity_pubkey:identity.pubkey,identity_status:identity.status,...identity.status==="unreadable"?{identity_detail:identity.detail}:{},builder,activeOrg,memberships:memberships.map(membership=>outputMembership2(membership,activeOrg)),display:`Builder ${builder.email??builder.handle??builder.id}. Active context: ${activeOrg??"personal"}.`,hint:identity.status==="missing"?"Run `dvmctl identity create` before a cloud or Connect deploy.":identity.status==="unreadable"?"Repair the local builder configuration before a cloud or Connect deploy.":"Every listed membership can deploy a new DVM. The role shows its existing access level."})}function readLocalIdentity(){try{const pubkey=loadIdentityPubkey();if(pubkey===null)return{status:"missing",pubkey:null};if(!/^[0-9a-f]{64}$/.test(pubkey)){return{status:"unreadable",pubkey:null,detail:"Local builder identity pubkey is not a 64-character hexadecimal key."}}return{status:"available",pubkey}}catch(error51){return{status:"unreadable",pubkey:null,detail:error51 instanceof Error?error51.message:String(error51)}}}function outputMembership2(membership,activeOrg){const active=membership.isPersonal?activeOrg===null:membership.handle===activeOrg;if(membership.isPersonal){return{displayName:membership.displayName,role:membership.role,personal:true,deployable:true,active}}return{handle:membership.handle,displayName:membership.displayName,role:membership.role,personal:false,deployable:true,active}}function printHuman2(builder,memberships,activeOrg,identity){info(`Builder: ${builder.displayName??builder.email??builder.handle??builder.id}`);info(` id: ${builder.id}`);info(` email: ${builder.email??"\u2014"}`);info(` handle: ${builder.handle??"\u2014"}`);info(` identity pubkey: ${identity.pubkey??"\u2014"} (${identity.status})`);if(identity.status==="unreadable")info(` identity detail: ${identity.detail}`);info(`Active context: ${activeOrg??"personal"}`);if(memberships.length===0){info("No org memberships found.");return}const rows=memberships.map(membership=>({handle:membership.isPersonal?"\u2014":membership.handle,name:membership.isPersonal?`${membership.displayName??"Personal context"} (personal)`:membership.displayName??"\u2014",role:membership.role,active:membership.isPersonal?activeOrg===null:membership.handle===activeOrg}));const handleW=Math.max(6,...rows.map(row=>row.handle.length));const nameW=Math.max(4,...rows.map(row=>row.name.length));const roleW=Math.max(4,...rows.map(row=>row.role.length));info("");info(` ${"HANDLE".padEnd(handleW)} ${"NAME".padEnd(nameW)} ${"ROLE".padEnd(roleW)} DEPLOY ACTIVE`);for(const row of rows){info(` ${row.handle.padEnd(handleW)} ${row.name.padEnd(nameW)} ${row.role.padEnd(roleW)} yes ${row.active?"yes":"no"}`)}}init_output();async function x402ExactWedged(handle2,opts){const limit=opts.limit??20;if(!Number.isSafeInteger(limit)||limit<1||limit>50){throw new Error("limit must be an integer in 1..50")}const{client,dvmId}=await connectAdmin(handle2,opts);const response=await adminCall(()=>client.getX402ExactSettlements({limit,...opts.includeResolved?{includeResolved:true}:{}}));if(opts.human){if(response.settlements.length===0){info("No exact x402 payments are waiting for recovery.");return}for(const settlement of response.settlements){raw(`${settlement.settlement_intent_id} ${settlement.status} tx=${settlement.transaction??"unknown"} credit=${settlement.credit_id??"-"} job=${settlement.job_id??"-"}`)}info(`Finish a chain-evidenced payment with \`dvmctl credit x402-exact-reconcile ${handle2} <settlement-intent-id>\`.`);return}json({op:"credit_x402_exact_wedged",handle:handle2,dvmId,slug:handle2,settlements:response.settlements,wedged_count:response.settlements.filter(settlement=>settlement.status!=="complete"&&settlement.status!=="rejected").length,display:response.settlements.length===0?"No exact x402 payments are waiting for recovery.":`${response.settlements.length} exact x402 payment(s) need an operator decision or local finalization.`,hint:"Run `dvmctl credit x402-exact-reconcile <handle> <settlement-intent-id>` only after this queue shows the authorization; the DVM derives the transaction and amount from its own evidence."})}async function x402ExactReconcile(handle2,settlementIntentId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const response=await adminCall(()=>client.reconcileX402ExactSettlement(settlementIntentId));const admissionPending=response.settlement_status==="local_committed";if(opts.human){info(admissionPending?`Recorded settlement ${response.transaction??response.settlement_intent_id}; its original job will be admitted when the caller retries the same request.`:response.replayed?`Settlement ${response.settlement_intent_id} was already recorded locally. Nothing changed.`:`Recorded settlement ${response.transaction??response.settlement_intent_id} against its original local effect.`);return}json({op:"credit_x402_exact_reconcile",handle:handle2,dvmId,slug:handle2,...response,display:admissionPending?`Recorded exact x402 transaction ${response.transaction??"from the DVM's chain evidence"}; its original job is still waiting for admission.`:response.replayed?"This exact x402 payment was already finalized locally. Nothing changed.":`Finalized the original local effect for exact x402 transaction ${response.transaction??"recorded by the DVM"}.`,hint:admissionPending?"Have the caller retry the identical signed request and x402 authorization. The DVM will reuse the settled payment and original job id; do not create a new authorization.":response.job_id?"The caller can retry or query its original request; no new payment authorization is needed.":"The original credit funding is now recorded; the caller can read that credit without paying again."})}init_output();import{DvmError as DvmError35}from"@dvmkit/sdk/internal";var MAX_LIMIT3=50;async function x402Wedged(handle2,opts){const limit=resolveLimit3(opts.limit);const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.getX402Settlements({limit,...opts.after===void 0?{}:{after:opts.after},...opts.includeResolved?{includeResolved:true}:{},...opts.minAgeMs===void 0?{}:{minAgeMs:opts.minAgeMs},...opts.evidence===false?{evidence:false}:{}}));const unresolved=res.settlements.filter(s=>s.status!=="written_off");const repairable=unresolved.filter(s=>s.chain?.chain==="found");const held=res.settlements.filter(s=>s.spending_blocked&&(s.credit_balance_micro??0)>0);if(opts.human){if(res.settlements.length===0){info("No x402 settlements are stuck between chain and ledger. Nothing to repair.");return}for(const settlement of res.settlements){raw(`${settlement.settlement_id} ${settlement.status} ${describeChain2(settlement)} credit=${settlement.credit_id??"-"} drain=${settlement.drain_id??"-"} ${describeHold(settlement)}`)}info(`${unresolved.length} awaiting a decision, ${repairable.length} with a matching refund on chain. Finish one with \`dvmctl credit x402-reconcile ${handle2} <settlement-id>\`.`);if(held.length>0){info(`${held.length} of these hold a caller's balance: it can be reclaimed but not spent until the settlement is closed out.`)}if(!opts.includeResolved){info("A written-off settlement keeps holding its caller's balance for good, and is not on this page \u2014 `--include-resolved` lists those too.")}if(res.next_after)info(`More rows: re-run with \`--after ${res.next_after}\`.`);return}json({op:"credit_x402_wedged",handle:handle2,dvmId,slug:handle2,settlements:res.settlements,wedged_count:unresolved.length,repairable_count:repairable.length,holding_balance_count:held.length,...res.next_after?{next_after:res.next_after}:{},display:unresolved.length===0?"No x402 refunds are waiting on an operator decision.":`${unresolved.length} x402 refund(s) settled on chain without the caller's credit balance being cleared. ${repairable.length} of them have a matching refund the chain can confirm.`+(held.length>0?` ${held.length} are holding a caller's balance, which they can reclaim but not spend until the settlement is closed out.`:""),hint:"Finish one with `dvmctl credit x402-reconcile <handle> <settlement-id>` \u2014 the amount comes off the chain, not from you. If the chain and the ledger disagree, close it with `dvmctl credit x402-write-off`."+(opts.includeResolved?"":" A written-off settlement holds its caller's balance for good and is not counted here; re-run with `--include-resolved` to see those.")})}async function x402Reconcile(handle2,settlementId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.reconcileX402Settlement({settlement_id:settlementId}));if(opts.human){info(res.replayed?`Already booked (drain ${res.drain_id} on ${res.credit_id}) \u2014 nothing moved.`:`Booked the ${res.settled_amount??"on-chain"} refund against drain ${res.drain_id} on ${res.credit_id}.`);return}json({op:"credit_x402_reconcile",handle:handle2,dvmId,slug:handle2,settlement_id:res.settlement_id,channel_id:res.channel_id,credit_id:res.credit_id,drain_id:res.drain_id,transaction:res.transaction,settled_amount:res.settled_amount,amount_micro:res.amount_micro,currency:res.currency,replayed:res.replayed,display:res.replayed?`This settlement was already booked against drain ${res.drain_id}. Nothing moved.`:`Cleared the caller's balance on ${res.credit_id} against the refund the chain already paid (${res.transaction??"no transaction recorded"}).`,hint:"The reclaim is reported to the platform on the DVM's own retry loop, so its liability view catches up without another command."})}async function x402WriteOff(handle2,settlementId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.writeOffX402Settlement({settlement_id:settlementId,...opts.note===void 0?{}:{note:opts.note}}));if(opts.human){info(res.replayed?`Already written off (${res.settlement_id})${res.note?` \u2014 note on record: "${res.note}"`:""}. Nothing changed.`:`Wrote off settlement ${res.settlement_id}. Nothing was booked.`);return}json({op:"credit_x402_write_off",handle:handle2,dvmId,slug:handle2,settlement_id:res.settlement_id,channel_id:res.channel_id,effect_id:res.effect_id,note:res.note,replayed:res.replayed,display:res.replayed?`This settlement was already written off${res.note?`, with the note "${res.note}"`:""}. Nothing changed, and your note was not recorded over it.`:"Closed this settlement without booking it. No ledger row moved: if the refund did reach the chain, the caller still holds the matching credit balance here and can reclaim it with a new drain.",hint:"Reversible: `dvmctl credit x402-reconcile` still accepts a written-off settlement if you change your mind."})}function describeChain2(settlement){const evidence=settlement.chain;if(!evidence)return"chain=not-checked";switch(evidence.chain){case"found":return`chain=paid:${evidence.amount}`;case"absent":return"chain=nothing-found";case"unbookmarked":return"chain=no-bookmark";default:return"chain=unreachable"}}function describeHold(settlement){const balance=settlement.credit_balance_micro;if(balance===null)return"balance=-";const amount2=`${String(balance)}${settlement.credit_currency?` ${settlement.credit_currency}`:""} micro`;return settlement.spending_blocked?`balance=${amount2} (spend-blocked)`:`balance=${amount2}`}function resolveLimit3(limit){if(limit===void 0)return 20;if(!Number.isSafeInteger(limit)||limit<1||limit>MAX_LIMIT3){throw new DvmError35("invalid_limit",`--limit must be an integer in 1..${MAX_LIMIT3} (got ${limit}).`,"Leave it unset for the default page of 20, then follow `next_after` for the rest. The ceiling is low because every row on the page may cost a chain log scan.")}return limit}init_output();import{asProviderText as asProviderText2,DvmError as DvmError36}from"@dvmkit/sdk/internal";init_output();import{formatFiat}from"@dvmkit/sdk";import{formatUsd,fundingRailLabel,shellQuoteArg,x402NetworkByCaip2,x402NetworkLabel}from"@dvmkit/sdk/internal";function takeCreditNoticeFields(){const taken={...pending};pending={};return taken}var pending={};init_output();import{shellQuoteArg as shellQuoteArg2}from"@dvmkit/sdk/internal";function takeFeedbackNoticeFields(){const taken={...pending2};pending2={};return taken}var pending2={};function catchErrors(fn,human){try{const result=fn();if(result instanceof Promise){result.then(()=>process.exit(process.exitCode??0),err=>handleError(err,human))}}catch(err){handleError(err,human)}}function handleError(err,human){if(err instanceof DvmError36){if(human){const dataDisplay=err.data?.display;const display=typeof dataDisplay==="string"?dataDisplay:err.display;const dataNextStep=err.data?.next_step;const nextStep=typeof dataNextStep==="string"?dataNextStep:void 0;info([`Error: ${err.message}`,display,nextStep,err.hint].filter(Boolean).join("\n"))}else{const error51={code:err.code,message:err.message,...err.display?{display:err.display}:{},...err.hint?{hint:err.hint}:{},...err.data??{}};for(const field of["message","display","hint"]){const value=error51[field];if(err.proseSources?.[field]==="provider"&&typeof value==="string"){error51[field]=asProviderText2(value)}}json({error:error51,...takeCreditNoticeFields(),...takeFeedbackNoticeFields()})}process.exit(1)}const diagnostic=unknownErrorDiagnostic(err);const message2=`An unexpected internal error occurred (${diagnostic.label}).`;if(human){info(`Error: ${message2}`)}else{json({error:{code:"internal",message:message2,error_name:diagnostic.name,...diagnostic.code?{error_code:diagnostic.code}:{}},...takeCreditNoticeFields(),...takeFeedbackNoticeFields()})}process.exit(1)}function unknownErrorDiagnostic(err){const name=unknownErrorName(err);const code=unknownErrorCode(err);return{name,...code?{code}:{},label:code?`${name}:${code}`:name}}function unknownErrorName(err){if(!(err instanceof Error))return`thrown_${typeof err}`;try{const prototype=Object.getPrototypeOf(err);const constructor=prototype?.constructor;const name=typeof constructor==="function"?constructor.name:"";return/^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/.test(name)?name:"Error"}catch{return"Error"}}function unknownErrorCode(err){if(typeof err!=="object"&&typeof err!=="function"||err===null)return void 0;try{const code=err.code;return typeof code==="string"&&/^E[A-Z0-9_]{1,31}$/.test(code)?code:void 0}catch{return void 0}}init_http();init_output();function buildProgram(){const program2=new Command;program2.name("dvmctl").description("Builder CLI for creating and deploying DVMs").version(CLI_VERSION);program2.command("create <name>").description("Scaffold a new DVM project").option("--price <price>","Static price (default: $0.01)").option("--name <name>","DVM display name (default: derived from directory)").option("--description <text>","DVM description").action((dir,opts)=>{catchErrors(()=>create(dir,opts))});program2.command("init <handle>").description("Bootstrap a self-hosted DVM: generate a canonical_dvm_id and persist it to ~/.dvmkit/builder.json").option("--self-hosted","Mark the DVM as self-hosted (required \u2014 platform-hosted DVMs get their canonical_dvm_id at deploy time)").option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>{init(handle2,opts)},opts.human)});program2.command("dev <handler>").description("Start a local development server for a DVM handler").option("--port <port>","HTTP port (default: PORT from .env or 3000)").option("--no-reload","Disable hot reload on file changes").action((handler,opts)=>{catchErrors(async()=>{const{dev:dev2}=await Promise.resolve().then(()=>(init_dev(),dev_exports));await dev2(handler,opts)})});program2.command("deploy").description("Deploy a DVM project").option("--target <target>","Deploy target: cloud, self-host, or local").option("--name <slug>","DVM slug for cloud deploy (default: from package.json)").option("--runtime <runtime>","Runtime tier: container or isolate (default: auto-detect)").option("--endpoint-url <url>","Connect-tier upstream URL (required on plans where the platform doesn't host compute)").option("--local","Register a locally-running DVM into the local platform (no Fly), pointing at its localhost URL").option("--url <url>","Localhost URL the DVM is running at, for --local (default http://localhost:<PORT or 3000>)").option("--dry-run","Validate the project (slug, package.json, vmConfig) and build the Dockerfile locally without contacting the platform").option("--yes","Skip the SDK-staleness confirmation prompt and proceed automatically").option("--create-identity","Create the builder signing identity when it is missing (required for noninteractive first deploys)").option("--allow-dirty","Allow a cloud image to include uncommitted packaged files").option("--org <handle>","Deploy under this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>deploy(opts),opts.human)});program2.command("deploy-status <deployId>").description("Show the current status of a deploy by ID (recovery handle for `dvmctl deploy`)").option("--human","Human-readable output instead of JSON").action((deployId,opts)=>{catchErrors(()=>deployStatus(deployId,opts),opts.human)});program2.command("validate").description("Validate the handler and `package.json#dvmkit` locally without contacting the platform").option("--handler <path>","Handler module (default: handler.ts or handler.js)").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>validate4(opts),opts.human)});program2.command("doctor").description("Diagnose builder-side local state").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>builderDoctor(opts),opts.human)});program2.command("serve <handler>").description("Start a production DVM server").option("--port <port>","HTTP port (default: PORT env var or 8080)").option("--dvm <handle>","Serve under the builder-store lock identity for <handle> \u2014 advertises the lock pubkey derived from your recovery mnemonic, so `dvmctl melt-pending <handle>` and `dvmctl rotate <handle>` can sign for this DVM (self-hosted deploys)").action((handler,opts)=>{catchErrors(async()=>{const{builderServe:builderServe2}=await Promise.resolve().then(()=>(init_serve(),serve_exports));await builderServe2(handler,opts)})});program2.command("list").description("List the deployed DVMs in your current org context").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>list(opts),opts.human)});program2.command("info <slug>").description("Show details for a deployed DVM").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>dvmInfo(slug,opts),opts.human)});program2.command("status <slug>").description("Show a deployed DVM's live Fly runtime state (machines, region, image, health)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>status(slug,opts),opts.human)});program2.command("destroy <slug>").description("Destroy a deployed DVM and its paired Postgres cluster").option("--confirm","Skip confirmation prompt (required in non-interactive mode)").option("--keep-db","Preserve the Postgres cluster for re-attachment on redeploy").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>destroy(slug,opts),opts.human)});program2.command("metrics <slug>").description("Show request metrics for a deployed DVM").option("--hours <hours>","Number of hours to look back (default: 24)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>metrics(slug,opts),opts.human)});program2.command("events <slug>").description("Show recent events for a deployed DVM (deploys, restarts, scale, env, machine state)").option("--since <duration>","Look-back window (e.g. 30s, 5m, 2h, 7d; default: 7d)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>events(slug,opts),opts.human)});const feedbackCmd=program2.command("feedback").description("View caller-submitted feedback and toggle collection per DVM");feedbackCmd.command("list <slug>").description("List caller-submitted feedback for one of your DVMs (newest-first)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--since <duration>","Look-back window (e.g. 24h, 7d, ISO 8601)").option("--cursor <c>","Opaque cursor from a prior page's next_cursor").option("--limit <n>","Max rows per page (1-100, default 50)").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>feedbackList(slug,opts),opts.human)});feedbackCmd.command("enable <slug>").description("Enable caller-feedback collection for one of your DVMs").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>feedbackEnable(slug,opts),opts.human)});feedbackCmd.command("disable <slug>").description("Disable caller-feedback collection for one of your DVMs").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>feedbackDisable(slug,opts),opts.human)});const traceCmd=program2.command("trace").description("Inspect request traces for your DVMs");traceCmd.command("get <traceId>").description("Fetch a trace by ID (isolate-dataset spans only)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable trace waterfall instead of JSON").option("--no-color","Disable ANSI colors in human output").action((traceId,opts)=>{catchErrors(()=>traceGet(traceId,opts),opts.human)});program2.command("env <slug>").description("View or update environment variables for a deployed DVM").option("--set <KEY=value...>","Set environment variables (repeatable)").option("--unset <KEY...>","Unset environment variables (repeatable)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>env(slug,opts),opts.human)});program2.command("logs <slug>").description("View or stream logs for a deployed DVM").option("--tail","Stream live logs until interrupted (Ctrl-C)").option("--since <duration>","Only show logs newer than this (e.g. 30s, 5m, 2h, 1d)").option("--lines <count>","Max recent lines to show in non-tail mode (default: 100)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").action((slug,opts)=>{catchErrors(()=>logs(slug,opts))});program2.command("ssh <slug>").description("Open an interactive shell (or run a one-shot --command) on a deployed DVM's Fly machine").option("--command <cmd>","Run a one-shot command instead of opening an interactive shell").option("--machine <id>","Target a specific machine (default: first running machine)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON (one-shot --command only)").action((slug,opts)=>{catchErrors(()=>ssh(slug,opts),opts.human)});program2.command("restart <slug>").description("Restart a deployed DVM's Fly machines without a redeploy").option("--machine <id>","Restart a single machine (default: all running machines)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>restart(slug,opts),opts.human)});program2.command("pause <slug>").description("Take a DVM offline \u2014 stops its machines, keeps its slug, data and database").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>pause(slug,opts),opts.human)});program2.command("resume <slug>").description("Bring a paused or idle DVM back online on the same image (no redeploy)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>resume(slug,opts),opts.human)});const dbCmd=program2.command("db").description("Connect to a DVM's per-DVM database");dbCmd.command("connect <slug>").description("Open an interactive psql session against the DVM's database (requires local psql)").option("--machine <id>","Broker through a specific machine (default: first running machine)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Print connection status to stderr").action((slug,opts)=>{catchErrors(()=>dbConnect(slug,opts),opts.human)});dbCmd.command("proxy <slug>").description("Bind a local port to the DVM's database so any Postgres client can connect (pg_dump, drizzle-kit, GUI clients)").option("--port <n>","Local port to bind (default: an OS-assigned free port)").option("--machine <id>","Broker through a specific machine (default: first running machine)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>dbProxy(slug,opts),opts.human)});program2.command("rollback <slug>").description("Revert a deployed DVM to a previous successful deploy's image").option("--to <deploy-id>","Roll back to a specific deploy_id (default: previous deploy)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>rollback(slug,opts),opts.human)});program2.command("scale <slug>").description("Change a deployed DVM's machine count and/or VM size (no redeploy)").option("--count <n>","Number of machines to run (1-8)").option("--size <vm-size>","Fly VM size, e.g. shared-cpu-1x, shared-cpu-2x, performance-1x").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>scale(slug,opts),opts.human)});program2.command("switch [handle]").description("Set the active org context for reads and deploys. Omit handle to show current; --personal to clear.").option("--personal","Clear org context (read and deploy as personal builder)").option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>switchCmd(handle2,opts),opts.human)});program2.command("orgs").description("List your personal and shared org memberships").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>orgs(opts),opts.human)});program2.command("whoami").description("Show your local identity, builder profile, and org access").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>whoami(opts),opts.human)});program2.command("transfer <slug> <to>").description("Transfer a DVM to an org (by handle) or back to personal").option("--create-org","Create the target org if it doesn't exist (to = desired handle)").option("--display-name <name>","Display name for the new org (with --create-org)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,to,opts)=>{catchErrors(()=>transfer(slug,to,opts),opts.human)});program2.command("auth").description("Authenticate with the dvmkit platform").option("--status","Show current auth status").option("--logout","Remove stored credentials").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>auth(opts),opts.human)});const handleCmd=program2.command("handle").description("Manage your builder handle for *.dvmkit.ai subdomains");handleCmd.command("set").argument("<handle>","Handle to claim (2-20 chars, lowercase, no '--')").option("--human","Human-readable output instead of JSON").action((h,opts)=>{catchErrors(()=>handle(h,opts),opts.human)});handleCmd.command("check").argument("<handle>","Handle to check availability for").option("--human","Human-readable output instead of JSON").action((h,opts)=>{catchErrors(()=>handleCheck(h,opts),opts.human)});const identityCmd=program2.command("identity").description("Manage your builder signing identity (deploy attestations, /v1/info#builder)");identityCmd.command("create").description("Generate a per-workstation secp256k1 identity keypair (tracked change). Persists pubkey to ~/.dvmkit/builder.json and secret to ~/.dvmkit/builder.key (0600).").option("--force","Overwrite an existing identity. Any DVMs deployed under the old key will need re-deploy to refresh their /v1/info attestation.").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>{identityCreate(opts)},opts.human)});identityCmd.command("show").description("Print the builder identity pubkey from ~/.dvmkit/builder.json").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>{identityShow(opts)},opts.human)});const lockCmd=program2.command("lock").description("Manage your builder Cashu P2PK lock keypair (BIP-39 mnemonic)");lockCmd.command("create").description("Generate a BIP-39 mnemonic for builder Cashu lock keypairs").option("--import <mnemonic>","Import an existing 12-word BIP-39 mnemonic").option("--force","Replace an existing mnemonic with a freshly generated one. The old words are copied to a timestamped .bak sibling; proofs locked to lock pubkeys derived from them stop being spendable.").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>{lockCreate(opts)},opts.human)});const domainsCmd=program2.command("domains").description("Manage custom domains for deployed DVMs");domainsCmd.command("add").argument("<slug>","DVM slug").argument("<domain>","Custom domain (e.g. api.example.com)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,domain2,opts)=>{catchErrors(()=>domains("add",slug,{domain:domain2,human:opts.human,org:opts.org}),opts.human)});domainsCmd.command("remove").argument("<slug>","DVM slug").argument("<domain>","Custom domain to remove").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,domain2,opts)=>{catchErrors(()=>domains("remove",slug,{domain:domain2,human:opts.human,org:opts.org}),opts.human)});domainsCmd.command("verify").argument("<slug>","DVM slug").argument("<domain>","Custom domain to verify").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,domain2,opts)=>{catchErrors(()=>domains("verify",slug,{domain:domain2,human:opts.human,org:opts.org}),opts.human)});domainsCmd.command("list").argument("<slug>","DVM slug").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>domains("list",slug,{human:opts.human,org:opts.org}),opts.human)});const secretsCmd=program2.command("secrets").description("Inspect and set secrets for a DVM");secretsCmd.command("list").argument("<slug>","DVM slug").description("List secret names + last-applied timestamps for a DVM. Never returns values; platform-injected keys are excluded.").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>secretsList(slug,opts),opts.human)});const revenueCmd=program2.command("revenue").description("View revenue data across your DVMs");revenueCmd.command("summary").description("Show revenue summary with totals and by-rail breakdown").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").requiredOption("--from <date>","Start date (YYYY-MM-DD)").requiredOption("--to <date>","End date (YYYY-MM-DD)").option("--currency <c>","Reporting currency (gbp, eur, usd, chf)").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>revenueSummary(opts),opts.human)});revenueCmd.command("events").description("List individual revenue events (requires admin role in a shared org)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--from <date>","Start date (YYYY-MM-DD)").option("--to <date>","End date (YYYY-MM-DD)").option("--rail <r>","Filter by payment rail (cashu, lightning, tempo, x402)").option("--limit <n>","Max events to return (default: 50)").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>revenueEvents(opts),opts.human)});revenueCmd.command("csv").description("Export revenue data as CSV (requires admin role in a shared org)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").requiredOption("--from <date>","Start date (YYYY-MM-DD)").requiredOption("--to <date>","End date (YYYY-MM-DD)").option("--currency <c>","Reporting currency (gbp, eur, usd, chf)").option("--rail <r>","Filter by payment rail").option("--out <path>","Write CSV to file instead of stdout").action(opts=>{catchErrors(()=>revenueCsv(opts))});const apiKeysCmd=program2.command("api-keys").description("Manage builder API keys");apiKeysCmd.command("list").description("List your API keys").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>apiKeysList(opts),opts.human)});apiKeysCmd.command("create").description("Create a new API key").option("--label <text>","Label for the key").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>apiKeysCreate(opts),opts.human)});apiKeysCmd.command("revoke <id>").description("Revoke (delete) an API key").option("--human","Human-readable output instead of JSON").action((id,opts)=>{catchErrors(()=>apiKeysRevoke(id,opts),opts.human)});program2.command("rotate <handle>").description("Rotate the per-DVM Cashu lock pubkey \u2014 derives the next BIP-32 child, publishes it to the DVM, demotes the prior pubkey to retired (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; required for self-hosted DVMs)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>rotate(handle2,opts),opts.human)});program2.command("melt-pending <handle>").description("Drain a DVM's pending Cashu accumulator batches \u2014 derives the per-DVM lock privkey locally, melts at the mint, posts mark-melted to the DVM admin endpoint").option("--payout <ln-address>","Lightning address to melt to (overrides any default set via `dvmctl set-payout`)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--watch","Run as a long-lived daemon polling every --interval seconds").option("--interval <seconds>","Poll cadence under --watch (default: 60, range 10\u20133600)",v=>Number(v)).option("--drains-only","Service the credit refunds you owe callers and stop \u2014 never sweep accumulator batches to the payout address. No --payout needed. Use when settling refunds out of band from the scheduled melt").option("--hold-alarm-after <duration>","How long this DVM's drain surface may stay unreadable before a one-shot sweep exits non-zero instead of holding the melt again (default: 24h). Nothing melts and no refund parks while it is held, so this is the ceiling on a silent stall").option("--refund-nwc <uri>","Send-capable NWC connection used to buy a caller's refund when no accumulator batch covers it \u2014 the notes are minted just in time and paid for from this wallet (env: DVMKIT_REFUND_NWC_URL). It only ever pays invoices this command obtained from your own accepted mints").option("--payout-nwc <uri>","Mint the payout invoice from this NWC wallet instead of resolving --payout over LNURL (env: DVMKIT_MELT_PAYOUT_NWC_URL). Use when the melt destination is a node with no Lightning address of its own").option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>meltPending(handle2,opts),opts.human)});program2.command("melt-status [handle]").description("Report when `dvmctl melt-pending` last completed cleanly for each DVM on this machine \u2014 the liveness signal a scheduled melt leaves behind, readable with no platform involved").option("--max-age <duration>","Exit non-zero when a DVM has not swept successfully within this window (e.g. `30h`, `2d`). Cron this and the exit code alarms on a melt job that stopped running at all. Every DVM is watched, and one that has never swept counts as stale").option("--except <handle>","Do not alarm on this DVM under --max-age (repeatable). For a DVM with no Cashu rail, which never melts and would otherwise hold the alarm red forever",(value,previous)=>[...previous,value],[]).option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>{meltStatus(handle2,opts)},opts.human)});const creditCmd=program2.command("credit").description("Reconcile prepaid-credit money your DVM could not apply on its own");creditCmd.command("blocked <handle>").description("List Lightning top-ups your DVM received but could never credit \u2014 the queue behind every `lightning_settlement_blocked` log line (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Page size (default: 50, max 200)",v=>Number(v)).option("--after <cursor>","Continue from a previous run's `next_after` value").option("--include-resolved","Also list rows you already reconciled or wrote off \u2014 the audit view").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>blockedInvoices(handleArg,opts),opts.human)});creditCmd.command("reconcile <handle> <payment-hash>").description("Credit a blocked Lightning payment onto a credit the caller holds. The amount, currency and caller all come off the invoice your DVM recorded; you name only the credit. Idempotent").option("--credit-id <id>","Credit the payment should land on (required)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,paymentHash,opts)=>{catchErrors(()=>reconcileInvoice(handleArg,paymentHash,opts),opts.human)});creditCmd.command("write-off <handle> <payment-hash>").description("Record that you reviewed a blocked Lightning payment and are not crediting it. Moves no money and is reversible \u2014 the row just leaves the queue").option("--note <text>","Why you are not crediting it. Recorded on the invoice row").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,paymentHash,opts)=>{catchErrors(()=>writeOffInvoice(handleArg,paymentHash,opts),opts.human)});creditCmd.command("drains-owed <handle>").description("List the stablecoin refunds your DVM owes callers that nothing will ever pay on its own \u2014 one-payment x402 and Tempo reclaims, the queue behind every `drain_manual_settlement_required` log line (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>drainsOwed(handleArg,opts),opts.human)});creditCmd.command("liability <handles...>").description("Show the satoshis your DVMs owe callers \u2014 undrawn Bitcoin deposits plus reclaims in flight \u2014 and how much of your hub balance is earnings you can sweep. Name every DVM the hub backs (tracked change)").option("--hub-sats <sats>","Your hub's spendable balance, in sats. Supply it to get the sweepable figure directly").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArgs,opts)=>{catchErrors(()=>creditLiability(handleArgs,opts),opts.human)});creditCmd.command("drain-settle <handle> <credit-id> <drain-id>").description("Record that you settled an owed stablecoin refund on chain. Moves no money \u2014 the ledger catches up with a payout you already made, the caller's poll sees it settled, and the reclaim stops counting against your liability. Idempotent").option("--tx <hash>","On-chain transaction that paid the refund (required)").option("--note <text>","Recorded alongside the transaction, e.g. which wallet sent it").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,creditId,drainId,opts)=>{catchErrors(()=>drainSettle(handleArg,creditId,drainId,opts),opts.human)});creditCmd.command("x402-wedged <handle>").description("List x402 cooperative refunds that settled on chain but never cleared the caller's balance, with what the chain says about each (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Page size (default: 20, max 50)",v=>Number(v)).option("--after <cursor>","Continue from a previous run's `next_after` value").option("--include-resolved","Also list settlements you already wrote off \u2014 the audit view").option("--min-age-ms <ms>","How long a settlement must have sat before it counts as stuck (default: 300000)",v=>Number(v)).option("--no-evidence","Skip the per-row chain lookups \u2014 a fast read of the queue itself").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>x402Wedged(handleArg,opts),opts.human)});creditCmd.command("x402-reconcile <handle> <settlement-id>").description("Finish the ledger leg of an x402 refund the chain already paid. The amount is re-derived from chain evidence, never sent from here; a chain/ledger disagreement refuses. Idempotent").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,settlementId,opts)=>{catchErrors(()=>x402Reconcile(handleArg,settlementId,opts),opts.human)});creditCmd.command("x402-write-off <handle> <settlement-id>").description("Record that you reviewed a wedged x402 settlement and are not booking it. Books nothing and is reversible \u2014 the row just leaves the queue").option("--note <text>","Why you are not booking it. Recorded on the settlement row").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,settlementId,opts)=>{catchErrors(()=>x402WriteOff(handleArg,settlementId,opts),opts.human)});creditCmd.command("x402-exact-wedged <handle>").description("List exact x402 authorizations whose chain settlement has not finished its original local credit or job effect").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Rows to return (default: 20, max 50)",v=>Number(v)).option("--include-resolved","Also list completed and rejected intents").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>x402ExactWedged(handleArg,opts),opts.human)});creditCmd.command("x402-exact-reconcile <handle> <settlement-intent-id>").description("Finish the original local effect of a chain-evidenced exact x402 payment. The transaction and amount come from the DVM, never this command").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,settlementIntentId,opts)=>{catchErrors(()=>x402ExactReconcile(handleArg,settlementIntentId,opts),opts.human)});creditCmd.command("tempo-losses <handle>").description("List Tempo-backed credits terminalized after their channel finalized before the DVM collected accepted value").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Rows to return (default: 20, max 50)",v=>Number(v)).option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>tempoLosses(handleArg,opts),opts.human)});creditCmd.command("tempo-wedged <handle>").description("List Tempo cooperative closes that landed on chain but never booked the caller's drain, with what the close receipt says about each (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Page size (default: 20, max 50)",v=>Number(v)).option("--after <cursor>","Continue from a previous run's `next_after` value").option("--include-resolved","Also list drains you already wrote off \u2014 the audit view").option("--min-age-ms <ms>","How long a drain must have sat before it counts as stuck (default: 300000)",v=>Number(v)).option("--no-evidence","Skip the per-row chain lookups \u2014 a fast read of the queue itself").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>tempoWedged(handleArg,opts),opts.human)});creditCmd.command("tempo-reconcile <handle> <credit-id> <drain-id>").description("Book a Tempo drain whose channel close already paid. The amount is re-read from the close receipt, never sent from here; a refund short of the debit refuses. Idempotent").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,creditId,drainId,opts)=>{catchErrors(()=>tempoReconcile(handleArg,creditId,drainId,opts),opts.human)});creditCmd.command("tempo-write-off <handle> <credit-id> <drain-id>").description("Record that you reviewed a wedged Tempo close and are not booking it. Books nothing and is reversible \u2014 the row just leaves the queue").option("--note <text>","Why you are not booking it. Recorded on the drain row").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,creditId,drainId,opts)=>{catchErrors(()=>tempoWriteOff(handleArg,creditId,drainId,opts),opts.human)});program2.command("set-payout <handle> <ln-address>").description("Persist the default Lightning payout address for `dvmctl melt-pending <handle>` (pre-flights the LNURL-pay endpoint)").option("--skip-preflight","Skip the LNURL pre-flight check (use when the provider is temporarily down)").option("--self-hosted","Resolve this handle from local builder.json state instead of asking the platform which DVM it is. Named for the self-hosted case it was built for, but it reaches any entry recorded on this machine \u2014 including one a `dvmctl deploy` wrote, whose payout address it will rewrite").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handle2,lnAddress,opts)=>{catchErrors(()=>setPayout(handle2,lnAddress,opts),opts.human)});return program2}if(process.argv[1]&&realpathSync2(process.argv[1])===fileURLToPath2(import.meta.url)){installGlobalAcceptEncoding();setOutputTraceId(randomTraceId());buildProgram().parse()}export{buildProgram};
|
|
2432
|
+
${e19}}`:`{${i2.join(",")}}`;return r=e19,a2}finally{a.delete(c)}}default:return}};return s({"":e17},"")}function Ke(e17){return e17.trim().replace(/[\t\n\f\r ]+/g,"").replace(/={1,2}$/,"")}function qe(e17){return base643.encode(e17)}function Je(e17){return base64urlnopad.encode(e17)}function Ye(e17){return base64url3.encode(e17)}function Xe(e17){try{return base64urlnopad.decode(Ke(e17))}catch(e18){throw new b("Invalid base64url string",{cause:e18})}}function Ze(e17){try{return base64nopad.decode(Ke(e17))}catch(e18){throw new b("Invalid base64 string",{cause:e18})}}function Qe(e17){try{return Xe(e17)}catch(t2){try{return Ze(e17)}catch{throw t2}}}function et(e17){if(typeof e17!="string"||e17.length===0)return false;let t2=Ke(e17);if(t2.length===0)return false;let n=/[-_]/.test(t2)?base64urlnopad:base64nopad;try{return n.encode(n.decode(t2))===t2}catch{return false}}function st(e17){let t2=[];return ct(e17,t2),new Uint8Array(t2)}function ct(e17,t2){if(e17===null)t2.push(246);else if(e17===void 0)t2.push(247);else if(typeof e17=="boolean")t2.push(e17?245:244);else if(typeof e17=="number")mt(e17,t2);else if(typeof e17=="bigint")ut(e17,t2);else if(typeof e17=="string")gt(e17,t2);else if(Array.isArray(e17))_t(e17,t2);else if(e17 instanceof Uint8Array)ht(e17,t2);else if(typeof e17=="object"&&e17&&!Array.isArray(e17))vt(e17,t2);else throw new b("Unsupported type")}function lt(e17,t2){e17<24?t2.push(e17):e17<256?t2.push(24,e17):e17<65536?t2.push(25,e17>>>8&255,e17&255):e17<4294967296?t2.push(26,e17>>>24&255,e17>>>16&255,e17>>>8&255,e17&255):ut(BigInt(e17),t2)}function ut(e17,t2){e17>=0n?dt(0,e17,t2):dt(1,-1n-e17,t2)}function dt(e17,t2,n){let r=e17<<5;if(t2<24n)n.push(r|Number(t2));else if(t2<256n)n.push(r|24,Number(t2));else if(t2<65536n){let e18=Number(t2);n.push(r|25,e18>>>8&255,e18&255)}else if(t2<4294967296n){let e18=Number(t2);n.push(r|26,e18>>>24&255,e18>>>16&255,e18>>>8&255,e18&255)}else if(t2<18446744073709551616n){let e18=Number(t2>>32n),i=Number(t2&4294967295n);n.push(r|27,e18>>>24&255,e18>>>16&255,e18>>>8&255,e18&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255)}else throw new b("BigInt value out of uint64 range")}function ft(e17,t2){let n=-1-e17;n<24?t2.push(32|n):n<256?t2.push(56,n&255):n<65536?t2.push(57,n>>>8&255,n&255):n<4294967296?t2.push(58,n>>>24&255,n>>>16&255,n>>>8&255,n&255):ut(BigInt(e17),t2)}function pt(e17,t2){let n=new DataView(new ArrayBuffer(8));n.setFloat64(0,e17,false),t2.push(251);for(let e18=0;e18<8;e18++)t2.push(n.getUint8(e18))}function mt(e17,t2){Number.isInteger(e17)?e17>=0?lt(e17,t2):ft(e17,t2):pt(e17,t2)}function ht(e17,t2){let n=e17.length;if(n<24)t2.push(64+n);else if(n<256)t2.push(88,n);else if(n<65536)t2.push(89,n>>8&255,n&255);else if(n<4294967296)t2.push(90,n>>>24&255,n>>>16&255,n>>>8&255,n&255);else throw new b("Byte string too long to encode");for(let n2=0;n2<e17.length;n2++)t2.push(e17[n2])}function gt(e17,t2){let n=new TextEncoder().encode(e17),r=n.length;if(r<24)t2.push(96+r);else if(r<256)t2.push(120,r);else if(r<65536)t2.push(121,r>>>8&255,r&255);else if(r<4294967296)t2.push(122,r>>>24&255,r>>>16&255,r>>>8&255,r&255);else throw new b("String too long to encode");for(let e18=0;e18<n.length;e18++)t2.push(n[e18])}function _t(e17,t2){let n=e17.length;if(n<24)t2.push(128|n);else if(n<256)t2.push(152,n);else if(n<65536)t2.push(153,n>>>8&255,n&255);else throw new b("Unsupported array length");for(let n2 of e17)ct(n2,t2)}function vt(e17,t2){let n=Object.keys(e17),r=n.length;if(r>=4294967296)throw new b("Object has too many keys to encode");r<24?t2.push(160|r):r<256?t2.push(184,r):r<65536?t2.push(185,r>>8&255,r&255):t2.push(186,r>>24&255,r>>16&255,r>>8&255,r&255);for(let r2 of n)gt(r2,t2),ct(e17[r2],t2)}var jt=utf8ToBytes3("Secp256k1_HashToCurve_Cashu_");function Mt(r){let i=sha2565(concatBytes(jt,r)),a=0,o=new Uint8Array(4),s=new DataView(o.buffer),c=2**16;for(let r2=0;r2<c;r2++){s.setUint32(0,a,true);let r3=sha2565(concatBytes(i,o));try{return P(bytesToHex2(concatBytes(new Uint8Array([2]),r3)))}catch{a++}}throw new b("No valid point found")}function Nt(t2){let n=t2.map(e17=>e17.toHex(false)).join("");return sha2565(new TextEncoder().encode(n))}function P(e17){return secp256k1.Point.fromHex(e17)}var Lt=e17=>{let t2,n=e18=>bytesToNumberBE(Qe(e18))%BigInt(2**31-1);if(e17.length===12&&et(e17))t2=n(e17);else if(V(e17))t2=wi(e17)%BigInt(2**31-1);else if(et(e17))t2=n(e17);else throw new b("Invalid keyset id: neither hex nor base64");return t2};function Rt(){return secp256k1.utils.randomSecretKey()}function Vt(e17,t2){let n=Mt(e17);if(t2===void 0)t2=secp256k1.Point.Fn.fromBytes(Rt());else if(t2===0n)throw new b("Blinding factor r must be non-zero");let r=secp256k1.Point.BASE.multiply(t2);return{B_:n.add(r),r:t2,secret:e17}}function Ht(e17,t2,n){return e17.subtract(n.multiply(t2))}function Ut(e17,t2,n,r){let i=Ht(e17.C_,t2,r);return{id:e17.id,secret:n,C:i}}var gn=utf8ToBytes3("Cashu_P2BK_v1");var _n=gn.slice();function vn(e17,n,r=true){let i=+!r,a=e17.length+i;if(a>11)throw new b(`Too many pubkeys, ${a} slots provided, maximum allowed is 11 in total`);if(!e17.length)return{blinded:[],Ehex:""};n=n??secp256k1.utils.randomSecretKey();let o=secp256k1.Point.Fn.fromBytes(n),s=secp256k1.getPublicKey(n,true);return{blinded:e17.map((e18,t2)=>{let n2=P(e18),r2=xn(n2,o,t2+i),a2=n2.add(secp256k1.Point.BASE.multiply(r2));if(a2.equals(secp256k1.Point.ZERO))throw new b("Blinded key at infinity");return a2.toHex(true)}),Ehex:bytesToHex2(s)}}function xn(t2,r,i){if(!Number.isInteger(i)||i<0||i>255)throw new b("P2BK: slot index must be an integer in [0, 255]");let a=t2.multiply(r).toBytes(true).slice(1),o=new Uint8Array([i&255]),s=bytesToNumberBE(sha2565(concatBytes(gn,a,o)));if((s===0n||s>=secp256k1.Point.CURVE().n)&&(s=bytesToNumberBE(sha2565(concatBytes(gn,a,o,new Uint8Array([255])))),s===0n||s>=secp256k1.Point.CURVE().n))throw new b("P2BK: tweak derivation failed");return s}var Sn={SIG_INPUTS:"SIG_INPUTS",SIG_ALL:"SIG_ALL"};var Cn=new Set(Object.values(Sn));function Dn(e17){let t2=e17.toLowerCase();if(t2.length===66&&(t2.startsWith("02")||t2.startsWith("03")))return t2;if(t2.length===64)return`02${t2}`;throw new b(`Invalid pubkey, expected 33 byte compressed or 32 byte x only, got length ${t2.length}`)}function L(e17){let t2=new Set,n=[];for(let r of e17){let e18=Dn(r),i=e18.slice(-64);t2.has(i)||(t2.add(i),n.push(e18))}return n}function On(e17){let t2=L(Array.isArray(e17.pubkey)?e17.pubkey:[e17.pubkey]),n=L(e17.refundKeys??[]),r=typeof e17.hashlock=="string"&&e17.hashlock.length>0;if(t2.length===0&&!r)throw new b("P2PK requires at least one pubkey");let i=+!!r+t2.length+n.length;if(i>11)throw new b(`Too many pubkeys, ${i} slots provided, maximum allowed is 11 in total`);e17.sigFlag!==void 0&&Wn(e17.sigFlag);let a=t2.length>0?e17.requiredSignatures??1:e17.requiredSignatures,o=e17.requiredRefundSignatures;return Kn({mainKeyCount:t2.length,refundKeyCount:n.length,nSigs:a,nSigsRefund:o,hasLocktime:e17.locktime!==void 0}),{pubkey:t2.length===1?t2[0]:t2,...e17.locktime===void 0?{}:{locktime:e17.locktime},...n.length>0?{refundKeys:n}:{},...a!==void 0&&a>1?{requiredSignatures:a}:{},...o!==void 0&&o>1?{requiredRefundSignatures:o}:{},...e17.additionalTags?.length?{additionalTags:e17.additionalTags}:{},...e17.blindKeys?{blindKeys:true}:{},...e17.sigFlag===void 0?{}:{sigFlag:e17.sigFlag},...e17.hashlock?{hashlock:e17.hashlock}:{}}}function Wn(e17){if(!Cn.has(e17))throw new b(`Invalid sigflag "${e17}": must be "SIG_INPUTS" or "SIG_ALL"`)}function Gn(e17,t2){if(!Number.isInteger(e17)||e17<1)throw new b(`${t2} must be a positive integer, got ${e17}`);return e17}function Kn(e17){let{mainKeyCount:t2,refundKeyCount:n,nSigs:r,nSigsRefund:i,hasLocktime:a}=e17;if(r!==void 0&&(Gn(r,"requiredSignatures (n_sigs)"),r>t2))throw new b(`requiredSignatures (n_sigs) (${r}) exceeds available pubkeys (${t2})`);if(i!==void 0){if(Gn(i,"requiredRefundSignatures (n_sigs_refund)"),n===0)throw new b("requiredRefundSignatures (n_sigs_refund) requires refund keys");if(i>n)throw new b(`requiredRefundSignatures (n_sigs_refund) (${i}) exceeds available refund keys (${n})`)}if(n>0&&!a)throw new b("refund keys require a locktime")}var $n=utf8ToBytes3("Cashu_DLEQ_R_v1");var tr=(e17,t2,n,r)=>{let i=secp256k1.Point.Fn.fromBytes(e17.s),a=secp256k1.Point.Fn.fromBytes(e17.e),o=secp256k1.Point.BASE.multiply(i),s=r.multiply(a),c=t2.multiply(i),l=n.multiply(a);return equalBytes2(Nt([o.subtract(s),c.subtract(l),r,n]),e17.e)};var nr=(e17,t2,n,r)=>{if(t2.r===void 0)throw new b("verifyDLEQProof_reblind: Undefined blinding factor");let i=Mt(e17),a=n.add(r.multiply(t2.r)),o=secp256k1.Point.BASE.multiply(t2.r);return tr(t2,i.add(o),a,r)};var ir="m/129372'/0'";var ar=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");var or=(function(e17){return e17[e17.SECRET=0]="SECRET",e17[e17.BLINDING_FACTOR=1]="BLINDING_FACTOR",e17})(or||{});var sr=(function(e17){return e17[e17.DEPRECATED_BIP32=0]="DEPRECATED_BIP32",e17[e17.HMAC_SHA256=1]="HMAC_SHA256",e17})(sr||{});function ur(e17,t2,n){return dr(e17,t2)(n)}function dr(e17,t2){switch(pr(e17),fr(t2)){case sr.DEPRECATED_BIP32:{let n=Lt(t2),r=HDKey.fromMasterSeed(e17).derive(`${ir}/${n}'`);return e18=>mr(r,e18)}case sr.HMAC_SHA256:return n=>hr(e17,t2,n)}}function fr(e17){if(e17.length===12&&et(e17))return sr.DEPRECATED_BIP32;let t2=/^[a-fA-F0-9]+$/.test(e17),n=e17.startsWith("01");if(t2&&n&&e17.length%2!=0)throw new b("Invalid hex string: odd length.");if(!t2&&et(e17)||t2&&e17.startsWith("00"))return sr.DEPRECATED_BIP32;if(t2&&n)return sr.HMAC_SHA256;throw new b(`Unrecognized keyset ID version ${e17.slice(0,2)}`)}function pr(e17){if(!(e17 instanceof Uint8Array)||e17.length<16||e17.length>64)throw new b("seed must be a 16 to 64 byte Uint8Array")}function mr(e17,t2){if(!Number.isInteger(t2)||t2<0||t2>=2147483648)throw new b("Counter must be an integer in the range 0 <= counter < 2^31");let n=e17.deriveChild(HARDENED_OFFSET+t2),r=n.deriveChild(0).privateKey,i=n.deriveChild(1).privateKey;if(r===null||i===null)throw new b("Could not derive private key");return{secret:r,blindingFactor:i}}function hr(e17,t2,n){if(!Number.isSafeInteger(n)||n<0)throw new b("Counter must be an integer in the range 0 <= counter <= 2^53 - 1");return{secret:gr(e17,t2,n,or.SECRET),blindingFactor:gr(e17,t2,n,or.BLINDING_FACTOR)}}function gr(t2,i,o,s){let c=concatBytes(utf8ToBytes3("Cashu_KDF_HMAC_SHA256"),hexToBytes2(i),numberToBytesBE(o,8));switch(s){case or.SECRET:c=concatBytes(c,hexToBytes2("00"));break;case or.BLINDING_FACTOR:c=concatBytes(c,hexToBytes2("01"))}let l=hmac2(sha2565,t2,c);if(s===or.BLINDING_FACTOR){let e17=bytesToNumberBE(l),t3=e17>=ar?e17-ar:e17;if(t3===0n)throw new b("Derived invalid blinding scalar r == 0");return numberToBytesBE(t3,32)}return l}var wr=utf8ToBytes3("Cashu_MintQuoteSig_v1");function B(e17,t2,n,r){let i=Ci(e17,"splitAmount.value",true),a=n?.map(e18=>Ci(e18,"splitAmount.split",true));if(a){if(a.length>8192)throw new b(`Cannot split amount: split would exceed ${ae} outputs`);let e18=A.sum(a);if(i.isZero()&&e18.isZero())return a;let n2=a.filter(e19=>!e19.isZero()),r2=A.sum(n2);if(r2.greaterThan(i))throw new b(`Split is greater than total amount: ${r2.toString()} > ${i.toString()}`);if(n2.some(e19=>!Si(e19,t2)))throw new b("Provided amount preferences do not match the amounts of the mint keyset.");if(r2.equals(i))return n2;a=n2,i=i.subtract(r2)}else a=[];let o=xi(t2,"desc");if(o.length===0)throw new b("Cannot split amount, keyset is inactive or contains no keys");for(let e18 of o){if(e18.isZero())continue;let t3=i.divideBy(e18),n2=ae-a.length;if(n2<=0||t3.greaterThan(n2))throw new b(`Cannot split amount: fill would exceed ${ae} outputs`);let r2=t3.toNumber();for(let t4=0;t4<r2;t4++)a.push(e18);if(i=i.subtract(e18.multiplyBy(t3)),i.isZero())break}if(!i.isZero())throw new b(`Unable to split remaining amount: ${i.toString()}`);return r&&(a=a.sort((e18,t3)=>r==="desc"?t3.compareTo(e18):e18.compareTo(t3))),a}function xi(e17,t2){let n=Object.keys(e17).map(e18=>A.from(e18));return n.sort((e18,n2)=>t2==="desc"?n2.compareTo(e18):e18.compareTo(n2)),n}function Si(e17,t2){let n=Ci(e17,"hasCorrespondingKey.amount",true).toString();return Object.prototype.hasOwnProperty.call(t2,n)}function Ci(e17,t2,n=false){let r=A.from(e17);if(!n&&r.isZero())throw new b(`Amount must be positive: ${r.toString()}, op: ${t2}`);return r}function wi(e17){return e17?BigInt(`0x${e17}`):0n}function Ti(e17){return e17.toString(16).padStart(64,"0")}function V(e17){return typeof e17=="string"&&e17.length%2==0&&/^[a-f0-9]+$/i.test(e17)}function Ei(e17){return Array.isArray(e17)?e17.some(e18=>!V(e18.id)):!V(e17.id)}function Oi(e17){return e17.map(e18=>{let t2={...e18};return t2.id=t2.id.slice(0,16),t2})}function ki(e17,t2){let n=q(e17.proofs);if(Ei(n))throw new b("Proofs contain a legacy keyset ID and cannot be encoded. Swap them at the mint first.");return Ai({...e17,proofs:n},t2?.removeDleq)}function Ai(e17,t2){let n=e17.proofs;if(t2&&(n=Ki(n)),Ei(n))throw new b("can not encode to v4 token if proofs contain non-hex keyset id");return n=Oi(n),"cashuB"+Je(st(Mi({...e17,proofs:n})))}function ji(e17){if(e17.r==null)throw new b("Missing blinding factor in included DLEQ proof");return{e:hexToBytes2(e17.e),s:hexToBytes2(e17.s),r:hexToBytes2(e17.r)}}function Mi(e17){let t2=Object.create(null),n=e17.mint;for(let n2=0;n2<e17.proofs.length;n2++){let r=e17.proofs[n2];t2[r.id]?t2[r.id].push(r):t2[r.id]=[r]}let i={m:n,u:e17.unit||"sat",t:Object.keys(t2).map(e18=>({i:hexToBytes2(e18),p:t2[e18].map(e19=>({a:e19.amount.toBigInt(),s:e19.secret,c:hexToBytes2(e19.C),...e19.dleq&&{d:ji(e19.dleq)},...e19.p2pk_e&&{pe:hexToBytes2(e19.p2pk_e)},...e19.witness&&{w:JSON.stringify(e19.witness)}}))}))};return e17.memo&&(i.d=e17.memo),i}function zi(n,i){for(let e17 of Object.keys(n))if(e17.length>20)throw new b("Invalid keyset denomination: exceeds 20 digits");let o=i?.unit??"sat",s=i?.expiry,c=i?.versionByte??1,l=i?.input_fee_ppk;if(i?.isDeprecatedBase64??false)return qe(sha2565(utf8ToBytes3(Object.entries(n).sort(([e17],[t2])=>A.from(e17).compareTo(t2)).map(([,e17])=>e17).reduce((e17,t2)=>e17+t2,"")))).slice(0,12);switch(c){case 0:return"00"+bytesToHex2(sha2565(Bi(...Object.entries(n).sort(([e17],[t2])=>A.from(e17).compareTo(t2)).map(([,e17])=>hexToBytes2(e17))))).slice(0,14);case 1:{if(!o)throw new b("Cannot compute keyset ID version 01: unit is required.");let r=Object.entries(n).sort(([e17],[t2])=>A.from(e17).compareTo(t2)).map(([e17,t2])=>`${e17}:${t2}`).join(",");return r+=`|unit:${o}`,l&&(r+=`|input_fee_ppk:${l}`),s&&(r+=`|final_expiry:${s}`),"01"+bytesToHex2(sha2565(utf8ToBytes3(r)))}default:throw new b(`Unrecognized keyset ID version: ${c}`)}}function Bi(...e17){let t2=e17.reduce((e18,t3)=>e18+t3.length,0),n=new Uint8Array(t2),r=0;for(let t3 of e17)n.set(t3,r),r+=t3.length;return n}function H(e17){return typeof e17=="object"&&!!e17}function U(e17){return H(e17)&&!Array.isArray(e17)}function W(e17,...t2){for(let n of t2)e17[n]===void 0&&(e17[n]=null)}function G(...e17){return e17.map(e18=>e18.replace(/(^\/+|\/+$)/g,"")).join("/")}function Hi(e17){let t2;try{t2=new URL(e17)}catch(t3){throw new b(`Invalid mint URL: ${e17}`,{cause:t3})}if(t2.protocol!=="http:"&&t2.protocol!=="https:")throw new b(`Invalid mint URL scheme: ${t2.protocol}`);if(t2.username||t2.password)throw new b("Mint URL must not contain credentials");if(t2.search||t2.href.includes("?"))throw new b("Mint URL must not contain query parameters");if(t2.hash||t2.href.includes("#"))throw new b("Mint URL must not contain a fragment");if(/%[0-9a-f]{2}/i.test(t2.pathname))throw new b("Mint URL path must not contain percent-encoded characters");return t2.href.replace(/\/+$/,"")}function q(e17){return e17.map(e18=>({...e18,amount:A.from(e18.amount)}))}function Ki(e17){return e17.map(e18=>{let{dleq:t2,...n}=e18;return n})}function Ji(e17,t2,n){let i=n?.require??true;if(!Si(e17.amount,t2.keys))throw new b(Object.keys(t2.keys).length===0?`No keys loaded for keyset ${t2.id}`:`Undefined key for amount ${e17.amount.toString()} in keyset ${t2.id}`);if(e17?.dleq==null)return!i;if(e17.dleq.r==null)return false;let a=t2.keys[e17.amount.toString()];try{let t3={e:hexToBytes2(e17.dleq.e),s:hexToBytes2(e17.dleq.s),r:wi(e17.dleq.r)};return nr(new TextEncoder().encode(e17.secret),t3,P(e17.C),P(a))}catch{return false}}function J(e17,t2,n){if(e17==null){if(arguments.length>=3)return n;throw new b(`Invalid ${t2}: missing value`)}try{return A.from(e17).toNumber()}catch(e18){throw new b(`Invalid ${t2}: ${e18 instanceof Error?e18.message:String(e18)}`,{cause:e18})}}function ra(e17){return{...e17,input_fee_ppk:J(e17.input_fee_ppk,"keyset.input_fee_ppk",void 0),final_expiry:J(e17.final_expiry,"keyset.final_expiry",void 0)}}function ia(e17){return{...e17,input_fee_ppk:J(e17.input_fee_ppk,"keys.input_fee_ppk",void 0),final_expiry:J(e17.final_expiry,"keys.final_expiry",void 0)}}function aa(e17,t2){let n;try{n=new URL(e17).protocol}catch{throw new b(`OIDCAuth: ${t2} is not a valid URL`)}if(n!=="https:"&&n!=="http:")throw new b(`OIDCAuth: ${t2} must be an http(s) URL`)}var oa=class t{static fromMintInfo(e17,n){let r=e17?.nuts?.["21"];if(!r?.openid_discovery)throw new b("OIDCAuth: mint does not advertise NUT-21 openid_discovery");let i=n?.clientId??r.client_id??"cashu-client";return new t(r.openid_discovery,{...n,clientId:i})}constructor(e17,t2){this.tokenListeners=[],this.inflightRefreshes=new Map,this.discoveryUrl=e17,this.logger=t2?.logger??E,this.clientId=t2?.clientId??"cashu-client",this.scope=t2?.scope??"openid",this.onTokens=t2?.onTokens}setClient(e17){this.clientId=e17}setScope(e17){this.scope=e17??"openid"}addTokenListener(e17){this.tokenListeners=[...this.tokenListeners,e17]}removeTokenListener(e17){this.tokenListeners=this.tokenListeners.filter(t2=>t2!==e17)}async loadConfig(){if(this.config)return this.config;let e17=await fetch(this.discoveryUrl,{method:"GET",headers:{Accept:"application/json"}}),t2=await e17.text(),n,r;try{n=t2?JSON.parse(t2):void 0}catch(e18){r=e18,this.logger.warn("OIDCAuth: bad discovery JSON",{err:e18})}if(!e17.ok||!n)throw new b("OIDCAuth: invalid discovery document",{cause:r});let i=n;if(typeof i.token_endpoint!="string"||i.token_endpoint.length===0)throw new b("OIDCAuth: invalid discovery document, missing token_endpoint");return this.config=i,i}generatePKCE(){let t2=Je(randomBytes3(48));return{verifier:t2,challenge:Je(sha2565(utf8ToBytes3(t2)))}}async buildAuthCodeUrl(e17){let t2=await this.loadConfig(),n=e17.scope??this.scope,r=e17.codeChallengeMethod;r!==void 0&&r!=="S256"&&this.logger.warn(`OIDCAuth: codeChallengeMethod '${typeof r=="string"?r:typeof r}' is not supported by cashu-ts v5, which accepts S256 only.`);let i=new URLSearchParams({response_type:"code",client_id:this.clientId,redirect_uri:e17.redirectUri,scope:n,code_challenge_method:e17.codeChallengeMethod??"S256",code_challenge:e17.codeChallenge});if(e17.state&&i.set("state",e17.state),!t2.authorization_endpoint)throw new b("OIDCAuth: discovery lacks authorization_endpoint");return aa(t2.authorization_endpoint,"authorization_endpoint"),`${t2.authorization_endpoint}?${i.toString()}`}async exchangeAuthCode(e17){let t2=await this.loadConfig(),n=this.toForm({grant_type:"authorization_code",code:e17.code,redirect_uri:e17.redirectUri,client_id:this.clientId,code_verifier:e17.codeVerifier}),r=await this.postFormStrict(t2.token_endpoint,n);return this.handleTokens(r,"signin"),r}async deviceStart(){let e17=(await this.loadConfig()).device_authorization_endpoint;if(!e17)throw new b("OIDCAuth: provider lacks device_authorization_endpoint");let t2=this.toForm({client_id:this.clientId,scope:this.scope}),n=await this.postFormStrict(e17,t2);return aa(n.verification_uri,"verification_uri"),n.verification_uri_complete!==void 0&&aa(n.verification_uri_complete,"verification_uri_complete"),n}async devicePoll(e17,t2=5){let n=await this.loadConfig(),r=Number(t2),i=Number.isFinite(r)?Math.max(1,r):5;for(;;){await this.sleep(i*1e3);let t3=this.toForm({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e17,client_id:this.clientId}),r2=await this.postFormLoose(n.token_endpoint,t3);if(r2.access_token)return this.handleTokens(r2,"signin",this.tokenListeners),r2;let a=(r2.error??"").toString();if(a!=="authorization_pending"){if(a==="slow_down"){i=Math.max(i+5,i*2);continue}throw new b(`OIDCAuth: ${r2.error_description||a||"device authorization failed"}`)}}}async startDeviceAuth(e17=5){let t2=await this.deviceStart(),n=Number(t2.interval),r=Number.isFinite(n)&&n>0?n:1,i=Number(e17),a=Math.max(r,Number.isFinite(i)?i:5),o=new AbortController,s,c=new Promise(e18=>{s=e18}),l=new Set,u=()=>{if(o.signal.aborted)throw new b("OIDCAuth: device polling cancelled")},d=async()=>{let e18=await this.loadConfig(),n2=Math.max(1,a);for(;;){u();let r2;await this.sleep(n2*1e3,e19=>{r2=e19,l.add(e19)}),l.delete(r2),u();let i2=this.toForm({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:t2.device_code,client_id:this.clientId}),a2=await this.postFormLoose(e18.token_endpoint,i2,o.signal);if(u(),a2.access_token)return this.handleTokens(a2,"signin"),a2;let s2=(a2.error??"").toString();if(s2!=="authorization_pending"){if(s2==="slow_down"){n2=Math.max(n2+5,n2*2);continue}throw new b(`OIDCAuth: ${a2.error_description||s2||"device authorization failed"}`)}}},f=()=>{o.abort(),s();for(let e18 of l)e18();l.clear()};return{...t2,poll:()=>Promise.race([d(),c.then(()=>{throw new b("OIDCAuth: device polling cancelled")})]),cancel:f}}async refresh(e17){let t2=this.clientId,n=this.tokenListeners,r=this.inflightRefreshes.get(e17);if(r?.listeners===n&&r.clientId===t2)return r.promise;let i=(async()=>{let r2=await this.loadConfig(),i2=this.toForm({grant_type:"refresh_token",refresh_token:e17,client_id:t2}),a=await this.postFormStrict(r2.token_endpoint,i2);return a.refresh_token||(a.refresh_token=e17),this.handleTokens(a,"refresh",n),a})();this.inflightRefreshes.set(e17,{clientId:t2,listeners:n,promise:i});try{return await i}finally{this.inflightRefreshes.get(e17)?.promise===i&&this.inflightRefreshes.delete(e17)}}async passwordGrant(e17,t2){let n=await this.loadConfig(),r=this.toForm({grant_type:"password",client_id:this.clientId,username:e17,password:t2,scope:this.scope}),i=await this.postFormStrict(n.token_endpoint,r);return this.handleTokens(i,"signin"),i}handleTokens(e17,t2,n=this.tokenListeners){if(!e17.access_token)throw new b(`OIDCAuth: ${e17.error_description||e17.error||"token response missing access_token"}`);queueMicrotask(()=>O(e18=>this.onTokens?.(e18,t2),e17,this.logger,{where:"OIDCAuth.handleTokens"}));let r=new Set(this.tokenListeners);for(let i of n)r.has(i)&&queueMicrotask(()=>O(e18=>i(e18,t2),e17,this.logger,{where:"OIDCAuth.handleTokens.listener"}))}toForm(e17){let t2=e18=>encodeURIComponent(e18).replace(/%20/g,"+");return Object.entries(e17).map(([e18,n])=>`${t2(e18)}=${t2(n)}`).join("&")}async postFormStrict(e17,t2){try{let n=await fetch(e17,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t2,redirect:"error"}),r=await n.text(),i,a;try{i=r?JSON.parse(r):void 0}catch(e18){a=e18,this.logger.warn("OIDCAuth: bad JSON (strict)",{err:e18})}if(!n.ok){let e18=i??{};throw new b(`OIDCAuth: ${e18.error_description||e18.error||`HTTP ${n.status}`}`,{cause:a})}return this.logger.debug("OIDCAuth Response",{status:n.status}),i??{}}catch(e18){throw this.logger.error("OIDCAuth: postFormStrict failed",{err:e18}),e18}}async postFormLoose(e17,t2,n){try{let r=await fetch(e17,{method:"POST",signal:n,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:t2,redirect:"error"}),i=await r.text(),a;try{a=i?JSON.parse(i):void 0}catch(e18){this.logger.warn("OIDCAuth: bad JSON (loose)",{err:e18})}return this.logger.debug("OIDCAuth Response",{status:r.status}),a??{}}catch(e18){return this.logger.error("OIDCAuth: postFormLoose network error",{err:e18}),{error:"network_error",error_description:String(e18)}}}sleep(e17,t2){let n=Math.min(e17,ue);return new Promise(e18=>{let r=setTimeout(e18,n);t2?.(()=>{clearTimeout(r),e18()})})}};var Y=class e10{constructor(t2,n){let r=n??E;this._mintInfo=e10.normalizeInfo(t2,r),this._maxArrayLength=e10.resolveMaxArrayLength(t2.max_array_length,r);let i=this.toEndpoints(this._mintInfo?.nuts?.[22]?.protected_endpoints,r);this._protected22=this.buildIndex(i);let a=this.toEndpoints(this._mintInfo?.nuts?.[21]?.protected_endpoints,r);this._protected21=this.buildIndex(a)}static normalizeInfo(t2,n=E){if(!U(t2)||!U(t2.nuts))throw n.error("MintInfo: malformed info response",{op:"normalizeInfo"}),new b("Invalid response from mint");return{...t2,...Array.isArray(t2.contact)?{contact:e10.capList(t2.contact,"contact",n)}:{},...Array.isArray(t2.urls)?{urls:e10.capList(t2.urls,"urls",n)}:{},nuts:{...t2.nuts,...t2.nuts[4]?{4:e10.normalizeSwapSection(t2.nuts[4],"nuts.4",n)}:{},...t2.nuts[5]?{5:e10.normalizeSwapSection(t2.nuts[5],"nuts.5",n)}:{},...t2.nuts[15]?{15:e10.normalizeNut15(t2.nuts[15],n)}:{},...t2.nuts[17]?{17:e10.normalizeNut17(t2.nuts[17],n)}:{},...t2.nuts[19]?{19:e10.normalizeNut19(t2.nuts[19],n)}:{},...t2.nuts[21]?{21:e10.normalizeNut21(t2.nuts[21],n)}:{},...t2.nuts[22]?{22:e10.normalizeNut22(t2.nuts[22],n)}:{},...t2.nuts[29]?{29:e10.normalizeNut29(t2.nuts[29],n)}:{}}}}static dropSection(e17,t2){t2.warn(`MintInfo: ${e17} is malformed and was omitted`)}static normalizeSwapSection(t2,n,r){if(!U(t2))throw r.error("MintInfo: malformed info response",{op:n}),new b("Invalid response from mint");return{...t2,methods:e10.normalizeSwapMethods(t2.methods,r)}}static normalizeSwapMethods(t2,n){return Array.isArray(t2)?e10.capList(t2,"nuts.4/5.methods",n).filter(e17=>U(e17)).map(e17=>{let t3={...e17};return W(t3,"min_amount","max_amount"),t3}):(n.warn("MintInfo: nuts.4/5.methods is malformed and was omitted"),[])}static resolveMaxArrayLength(e17,t2){if(e17==null)return 500;let n;try{n=J(e17,"max_array_length")}catch{return t2.warn("MintInfo: max_array_length is malformed, defaulting to internal default",{value:e17}),500}if(n<1||n>1e4){let e18=Math.min(Math.max(n,1),oe);return t2.warn("MintInfo: max_array_length is out of range and was clamped",{advertised:n,clampedTo:e18}),e18}return n}static normalizeNut15(t2,n){return U(t2)?Array.isArray(t2.methods)?{...t2,methods:e10.capList(t2.methods,"nuts.15.methods",n)}:t2:e10.dropSection("nuts.15",n)}static normalizeNut17(t2,n){return U(t2)?Array.isArray(t2.supported)?{...t2,supported:e10.capList(t2.supported,"nuts.17.supported",n)}:t2:e10.dropSection("nuts.17",n)}static normalizeNut19(t2,n){return U(t2)?{...t2,...Array.isArray(t2.cached_endpoints)?{cached_endpoints:e10.capList(t2.cached_endpoints,"nuts.19.cached_endpoints",n)}:{},ttl:J(t2.ttl,"nuts.19.ttl",null)}:e10.dropSection("nuts.19",n)}static normalizeNut21(t2,n){return U(t2)?Array.isArray(t2.protected_endpoints)?{...t2,protected_endpoints:e10.capList(t2.protected_endpoints,"nuts.21.protected_endpoints",n)}:t2:e10.dropSection("nuts.21",n)}static normalizeNut22(t2,n){if(!U(t2))return e10.dropSection("nuts.22",n);let r=100;try{r=J(t2.bat_max_mint,"nuts.22.bat_max_mint",100)}catch{n.warn("MintInfo: nuts.22.bat_max_mint is malformed, defaulting to internal cap",{value:t2.bat_max_mint})}return r>100&&(n.warn("MintInfo: nuts.22.bat_max_mint exceeds internal cap and was clamped",{advertised:r,clampedTo:100}),r=100),{...t2,...Array.isArray(t2.protected_endpoints)?{protected_endpoints:e10.capList(t2.protected_endpoints,"nuts.22.protected_endpoints",n)}:{},bat_max_mint:r}}static normalizeNut29(t2,n){if(!U(t2))return e10.dropSection("nuts.29",n);let r=100;try{r=J(t2.max_batch_size,"nuts.29.max_batch_size",100)}catch{n.warn("MintInfo: nuts.29.max_batch_size is malformed, defaulting to internal cap",{value:t2.max_batch_size})}return r>100&&(n.warn("MintInfo: nuts.29.max_batch_size exceeds internal cap and was clamped",{advertised:r,clampedTo:100}),r=100),{methods:Array.isArray(t2.methods)?e10.capList(t2.methods,"nuts.29.methods",n):t2.methods,max_batch_size:r}}isSupported(e17){switch(e17){case 4:case 5:return this.checkMintMelt(e17);case 7:case 8:case 9:case 10:case 11:case 12:case 14:case 20:return this.checkGenericNut(e17);case 17:return this.checkNut17();case 15:return this.checkNut15();case 19:return this.checkNut19();case 29:return this.checkNut29();default:throw new b("nut is not supported by cashu-ts")}}requiresBlindAuthToken(e17,t2){return this.matchesProtected(this._protected22,e17,t2)}requiresClearAuthToken(e17,t2){return this.matchesProtected(this._protected21,e17,t2)}matchesProtected(e17,t2,n){if(!e17)return false;let r=e17.exact[t2],i=e17.prefix[t2];if(!r||!i)return false;if(e17.exact[t2].has(n))return true;for(let r2 of e17.prefix[t2])if(n.startsWith(r2))return true;return false}checkGenericNut(e17){return this._mintInfo.nuts[e17]?.supported?{supported:true}:{supported:false}}checkMintMelt(t2){let n=this._mintInfo.nuts[t2];return n&&n.methods.length>0&&!n.disabled?{disabled:false,params:e10.snapshot(n.methods)}:{disabled:true,params:e10.snapshot(n?.methods??[])}}checkNut17(){return this._mintInfo.nuts[17]&&this._mintInfo.nuts[17].supported.length>0?{supported:true,params:e10.snapshot(this._mintInfo.nuts[17].supported)}:{supported:false}}checkNut15(){return this._mintInfo.nuts[15]&&this._mintInfo.nuts[15].methods.length>0?{supported:true,params:e10.snapshot(this._mintInfo.nuts[15].methods)}:{supported:false}}checkNut19(){let t2=this._mintInfo.nuts?.[19];if(t2&&(t2?.cached_endpoints?.length||0)>0){let n=J(t2.ttl,"nuts.19.ttl",null);return{supported:true,params:{ttl:n===null?Infinity:Math.max(n,0)*1e3,cached_endpoints:e10.snapshot(t2.cached_endpoints)}}}return{supported:false}}checkNut29(){let t2=this._mintInfo.nuts?.[29];return t2?{supported:true,params:e10.snapshot(t2)}:{supported:false}}static capList(e17,t2,n){return e17.length<=1024?e17:(n.warn(`MintInfo: ${t2} exceeds internal cap and was truncated`,{advertised:e17.length,cap:se}),e17.slice(0,se))}toEndpoints(t2,n){if(!Array.isArray(t2))return[];let r=e10.capList(t2,"nuts.21/22.protected_endpoints",n),i=[];for(let e17 of r)if(e17&&typeof e17=="object"){let t3=e17,n2=t3.method,r2=t3.path;if(typeof n2=="string"&&typeof r2=="string"){let e18=n2.toUpperCase();(e18==="GET"||e18==="POST")&&i.push({method:e18,path:r2})}}return i}buildIndex(e17){if(!e17?.length)return;let t2={GET:new Set,POST:new Set},n={GET:[],POST:[]};for(let r of e17){let e18=r.path;if(e18.startsWith("^")&&(e18=e18.slice(1)),e18.endsWith("$")&&(e18=e18.slice(0,-1)),e18.endsWith(".*")){n[r.method].push(e18.slice(0,-2));continue}if(e18.endsWith("*")){n[r.method].push(e18.slice(0,-1));continue}t2[r.method].add(e18)}return n.GET.sort((e18,t3)=>t3.length-e18.length),n.POST.sort((e18,t3)=>t3.length-e18.length),{exact:t2,prefix:n}}static snapshot(t2,n=0){if(typeof t2!="object"||!t2||t2 instanceof A)return t2;if(n>64)throw new b("Mint info nesting exceeds 64 levels");if(Array.isArray(t2))return t2.map(t3=>e10.snapshot(t3,n+1));let r={};for(let[i,a]of Object.entries(t2))r[i]=e10.snapshot(a,n+1);return r}get cache(){return e10.snapshot(this._mintInfo)}get contact(){return e10.snapshot(this._mintInfo.contact)}get description(){return this._mintInfo.description}get description_long(){return this._mintInfo.description_long}get name(){return this._mintInfo.name}get pubkey(){return this._mintInfo.pubkey}get nuts(){return e10.snapshot(this._mintInfo.nuts)}get version(){return this._mintInfo.version}get motd(){return this._mintInfo.motd}get icon_url(){return this._mintInfo.icon_url}get urls(){return e10.snapshot(this._mintInfo.urls)}get time(){return this._mintInfo.time}get tos_url(){return this._mintInfo.tos_url}get maxArrayLength(){return this._maxArrayLength}supportsNut04Description(e17,t2){return this._mintInfo.nuts[4]?.methods.some(n=>n.method===e17&&(t2?n.unit===t2:true)&&(n.options?.description===true||n.description===true))}supportsMintMeltMethod(e17,t2,n){let{disabled:r,params:i}=this.isSupported(e17==="mint"?4:5);return r?false:i.some(e18=>e18.method===t2&&e18.unit===n)}supportsAmountless(e17="bolt11",t2="sat"){let n=this._mintInfo?.nuts?.[5]?.methods??[];return Array.isArray(n)?n.some(n2=>n2.method===e17&&n2.unit===t2&&n2.options?.amountless===true):false}};var sa={UNPAID:"UNPAID",PAID:"PAID",ISSUED:"ISSUED"};var ca={UNPAID:"UNPAID",PENDING:"PENDING",PAID:"PAID"};function ua(e17){return e17.window!==void 0&&e17.window.document!==void 0?true:e17.WorkerGlobalScope!==void 0&&e17.self!==void 0&&e17.self instanceof e17.WorkerGlobalScope}var da=ua(globalThis);function fa(e17,t2,n=da){return Pa({Accept:"application/json, text/plain, */*",...e17?{"Content-Type":"application/json"}:void 0,...n?void 0:{"User-Agent":"Mozilla/5.0"}},t2)}function pa(e17,t2){return e17 instanceof Error?e17.message:t2}function ma(e17,t2,n,r){if(t2?.signal.aborted)return new Ea(`Request timed out after ${n}ms`,{cause:e17});if(r?.aborted)return new X(pa(e17,"Request aborted by caller"))}async function ha(e17,t2){if(t2?.aborted)throw new b("response body read aborted");let n=e17.text();if(!t2)return n;n.catch(()=>void 0);let r,i=new Promise((e18,n2)=>{r=()=>n2(new b("response body read aborted")),t2.aborted?r():t2.addEventListener("abort",r,{once:true})});i.catch(()=>void 0);try{return await Promise.race([n,i])}finally{r&&t2.removeEventListener("abort",r)}}function ga(e17){if(e17===null)return;let t2=e17.trim();if(t2!==""){if(/^\d+$/.test(t2))return Math.max(Number(t2)*1e3,0);if(/[a-zA-Z]/.test(t2)){let e18=new Date(t2).getTime();if(!Number.isNaN(e18))return Math.max(e18-Date.now(),0)}}}var _a3={endpoint:true,requestBody:true,logger:true,ttl:true,cached_endpoints:true,requestTimeout:true,onResponseMeta:true};var va={};var ya=E;function xa(e17){ya=e17}var Sa=9;var Ca=1e3;var wa=100;var Ta=["blind-auth","clear-auth"];var X=class e11 extends S{constructor(t2){super(t2),this.name="CallerAbortError",Object.setPrototypeOf(this,e11.prototype)}};var Ea=class e12 extends S{constructor(t2,n){super(t2,n),this.name="UncancellableReadError",Object.setPrototypeOf(this,e12.prototype)}};function Da(e17){return e17 instanceof X||e17 instanceof Ea?false:e17 instanceof S?true:e17 instanceof x&&e17.status>=500}function Oa(e17,t2){return t2?new Promise((n,r)=>{if(t2.aborted){r(new X("Request aborted by caller"));return}let i=()=>{clearTimeout(a),t2.removeEventListener("abort",i),r(new X("Request aborted by caller"))};t2.addEventListener("abort",i,{once:true});let a=setTimeout(()=>{t2.removeEventListener("abort",i),n()},e17)}):new Promise(t3=>setTimeout(t3,e17))}function ka(e17){try{return new URL(e17).pathname}catch{return e17.startsWith("/")?e17.split(/[?#]/,1)[0]:void 0}}function Aa(e17,t2){return e17===t2?true:e17.endsWith(t2)}async function ja(e17){let{ttl:t2,cached_endpoints:n,endpoint:r}=e17,i=e17.logger??ya;if(Object.keys(e17.headers??{}).some(e18=>e18.toLowerCase()==="blind-auth"))return await Ma(e17);let a=ka(r),o=e17.method?.toUpperCase()??"GET";if(!(a!==void 0&&n?.some(e18=>Aa(a,e18.path)&&e18.method===o)&&t2))return await Ma(e17);let s=0,c=Date.now(),l=async()=>{try{return await Ma(e17)}catch(n2){if(Da(n2)){let r2=Date.now()-c;if(s<Sa&&(!t2||r2<t2)){let a2=Math.min(2**s*wa,Ca),o2=Math.random()*a2;if(r2+o2>t2)throw i.error(`Network Error: request abandoned after ${s} retries`,{e:n2,retries:s}),n2;return s++,i.info(`Network Error: attempting retry ${s} in ${o2}ms`,{e:n2,retries:s,delay:o2}),await Oa(o2,e17.signal),l()}}throw i.error("Request failed and could not be retried",{e:n2}),n2}};return l()}async function Ma(e17){let{endpoint:t2,requestBody:n,headers:r,requestTimeout:i,onResponseMeta:a,cached_endpoints:o,ttl:s,logger:c,...l}=e17,u=c??ya,d=n?j.stringify(n):void 0,f=fa(d,r),p=Object.keys(f).some(e18=>Ta.includes(e18.toLowerCase())),m=e17.signal??void 0;if(m?.aborted)throw new X("Request aborted by caller");let h=i===void 0?void 0:new AbortController,g=m,_,v;if(h)if(_=setTimeout(()=>h.abort(),i),!m)g=h.signal;else{let e18=new AbortController,t3=()=>e18.abort();m.addEventListener("abort",t3,{once:true}),h.signal.addEventListener("abort",t3,{once:true}),v=()=>{m.removeEventListener("abort",t3),h.signal.removeEventListener("abort",t3)},g=e18.signal}try{let e18;try{e18=await fetch(t2,{body:d,headers:f,cache:"no-store",credentials:"omit",referrer:"",referrerPolicy:"no-referrer",...d===void 0?void 0:{redirect:"error"},...l,...p?{redirect:"error"}:void 0,signal:g})}catch(e19){let t3=!!h?.signal.aborted,n3=!!m?.aborted;throw t3?new S(`Request timed out after ${i}ms`,{cause:e19}):n3?new X(pa(e19,"Request aborted by caller")):e19 instanceof Error&&(e19.name==="AbortError"||e19.name==="TimeoutError")?new S(e19.message,{cause:e19}):new S(pa(e19,"Network request failed"),{cause:e19})}let n2=ga(e18.headers.get("Retry-After"));if(a&&e18.headers&&O(a,{endpoint:t2,status:e18.status,retryAfterMs:n2,rateLimit:e18.headers.get("RateLimit")??void 0,rateLimitPolicy:e18.headers.get("RateLimit-Policy")??void 0,headers:e18.headers},u,{op:"request.onResponseMeta",status:e18.status,endpoint:t2}),!e18.ok){if(e18.status===429){let t4=e18.body;throw t4&&typeof t4.cancel=="function"&&t4.cancel().catch(()=>void 0),new T("429 Too Many Requests",n2)}let t3,r3;try{t3=Na(await ha(e18,g))}catch(e19){let n3=ma(e19,h,i,m);if(n3)throw n3;r3=e19,t3={error:"bad response"}}if(e18.status===400&&"code"in t3&&typeof t3.code=="number"&&"detail"in t3&&typeof t3.detail=="string")throw new te(t3.code,t3.detail);let a2="HTTP request failed";throw"error"in t3&&typeof t3.error=="string"?a2=t3.error:"detail"in t3&&typeof t3.detail=="string"&&(a2=t3.detail),new x(a2,e18.status,{cause:r3})}let r2;try{r2=await ha(e18,g)}catch(t3){throw ma(t3,h,i,m)||(u.error("Failed to read HTTP response",{err:t3}),new x("bad response",e18.status,{cause:t3}))}try{if(!r2)throw new b("Empty response body");return j.parse(r2,void 0,{strict:true})}catch(t3){throw u.error("Failed to parse HTTP response",{err:t3}),new x("bad response",e18.status,{cause:t3})}}finally{clearTimeout(_),v?.()}}function Na(e17){if(!e17)return{detail:"bad response"};let t2;try{t2=j.parse(e17,void 0,{strict:true})}catch{return{detail:e17}}return typeof t2=="object"&&t2&&("detail"in t2||"code"in t2||"error"in t2)?t2:{detail:t2}}function Pa(e17,t2){let n=new Map;for(let r of[e17,t2])for(let[e18,t3]of Object.entries(r??{}))n.set(e18.toLowerCase(),[e18,t3]);return Object.fromEntries(n.values())}async function Fa(e17){let t2=e17.onResponseMeta,n=va.onResponseMeta,r={...e17,...va};for(let t3 of Object.keys(_a3))e17[t3]!==void 0&&(r[t3]=e17[t3]);if(r.headers=Pa(va.headers,e17.headers),t2&&n&&t2!==n){let i=r.logger??ya;r.onResponseMeta=r2=>{O(t2,r2,i,{op:"request.onResponseMeta",scope:"per-request",endpoint:e17.endpoint}),O(n,r2,i,{op:"request.onResponseMeta",scope:"global",endpoint:e17.endpoint})}}return await ja(r)}var Ia;typeof WebSocket<"u"&&(Ia=WebSocket);function Ra(){if(Ia===void 0)throw new b("WebSocket implementation not initialized");return Ia}var za=1006;var Ba=class{constructor(e17){this.next=null,this.value=e17}};var Va=class{constructor(){this._first=null,this._last=null,this.size=0}enqueue(e17){let t2=new Ba(e17);return this._last?this._last.next=t2:this._first=t2,this._last=t2,this.size++,true}dequeue(){if(!this._first)return null;let e17=this._first;return this._first=e17.next,this._first||(this._last=null),this.size--,e17.value}};var Ha=class{constructor(e17,t2){this.subListeners={},this.rpcListeners={},this.rpcId=0,this.onCloseCallbacks=[],this._WS=Ra(),this.url=new URL(e17),this.messageQueue=new Va,this._logger=t2??E}setLogger(e17){this._logger=e17}connect(e17=1e4){return this.connectionPromise||(this.connectionPromise=new Promise((t2,n)=>{let r=false,i=false,a=null,o=e18=>{i||(i=true,a&&clearTimeout(a),this.abandonConnect=void 0,e18())};this.abandonConnect=e18=>o(()=>n(e18));let s=()=>{if(this.ws){try{this.ws.onopen=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.onclose=null}catch{}try{this.ws.close()}catch{}this.ws=void 0,this.stopMessageHandling()}},c=e18=>{this.connectionPromise=void 0,s();let t3=e18 instanceof Error?e18:new b(String(e18),{cause:e18});this.failPendingRpc(t3),o(()=>n(t3))},l;try{l=new this._WS(this.url.toString()),this.ws=l}catch(e18){c(e18);return}let u=()=>this.ws===l;a=setTimeout(()=>{c(new b(`WebSocket connect timeout after ${e17}ms`))},e17),l.onopen=()=>{u()&&(r=true,o(t2))},l.onerror=e18=>{if(u()){if(!r){c(new b("Failed to open WebSocket"));return}this._logger.error("WebSocket error after open",{ev:e18})}},l.onmessage=e18=>{if(u()){if(this.messageQueue.size>=1e4){this._logger.error("WebSocket message queue exceeded its bound, closing connection",{size:this.messageQueue.size});let e19=new b("WebSocket message queue exceeded its bound");c(e19),this.onCloseCallbacks.forEach(t3=>t3({code:za,reason:e19.message,wasClean:false}));return}this.messageQueue.enqueue(e18.data),this.handlingInterval||(this.handlingInterval=setInterval(this.handleNextMessage.bind(this),0))}},l.onclose=e18=>{if(this.ws&&this.ws!==l)return;if(this.connectionPromise=void 0,!r){let t4=e18?.reason?`, ${e18.reason}`:"";c(new b(`WebSocket closed before open (code ${e18?.code??0}${t4})`));return}this.stopMessageHandling();let t3=e18?.reason?`, ${e18.reason}`:"",n2=e18?.code??0;!(typeof e18.wasClean!="boolean"||e18.wasClean)||n2!==1e3&&n2!==1001?this.failPendingRpc(new b(`WebSocket closed (code ${n2}${t3})`)):this.rpcListeners={},this.onCloseCallbacks.forEach(t4=>t4(e18))}})),this.connectionPromise}sendRequest(e17,t2){if(this.ws?.readyState!==this._WS.OPEN){if(e17==="unsubscribe")return;throw this._logger.error("Attempted sendRequest, but socket was not open"),new b("Socket not open")}let n=this.rpcId;this.rpcId++,this.sendRpcMessage(e17,t2,n)}addSubListener(e17,t2){(this.subListeners[e17]=this.subListeners[e17]||[]).push(t2)}stopMessageHandling(){for(this.handlingInterval&&(clearInterval(this.handlingInterval),this.handlingInterval=void 0);this.messageQueue.size>0;)this.messageQueue.dequeue();this.subListeners={}}failPendingRpc(e17){let t2=this.rpcListeners;this.rpcListeners={};for(let n of Object.keys(t2))try{t2[n].errorCallback(e17)}catch{}}sendRpcMessage(e17,t2,n){if(this.ws?.readyState!==this._WS.OPEN)throw new b("Socket not open");let r=JSON.stringify({jsonrpc:"2.0",method:e17,params:t2,id:n});try{this.ws.send(r)}catch(e18){this._logger.error("WebSocket send failed",{e:e18}),this.connectionPromise=void 0;try{this.ws.close()}catch{}this.ws=void 0,this.stopMessageHandling();let t3=e18 instanceof Error?e18:new b(String(e18),{cause:e18});throw this.failPendingRpc(t3),t3}}addRpcListener(e17,t2,n){this.rpcListeners[n]={callback:e17,errorCallback:t2}}removeRpcListener(e17){delete this.rpcListeners[e17]}removeListener(e17,t2){if(this.subListeners[e17]){if(this.subListeners[e17].length===1){delete this.subListeners[e17];return}this.subListeners[e17]=this.subListeners[e17].filter(e18=>e18!==t2)}}async ensureConnection(e17){this.ws?.readyState!==this._WS.OPEN&&await this.connect(e17)}handleNextMessage(){for(;this.messageQueue.size>0;){let e17=this.messageQueue.dequeue();try{let t2=j.parse(e17,void 0,{strict:true});if("result"in t2&&t2.id!=null)this.rpcListeners[t2.id]&&(this.rpcListeners[t2.id].callback(),this.removeRpcListener(t2.id));else if("error"in t2&&t2.id!=null)this.rpcListeners[t2.id]&&(this.rpcListeners[t2.id].errorCallback(new b(t2.error.message)),this.removeRpcListener(t2.id));else if("method"in t2&&!("id"in t2)){let e18=t2.params?.subId;if(!e18)continue;if(this.subListeners[e18]?.length>0){let n=t2;this.subListeners[e18].forEach(e19=>{try{let t3=e19(n.params?.payload);t3&&typeof t3.then=="function"&&Promise.resolve(t3).catch(e20=>{this._logger.error("Subscription handler threw",{e:e20})})}catch(e20){this._logger.error("Subscription handler threw",{e:e20})}})}}}catch(e18){this._logger.error("Error doing handleNextMessage",{e:e18})}}this.handlingInterval&&(clearInterval(this.handlingInterval),this.handlingInterval=void 0)}createSubscription(e17,t2,n){if(this.ws?.readyState!==this._WS.OPEN)throw this._logger.error("Attempted createSubscription, but socket was not open"),new b("Socket is not open");let r=(Math.random()+1).toString(36).substring(7),i=this.rpcId;this.addRpcListener(()=>{this.addSubListener(r,t2)},n,i);try{this.sendRequest("subscribe",{...e17,subId:r})}catch(e18){throw this.removeRpcListener(i),e18}return r}cancelSubscription(e17,t2,n){if(this.removeListener(e17,t2),this.ws?.readyState!==this._WS.OPEN){this._logger.info("Socket not open, removed listener locally {subId}",{subId:e17});return}let r=this.rpcId;this.rpcId++,this.addRpcListener(()=>{this._logger.info("Unsubscribed {subId}",{subId:e17})},n||(e18=>this._logger.error("Unsubscribe failed",{e:e18})),r);try{this.sendRpcMessage("unsubscribe",{subId:e17},r)}catch(e18){throw this.removeRpcListener(r),e18}}get activeSubscriptions(){return Object.keys(this.subListeners)}close(){let e17=new b("WebSocket closed");if(this.abandonConnect?.(e17),this.ws){try{this.ws.close()}catch{}this.ws=void 0}this.connectionPromise=void 0,this.failPendingRpc(e17),this.stopMessageHandling()}onClose(e17){this.onCloseCallbacks.push(e17)}};function Ua(e17){return Array.isArray(e17)?"array":typeof e17}var Wa=class{constructor(e17,t2){this._lastResponseMetadata=void 0,this._captureResponseMetadata=e18=>{this._lastResponseMetadata=e18},this._mintUrl=Hi(e17),this._request=t2?.customRequest??Fa,this._authProvider=t2?.authProvider,this._logger=t2?.logger??E,xa(this._logger)}get mintUrl(){return this._mintUrl}get lastResponseMetadata(){return this._lastResponseMetadata}async oidcAuth(e17){let t2=(await this.getLazyMintInfo()).nuts[21];if(!t2?.openid_discovery)throw new b("Mint: no NUT-21 openid_discovery");return new oa(t2.openid_discovery,{...e17,clientId:e17?.clientId??t2.client_id??"cashu-client"})}async getInfo(e17){let t2=await(e17??this._request)({endpoint:G(this._mintUrl,"/v1/info"),onResponseMeta:this._captureResponseMetadata,logger:this._logger});return Y.normalizeInfo(t2,this._logger)}async getLazyMintInfo(e17){if(this._mintInfo)return this._mintInfo;let t2=await this.getInfo(e17);return this._mintInfo=new Y(t2,this._logger),this._mintInfo}setMintInfo(e17){this._mintInfo=e17 instanceof Y?e17:new Y(e17,this._logger)}async swap(e17,t2){D(!Array.isArray(e17?.inputs),"swap: inputs must be an array of proofs",this._logger);let n=await this.requestWithAuth("POST","/v1/swap",{requestBody:{...e17,inputs:this.stripWalletFields(e17.inputs)}},t2);if(!H(n)||!Array.isArray(n?.signatures))throw this._logger.error("Invalid response from mint...",{data:n,op:"swap"}),new b("Invalid response from mint");return this.assertSignatureCount(n.signatures,e17.outputs,"swap"),n.signatures=this.normalizeSignatureAmounts(n.signatures),n}async createMintQuote(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint quote method: ${e17}`,this._logger);let r=await this.requestWithAuth("POST",`/v1/mint/quote/${e17}`,{requestBody:t2},n?.customRequest);return this.normalizeMintQuoteResponse(e17,r,n?.normalize)}async createMintQuoteBolt11(e17,t2){return this.createMintQuote("bolt11",{...e17,amount:A.from(e17.amount).toBigInt()},{customRequest:t2})}async createMintQuoteBolt12(e17,t2){let n={...e17};return e17.amount!==void 0&&(n.amount=A.from(e17.amount).toBigInt()),this.createMintQuote("bolt12",n,{customRequest:t2})}async createMintQuoteOnchain(e17,t2){return this.createMintQuote("onchain",e17,{customRequest:t2})}async checkMintQuote(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint quote method: ${e17}`,this._logger);let r=await this.requestWithAuth("GET",`/v1/mint/quote/${e17}/${t2}`,{},n?.customRequest),i=this.normalizeMintQuoteResponse(e17,r,n?.normalize);if(i.quote!==t2)throw this._logger.error("Invalid response from mint...",{op:`checkMintQuote.${e17}`}),new b("Mint quote response is for a different quote");return i}async checkMintQuoteBolt11(e17,t2){return this.checkMintQuote("bolt11",e17,{customRequest:t2})}async checkMintQuoteBolt12(e17,t2){return this.checkMintQuote("bolt12",e17,{customRequest:t2})}async checkMintQuoteOnchain(e17,t2){return this.checkMintQuote("onchain",e17,{customRequest:t2})}async checkMintQuoteBatch(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint quote method: ${e17}`,this._logger),D(t2.length===0,"checkMintQuoteBatch: no quote ids provided",this._logger),D(new Set(t2).size!==t2.length,"checkMintQuoteBatch: duplicate quote ids provided",this._logger);let r=await this.requestWithAuth("POST",`/v1/mint/quote/${e17}/check`,{requestBody:{quotes:t2}},n?.customRequest);if(!Array.isArray(r)||r.length!==t2.length)throw this._logger.error("Invalid response from mint...",{expectedCount:t2.length,actualCount:Array.isArray(r)?r.length:void 0,op:`checkMintQuoteBatch.${e17}`}),new b("Invalid response from mint");return r.map((r2,i)=>{if(r2.quote!==t2[i])throw this._logger.error("Invalid response from mint...",{index:i,op:`checkMintQuoteBatch.${e17}`}),new b("Invalid response from mint");return this.normalizeMintQuoteResponse(e17,r2,n?.normalize)})}async checkMintQuoteBatchBolt11(e17,t2){return this.checkMintQuoteBatch("bolt11",e17,{customRequest:t2})}async checkMintQuoteBatchBolt12(e17,t2){return this.checkMintQuoteBatch("bolt12",e17,{customRequest:t2})}async mintBolt11(e17,t2){return this.mint("bolt11",e17,{customRequest:t2})}async mintBolt12(e17,t2){return this.mint("bolt12",e17,{customRequest:t2})}async mintOnchain(e17,t2){return this.mint("onchain",e17,{customRequest:t2})}async mint(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint method: ${e17}`,this._logger);let r=await this.requestWithAuth("POST",`/v1/mint/${e17}`,{requestBody:t2},n?.customRequest);if(!H(r)||!Array.isArray(r?.signatures))throw this._logger.error("Invalid response from mint...",{data:r,op:`mint.${e17}`}),new b("Invalid response from mint");return this.assertSignatureCount(r.signatures,t2.outputs,`mint.${e17}`),r.signatures=this.normalizeSignatureAmounts(r.signatures),n?.normalize?n.normalize(r):r}async mintBatchBolt11(e17,t2){return this.mintBatch("bolt11",e17,{customRequest:t2})}async mintBatchBolt12(e17,t2){return this.mintBatch("bolt12",e17,{customRequest:t2})}async mintBatch(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid mint method: ${e17}`,this._logger);let r={...t2,quote_amounts:t2.quote_amounts.map(e18=>A.from(e18).toBigInt())},i=await this.requestWithAuth("POST",`/v1/mint/${e17}/batch`,{requestBody:r},n?.customRequest);if(!H(i)||!Array.isArray(i?.signatures))throw this._logger.error("Invalid response from mint...",{data:i,op:`mintBatch.${e17}`}),new b("Invalid response from mint");return this.assertSignatureCount(i.signatures,t2.outputs,`mintBatch.${e17}`),i.signatures=this.normalizeSignatureAmounts(i.signatures),n?.normalize?n.normalize(i):i}async createMeltQuote(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid melt quote method: ${e17}`,this._logger);let r=await this.requestWithAuth("POST",`/v1/melt/quote/${e17}`,{requestBody:t2},n?.customRequest);return this.normalizeMeltQuoteResponse(e17,r,n?.normalize)}async createMeltQuoteBolt11(e17,t2){let n=await this.createMeltQuote("bolt11",this.normalizeMeltQuoteRequestOptions(e17),{customRequest:t2});return D(n.request!==""&&n.request.toLowerCase()!==e17.request.toLowerCase(),"Melt quote is for a different payment request",this._logger),n}async createMeltQuoteBolt12(e17,t2){return this.createMeltQuote("bolt12",this.normalizeMeltQuoteRequestOptions(e17),{customRequest:t2})}async createMeltQuoteOnchain(e17,t2){return this.createMeltQuote("onchain",{...e17,amount:A.from(e17.amount).toBigInt()},{customRequest:t2})}async checkMeltQuote(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid melt quote method: ${e17}`,this._logger);let r=await this.requestWithAuth("GET",`/v1/melt/quote/${e17}/${t2}`,{},n?.customRequest),i=this.normalizeMeltQuoteResponse(e17,r,n?.normalize);if(i.quote!==t2)throw this._logger.error("Invalid response from mint...",{data:i,op:`checkMeltQuote.${e17}`}),new b("Melt quote response is for a different quote");return i}async checkMeltQuoteBolt11(e17,t2){return this.checkMeltQuote("bolt11",e17,{customRequest:t2})}async checkMeltQuoteBolt12(e17,t2){return this.checkMeltQuote("bolt12",e17,{customRequest:t2})}async checkMeltQuoteOnchain(e17,t2){return this.checkMeltQuote("onchain",e17,{customRequest:t2})}async melt(e17,t2,n){D(!this.isValidMethodString(e17),`Invalid melt method: ${e17}`,this._logger),D(!Array.isArray(t2?.inputs),"melt: inputs must be an array of proofs",this._logger);let r=await this.requestWithAuth("POST",`/v1/melt/${e17}`,{requestBody:{...t2,inputs:this.stripWalletFields(t2.inputs)}},n?.customRequest),i=this.normalizeMeltQuoteResponse(e17,r,n?.normalize,true);return i.quote!==t2.quote&&(this._logger.warn("Melt response reports a different quote id",{op:`melt.${e17}`,expected:t2.quote,received:i.quote}),i.quote=t2.quote),i}async meltBolt11(e17,t2){return this.melt("bolt11",e17,t2)}async meltBolt12(e17,t2){return this.melt("bolt12",e17,t2)}async meltOnchain(e17,t2){return this.melt("onchain",e17,t2)}async check(e17,t2){let n=await this.requestWithAuth("POST","/v1/checkstate",{requestBody:e17},t2);if(!H(n)||!Array.isArray(n?.states)||n.states.length>e17.Ys.length)throw this._logger.error("Invalid response from mint...",{data:n,op:"check"}),new b("Invalid response from mint");this.assertRecordEntries(n.states,"check");for(let e18 of n.states)W(e18,"witness");return n}async getKeys(e17,t2,n){let r=t2||this._mintUrl;e17&&(e17=e17.replace(/\//g,"_").replace(/\+/g,"-"));let i=await(n??this._request)({endpoint:e17?G(r,"/v1/keys",e17):G(r,"/v1/keys"),onResponseMeta:this._captureResponseMetadata,logger:this._logger});if(!H(i)||!Array.isArray(i.keysets))throw this._logger.error("Invalid response from mint...",{data:i,op:"getKeys"}),new b("Invalid response from mint");return this.assertKeysetList(i.keysets,"getKeys"),{...i,keysets:i.keysets.map(e18=>ia(e18))}}async getKeySets(e17){let t2=await(e17??this._request)({endpoint:G(this._mintUrl,"/v1/keysets"),onResponseMeta:this._captureResponseMetadata,logger:this._logger});if(!H(t2)||!Array.isArray(t2.keysets))throw this._logger.error("Invalid response from mint...",{data:t2,op:"getKeySets"}),new b("Invalid response from mint");return this.assertKeysetList(t2.keysets,"getKeySets"),{...t2,keysets:t2.keysets.map(e18=>ra(e18))}}async restore(e17,t2){let n=await(t2??this._request)({endpoint:G(this._mintUrl,"/v1/restore"),method:"POST",requestBody:e17,onResponseMeta:this._captureResponseMetadata,logger:this._logger});if(!H(n)||!Array.isArray(n?.outputs)||!Array.isArray(n?.signatures)||n.outputs.length!==n.signatures.length||n.outputs.length>e17.outputs.length)throw this._logger.error("Invalid response from mint...",{data:n,op:"restore"}),new b("Invalid response from mint");return n.outputs=this.normalizeMessageAmounts(n.outputs),n.signatures=this.normalizeSignatureAmounts(n.signatures),n}async connectWebSocket(){try{let e17=new URL(this._mintUrl),t2="v1/ws";e17.pathname.endsWith("/")?e17.pathname+=t2:e17.pathname+="/"+t2,e17.protocol=e17.protocol==="https:"?"wss:":"ws:";let n=e17.toString();this.ws||(this.ws=new Ha(n,this._logger)),await this.ws.ensureConnection()}catch(e17){this._logger.error("Failed to connect to WebSocket...",{e:e17});try{this.ws?.close()}catch{}throw this.ws=void 0,new b("Failed to connect to WebSocket...",{cause:e17})}}disconnectWebSocket(){this.ws&&this.ws.close()}get webSocketConnection(){return this.ws}async handleClearAuth(e17,t2,n){if(this._authProvider&&(n??await this.getLazyMintInfo()).requiresClearAuthToken(e17,t2))return this._authProvider.ensureCAT?this._authProvider.ensureCAT():this._authProvider.getCAT()}async handleBlindAuth(e17,t2,n){if(this._authProvider&&(n??await this.getLazyMintInfo()).requiresBlindAuthToken(e17,t2))return await this._authProvider.getBlindAuthToken({method:e17,path:t2})}async requestWithAuth(e17,t2,n={},r){let i=r??this._request,a=this._mintInfo;this._authProvider&&(a=await this.getLazyMintInfo(r));let o=await this.handleBlindAuth(e17,t2,a),s=await this.handleClearAuth(e17,t2,a),c={...n.headers??{},...o?{"Blind-auth":o}:{},...s?{"Clear-auth":s}:{}},l=a?.isSupported(19);return i({...n,endpoint:G(this._mintUrl,t2),method:e17,headers:c,...o||s||n.requestBody?{redirect:"error"}:{},...l?.supported&&l.params?l.params:{},onResponseMeta:this._captureResponseMetadata,logger:n.logger??this._logger})}normalizeMeltQuoteRequestOptions(e17){if(!e17.options)return{...e17};let t2={...e17.options};return e17.options.amountless&&(t2.amountless={amount_msat:A.from(e17.options.amountless.amount_msat).toBigInt()}),"mpp"in e17.options&&e17.options.mpp&&(t2.mpp={amount:A.from(e17.options.mpp.amount).toBigInt()}),{...e17,options:t2}}isValidMethodString(e17){return!!(typeof e17=="string"&&/^[a-z0-9_-]+$/.test(e17))}normalizeSignatureAmounts(e17){return this.assertRecordEntries(e17,"signatures"),e17.map(e18=>({...e18,amount:A.from(e18.amount)}))}normalizeMessageAmounts(e17){return this.assertRecordEntries(e17,"outputs"),e17.map(e18=>({...e18,amount:A.from(e18.amount)}))}stripWalletFields(e17){return e17.map(e18=>{let{dleq:t2,p2pk_e:n,...r}=e18;return r})}assertRecordEntries(e17,t2){if(!e17.every(e18=>U(e18)))throw this._logger.error("Invalid response from mint...",{entries:e17.length,op:t2}),new b("Invalid response from mint")}assertSignatureCount(e17,t2,n){if(!(e17.length<=t2.length))throw this._logger.error("Invalid response from mint...",{signatures:e17.length,outputs:t2.length,op:n}),new b(`Invalid response from mint: ${e17.length} signatures, expected ${t2.length}. The operation may already have been applied; if the wallet is seeded, try restoring (NUT-09) to recover.`)}assertKeysetList(e17,t2){if(e17.length>1e4)throw this._logger.error("Invalid response from mint...",{keysets:e17.length,op:t2}),new b("Invalid response from mint");this.assertRecordEntries(e17,t2)}normalizeMintQuoteResponse(e17,t2,n){let r=`${e17} mint quote`;if(!U(t2))throw this._logger.error("Invalid response from mint...",{type:Ua(t2),op:r}),new b("Invalid response from mint");let i={...t2};return this.normalizeMintBaseFields(i),e17==="bolt11"?this.normalizeMintQuoteBolt11Fields(i):e17==="bolt12"?this.normalizeMintQuoteBolt12Fields(i):e17==="onchain"&&this.normalizeMintQuoteOnchainFields(i),n?n(i):i}normalizeMintBaseFields(e17){e17.amount_paid!=null&&e17.amount_issued!=null&&(e17.amount_paid=A.from(e17.amount_paid),e17.amount_issued=A.from(e17.amount_issued)),e17.updated_at=J(e17.updated_at,"mintQuote.updated_at",null)}deriveMintQuoteState(e17,t2){return e17.isZero()&&t2.isZero()?sa.UNPAID:e17.greaterThan(t2)?sa.PAID:sa.ISSUED}normalizeMintQuoteBolt11Fields(e17){e17.amount=A.from(e17.amount),e17.expiry=J(e17.expiry,"mintQuoteBolt11.expiry",null),(typeof e17.state!="string"||!Object.values(sa).includes(e17.state))&&e17.amount_paid instanceof A&&e17.amount_issued instanceof A&&(e17.state=this.deriveMintQuoteState(e17.amount_paid,e17.amount_issued))}normalizeMintQuoteBolt12Fields(e17){W(e17,"amount"),e17.amount=e17.amount===null?null:A.from(e17.amount),e17.expiry=J(e17.expiry,"mintQuoteBolt12.expiry",null),e17.amount_paid=A.from(e17.amount_paid),e17.amount_issued=A.from(e17.amount_issued)}normalizeMintQuoteOnchainFields(e17){e17.expiry=J(e17.expiry,"mintQuoteOnchain.expiry",null),e17.amount_paid=A.from(e17.amount_paid),e17.amount_issued=A.from(e17.amount_issued)}normalizeMeltQuoteResponse(e17,t2,n,r=false){let i=`${e17} melt quote`;if(!U(t2))throw this._logger.error("Invalid response from mint...",{type:Ua(t2),op:i}),new b("Invalid response from mint");let a={...t2};return r&&((a.request==null||a.request==="")&&delete a.request,a.fee_reserve??delete a.fee_reserve),this.normalizeMeltBaseFields(a,i),e17==="bolt11"||e17==="bolt12"?this.normalizeMeltBoltFields(a,i,r):e17==="onchain"&&this.normalizeMeltOnchainFields(a,r),n?n(a):a}normalizeMeltBaseFields(e17,t2){if(e17.amount=A.from(e17.amount),e17.expiry=J(e17.expiry,"meltQuote.expiry",void 0),e17.change){if(!Array.isArray(e17.change)||e17.change.length>1024)throw this._logger.error("Invalid response from mint...",{type:Ua(e17.change),op:t2}),new b("Invalid response from mint");e17.change=this.normalizeSignatureAmounts(e17.change)}if(!H(e17)||typeof e17.quote!="string"||!(e17.amount instanceof A)||typeof e17.unit!="string"||typeof e17.state!="string"||typeof e17.expiry!="number"||!Object.values(ca).includes(e17.state))throw this._logger.error("Invalid response from mint...",{op:t2}),new b("Invalid response from mint")}normalizeMeltBoltFields(e17,t2,n){let r=t3=>n&&e17[t3]===void 0;if(!r("fee_reserve")&&e17.fee_reserve!=null&&(e17.fee_reserve=A.from(e17.fee_reserve)),typeof e17.request!="string"&&!r("request")||!(e17.fee_reserve instanceof A)&&!r("fee_reserve"))throw this._logger.error("Invalid response from mint...",{op:t2}),new b("Invalid response from mint");W(e17,"payment_preimage")}normalizeMeltOnchainFields(e17,t2){if(t2&&e17.fee_options===void 0){W(e17,"selected_fee_index","outpoint");return}if(!Array.isArray(e17.fee_options)||e17.fee_options.length===0||e17.fee_options.length>1024||(e17.fee_options=e17.fee_options.map(e18=>{let t3=e18;if(!Number.isSafeInteger(t3.fee_index))throw this._logger.error("Invalid response from mint...",{op:"onchain melt quote"}),new b("Invalid response from mint");return{...t3,fee_index:t3.fee_index,fee_reserve:A.from(t3.fee_reserve),estimated_blocks:t3.estimated_blocks}}),W(e17,"selected_fee_index","outpoint"),typeof e17.request!="string"||e17.selected_fee_index!==null&&!Number.isSafeInteger(e17.selected_fee_index)||e17.outpoint!==null&&typeof e17.outpoint!="string"))throw this._logger.error("Invalid response from mint...",{op:"onchain melt quote"}),new b("Invalid response from mint")}};var Ga=class e13{constructor(e17,t2,n,r,i){this._keys={},this._id=e17,this._unit=t2,this._active=n,this._input_fee_ppk=r,this._final_expiry=i}get id(){return this._id}get unit(){return this._unit}get isActive(){return this._active}get fee(){return this._input_fee_ppk??0}get expiry(){return this._final_expiry}get hasKeys(){return Object.keys(this._keys).length>0}get hasHexId(){return V(this._id)}get version(){return this.hasHexId?hexToBytes2(this._id)[0]:-1}get keys(){return this._keys}set keys(e17){this._keys=e17}toMintKeyset(){return{id:this._id,unit:this._unit,active:this._active,input_fee_ppk:this._input_fee_ppk,final_expiry:this._final_expiry}}toMintKeys(){return this.hasKeys?{id:this._id,unit:this._unit,active:this._active,input_fee_ppk:this._input_fee_ppk,final_expiry:this._final_expiry,keys:this._keys}:null}verify(){return this.hasKeys?e13.verifyKeysetId(this.toMintKeys()):false}static verifyKeysetId(e17){try{let t2=e17.keys?Object.keys(e17.keys).length:0;if(t2===0||t2>256||new Set(Object.values(e17.keys).map(e18=>e18.toLowerCase())).size!==t2)return false;let n=et(e17.id)&&!V(e17.id),i=V(e17.id)?hexToBytes2(e17.id)[0]:0;return zi(e17.keys,{input_fee_ppk:e17.input_fee_ppk,expiry:e17.final_expiry,unit:e17.unit,versionByte:i,isDeprecatedBase64:n})===e17.id}catch{return false}}static fromMintApi(t2,n){let r=ra(t2),i=n?ia(n):void 0,a=new e13(r.id,r.unit,r.active,r.input_fee_ppk,r.final_expiry);if(i){if(i.id!==r.id)throw new b(`Mismatched keyset ids: meta=${r.id}, keys=${i.id}`);if(i.unit!==r.unit)throw new b(`Mismatched keyset units: meta=${r.unit}, keys=${i.unit}`);if(i.final_expiry!==void 0&&r.final_expiry!==void 0&&i.final_expiry!==r.final_expiry)throw new b(`Mismatched keyset expiry for id=${r.id}`);a.keys=i.keys}return a}};var Ka=class e14{assertInitialized(){if(Object.keys(this.keysets).length===0)throw new b("KeyChain not initialized")}constructor(e17,t2,n=E){this.keysets=Object.create(null),this.pendingKeyFetches=new Map,this.generation=0,this.refreshSeq=0,this.mint=typeof e17=="string"?new Wa(e17):e17,this.unit=t2,this._logger=n}static fromCache(t2,n,r,i){let a=new e14(t2,n,i);return a.loadFromCache(r),a}static mintToCacheDTO(e17,t2,n){let r=new Map(n.map(e18=>[e18.id,e18]));return{keysets:t2.map(e18=>{let t3=r.get(e18.id),n2={...e18};return t3&&(n2.keys={...t3.keys}),n2}),mintUrl:e17,savedAt:Date.now()}}static cacheToMintDTO(e17){return{keysets:e17.keysets.map(e18=>({id:e18.id,unit:e18.unit,active:e18.active,input_fee_ppk:e18.input_fee_ppk,final_expiry:e18.final_expiry})),keys:e17.keysets.filter(e18=>!!e18.keys).map(e18=>({id:e18.id,unit:e18.unit,active:e18.active,input_fee_ppk:e18.input_fee_ppk,final_expiry:e18.final_expiry,keys:{...e18.keys}}))}}async init(e17){if(Object.keys(this.keysets).length>0&&!e17)return;let t2=++this.refreshSeq,[n,r]=await Promise.all([this.mint.getKeySets(),this.mint.getKeys()]);if(t2!==this.refreshSeq){this._logger.debug("Discarding keychain refresh superseded by a later one",{seq:t2});return}this.buildKeychain(n.keysets,r.keysets),this.savedAt=Date.now()}loadFromCache(t2){let n;try{n=Hi(String(t2.mintUrl))}catch{n=void 0}n!==this.mint.mintUrl&&this._logger.warn(`KeyChain cache is for a different mint: ${n??"unknown"} (expected ${this.mint.mintUrl}). This will become an error in cashu-ts v5.`,{cacheMintUrl:t2.mintUrl,mintUrl:this.mint.mintUrl});let{keysets:r,keys:i}=e14.cacheToMintDTO(t2);this.buildKeychain(r,i),this.savedAt=t2.savedAt}buildKeychain(e17,t2){let n=this.keysets,r=Object.create(null),i=new Map(t2.map(e18=>[e18.id,e18]));for(let t3 of e17){let e18=i.get(t3.id),a=e18?Ga.fromMintApi(t3,e18):Ga.fromMintApi(t3);a.verify()||(a.hasKeys&&this._logger.warn("Discarding keys that do not derive their keyset id",{id:a.id}),a.keys={});let o=n[t3.id];!a.hasKeys&&o?.hasKeys&&o.unit===a.unit&&(a.keys={...o.keys},a.verify()||(this._logger.warn("Dropping carried keys: fresh metadata no longer derives the keyset id",{id:a.id}),a.keys={})),r[a.id]=a}this.keysets=r,this.generation++}getKeyset(e17){let t2=e17?this.keysets[e17]:this.getCheapestKeyset();if(!t2)throw new b(`Keyset '${e17}' not found`);return t2}getCheapestKeyset(){if(Object.keys(this.keysets).length===0)throw new b("KeyChain not initialized");let e17=Object.values(this.keysets).filter(e18=>e18.unit===this.unit&&e18.isActive&&e18.hasHexId&&e18.hasKeys);if(e17.length===0)throw new b(`No active keyset found for unit: ${this.unit}`);let t2=2**53-1;return e17.sort((e18,n)=>n.version-e18.version||e18.fee-n.fee||(n.expiry??t2)-(e18.expiry??t2))[0]}async ensureKeysetKeys(e17){let t2=this.keysets[e17];if(!t2)throw new b(`Keyset '${e17}' not found`);if(t2.hasKeys)return t2;let n=this.pendingKeyFetches.get(e17);if(n)return await n;let r=(async()=>{let n2=this.generation,r2=(await this.mint.getKeys(e17)).keysets.find(t3=>t3.id===e17);if(!r2||!r2.keys||Object.keys(r2.keys).length===0)throw new b(`Mint returned no keys for keyset '${e17}'`);let i=t2.toMintKeyset(),a=Ga.fromMintApi(i,r2);if(!a.verify())throw new b(`Keyset verification failed for ID ${e17}`);if(this.generation!==n2){this._logger.debug("Keychain refreshed during key fetch; returning the live keyset",{id:e17});let t3=this.keysets[e17];if(!t3)throw new b(`Keyset '${e17}' not found`);return t3}return this.keysets[e17]=a,a})();this.pendingKeyFetches.set(e17,r);try{return await r}finally{this.pendingKeyFetches.delete(e17)}}getKeysets(){this.assertInitialized();let e17=Object.values(this.keysets).filter(e18=>e18.unit===this.unit);if(e17.length===0)throw new b(`No keysets found for unit: ${this.unit}`);return e17}isUnitKeyset(e17){if(!e17)return false;let t2=this.keysets[e17];return t2!==void 0&&t2.unit===this.unit}hasKeyset(e17){return!!e17&&this.keysets[e17]!==void 0}getAllKeys(){return this.assertInitialized(),Object.values(this.keysets).map(e17=>e17.toMintKeys()).filter(e17=>e17!==null)}getAllKeysetIds(){return this.assertInitialized(),Object.keys(this.keysets)}get cache(){let t2=Object.values(this.keysets),n=t2.map(e17=>e17.toMintKeyset()),r=t2.map(e17=>e17.toMintKeys()).filter(e17=>e17!==null),i=e14.mintToCacheDTO(this.mint.mintUrl,n,r);return i.savedAt=this.savedAt,i}};var qa=class{constructor(e17,t2,n){this.amountValue=A.from(e17),this.B_=t2,this.id=n}get amount(){return this.amountValue}getSerializedBlindedMessage(){return{amount:this.amountValue,B_:this.B_.toHex(true),id:this.id}}};var Ja=new Set(["locktime","pubkeys","n_sigs","refund","n_sigs_refund","sigflag"]);function Ya(e17){if(!e17||typeof e17!="string")throw new b("tag key must be a non empty string");if(Ja.has(e17))throw new b(`additionalTags must not use reserved key "${e17}"`)}var Z=class e15{constructor(e17,t2,n,r){if(typeof t2!="bigint"||t2<=0n)throw new b("OutputData: blindingFactor must be a positive bigint");if(!(n instanceof Uint8Array)||n.length===0)throw new b("OutputData: secret must be a non-empty Uint8Array");if(e17==null)throw new b("OutputData: blindedMessage is required");this.secret=n,this.blindingFactor=t2,this.blindedMessage=e17,this.ephemeralE=r}toProof(e17,n){if(e17==null)throw new b("Mint response is missing a signature for one of the outputs. Inputs may already be spent; if the wallet is seeded, try restoring (NUT-09) to recover.");if(!this.blindedMessage.amount.isZero()&&e17.id!==this.blindedMessage.id)throw new b(`Mint signature keyset id ${e17.id} does not match output ${this.blindedMessage.id}`);let i;e17.dleq&&(i={s:hexToBytes2(e17.dleq.s),e:hexToBytes2(e17.dleq.e),r:this.blindingFactor});let a=e17.amount.toString(),o=P(n.keys[a]);if(i){let t2=P(this.blindedMessage.B_),n2=P(e17.C_);if(!tr(i,t2,n2,o))throw new b("DLEQ verification failed on mint response")}let s=Ut({id:e17.id,C_:P(e17.C_)},this.blindingFactor,this.secret,o),c={id:e17.id,amount:e17.amount,C:s.C.toHex(true),secret:xe(s.secret),...i&&{dleq:{s:bytesToHex2(i.s),e:bytesToHex2(i.e),r:Ti(this.blindingFactor)}}};return this.ephemeralE&&(c.p2pk_e=this.ephemeralE),c}static createP2PKData(e17,t2,n,r){let i=B(t2,n.keys,r),a=e17.blindKeys&&e17.sigFlag==="SIG_ALL"?Rt():void 0;return i.map(t3=>this.createSingleP2PKData(e17,t3,n.id,a))}static createSingleP2PKData(n,r,a,o){let s=A.from(r),c=On(n),l=Array.isArray(c.pubkey)?c.pubkey:[c.pubkey],u=c.refundKeys??[],d=c.requiredSignatures??1,f=c.requiredRefundSignatures??1,p=c.hashlock,m=typeof p=="string"&&p.length>0,h=m?p:l[0],g=m?l:l.slice(1),_=u,v;if(n.blindKeys){let{blinded:e17,Ehex:t2}=vn([...l,...u],o,!m);m?g=e17.slice(0,l.length):(h=e17[0],g=e17.slice(1,l.length)),_=e17.slice(l.length),v=t2}let y=[],x2=c.locktime??NaN;if(Number.isSafeInteger(x2)&&x2>=0&&y.push(["locktime",String(x2)]),g.length>0&&(y.push(["pubkeys",...g]),d>1&&y.push(["n_sigs",String(d)])),_.length>0&&(y.push(["refund",..._]),f>1&&y.push(["n_sigs_refund",String(f)])),c.sigFlag=="SIG_ALL"&&y.push(["sigflag","SIG_ALL"]),c.additionalTags?.length){let e17=c.additionalTags.map(([e18,...t2])=>(Ya(e18),[e18,...t2.map(String)]));y.push(...e17)}let S2=[m?"HTLC":"P2PK",{nonce:bytesToHex2(randomBytes3(32)),data:h,tags:y}],C=JSON.stringify(S2),ee=[...C].length;if(ee>1024)throw new b(`Secret too long (${ee} characters), maximum is ${ce}`);let w=new TextEncoder().encode(C),{r:T2,B_:te2}=Vt(w);return new e15(new qa(s,te2,a).getSerializedBlindedMessage(),T2,w,v)}static createRandomData(e17,t2,n){return B(e17,t2.keys,n).map(e18=>this.createSingleRandomData(e18,t2.id))}static createSingleRandomData(n,r){let a=A.from(n),o=bytesToHex2(randomBytes3(32)),s=new TextEncoder().encode(o),{r:c,B_:l}=Vt(s);return new e15(new qa(a,l,r).getSerializedBlindedMessage(),c,s)}static createDeterministicData(e17,t2,n,r,i){let a=B(e17,r.keys,i),o=dr(t2,r.id);return a.map((e18,t3)=>Xa(e18,r.id,o(n+t3)))}static createSingleDeterministicData(e17,t2,n,r){return Xa(e17,r,ur(t2,r,n))}static sumOutputAmounts(e17){return A.sum(e17.map(e18=>e18.blindedMessage.amount))}static serialize(e17){return{blindedMessage:{amount:e17.blindedMessage.amount.toString(),B_:e17.blindedMessage.B_,id:e17.blindedMessage.id},blindingFactor:e17.blindingFactor.toString(),secret:bytesToHex2(e17.secret),...e17.ephemeralE&&{ephemeralE:e17.ephemeralE}}}static deserialize(t2){try{if(!/^(0|[1-9]\d*)$/.test(t2.blindingFactor))throw new b("blindingFactor must be a canonical decimal integer");let n=hexToBytes2(t2.secret);xe(n);let i=BigInt(t2.blindingFactor),{B_:a}=Vt(n,i);if(a.toHex(true)!==t2.blindedMessage.B_.toLowerCase())throw new b("stored output does not match its secret. Inputs may already be spent; if the wallet is seeded, try restoring (NUT-09) to recover.");return new e15({amount:A.from(t2.blindedMessage.amount),B_:t2.blindedMessage.B_,id:t2.blindedMessage.id},i,n,t2.ephemeralE?P(t2.ephemeralE).toHex(true):void 0)}catch(e17){throw new b(`Invalid SerializedOutputData: ${e17 instanceof Error?e17.message:String(e17)}`,{cause:e17})}}};function Xa(e17,n,r){let i=A.from(e17),a=bytesToHex2(r.secret),o=new TextEncoder().encode(a),{r:s,B_:c}=Vt(o,bytesToNumberBE(r.blindingFactor));return new Z(new qa(i,c,n).getSerializedBlindedMessage(),s,o)}var Mo;var No=class e16{constructor(e17,t2){this.tokenGeneration=0,this.sessionGeneration=0,this.tokens={},this.pool=[],this.desiredPoolSize=100,this.maxPerMint=100,this.mintUrl=e17,this.req=t2?.request??Fa,this.logger=t2?.logger??E;let n=Math.max(1,t2?.desiredPoolSize??this.desiredPoolSize),r=Math.max(1,t2?.maxPerMint??this.maxPerMint);this.desiredPoolSize=Math.min(n,100),this.maxPerMint=Math.min(r,100),this.desiredPoolSize!==n&&this.logger.warn("AuthManager: desiredPoolSize exceeds internal cap and was clamped",{configured:n,clampedTo:this.desiredPoolSize}),this.maxPerMint!==r&&this.logger.warn("AuthManager: maxPerMint exceeds internal cap and was clamped",{configured:r,clampedTo:this.maxPerMint})}attachOIDC(e17){return this.oidc&&this.oidcListener&&this.oidc.removeTokenListener(this.oidcListener),this.oidc&&this.oidc!==e17&&(this.tokens={}),this.tokenGeneration++,this.sessionGeneration++,this.oidc=e17,this.bindOIDC(),this}bindOIDC(){let e17=this.oidc;if(!e17)return;this.oidcListener&&e17.removeTokenListener(this.oidcListener);let t2=(n,r)=>{if(this.oidc!==e17||r==="refresh"&&this.oidcListener!==t2){this.logger.warn("AuthManager: ignoring tokens from an earlier session");return}this.updateFromOIDC(n,r)};this.oidcListener=t2,e17.addTokenListener(t2)}get poolSize(){return this.pool.length}get poolTarget(){return this.desiredPoolSize}get activeAuthKeysetId(){try{return this.keychain?.getCheapestKeyset().id}catch{return}}get hasCAT(){return!!this.tokens.accessToken}getCAT(){return this.tokens.accessToken}setCAT(e17){this.tokenGeneration++,this.sessionGeneration++,this.tokens={accessToken:e17},this.bindOIDC()}async ensureCAT(e17){if(this.validForAtLeast(e17)||!this.oidc||!this.tokens.refreshToken)return this.tokens.accessToken;if(this.inflightRefresh?.session!==this.sessionGeneration){let e18=this.tokenGeneration,t3=this.sessionGeneration,n=(async()=>{try{let t4=await this.oidc.refresh(this.tokens.refreshToken);this.tokenGeneration===e18&&this.updateFromOIDC(t4,"refresh")}catch(e19){this.logger.warn("AuthManager: CAT refresh failed",{err:e19})}})();this.inflightRefresh={session:t3,promise:n}}let t2=this.inflightRefresh;try{await t2.promise}finally{this.inflightRefresh===t2&&(this.inflightRefresh=void 0)}return this.validForAtLeast(0)?this.tokens.accessToken:void 0}validForAtLeast(t2=e16.MIN_VALID_SECS){let{accessToken:n,expiresAt:r}=this.tokens;return n?r?Date.now()+t2*1e3<r:true:false}updateFromOIDC(e17,t2){if(!e17.access_token)return;this.tokenGeneration++,t2==="signin"&&this.sessionGeneration++;let n=Date.now();if(this.tokens.accessToken=e17.access_token,this.tokens.refreshToken=e17.refresh_token||(t2==="refresh"?this.tokens.refreshToken:void 0),typeof e17.expires_in=="number"&&e17.expires_in>0)this.tokens.expiresAt=n+e17.expires_in*1e3;else{let t3=this.parseJwtExpSec(e17.access_token);this.tokens.expiresAt=t3?t3*1e3:void 0}this.bindOIDC(),this.logger.debug("AuthManager: OIDC tokens updated",{expiresAt:this.tokens.expiresAt})}async ensure(e17){if(await this.init(),this.pool.length>=e17)return;let t2=Math.max(this.desiredPoolSize,e17),n=this.getBatMaxMint(),r=Math.min(t2-this.pool.length,n);r<=0||await this.topUp(r)}async getBlindAuthToken({method:e17,path:t2}){return this.info&&!this.info.requiresBlindAuthToken(e17,t2)&&this.logger.warn("Endpoint is not marked as protected by NUT-22; still issuing BAT",{method:e17,path:t2}),this.withLock(async()=>{if(await this.ensure(1),this.pool.length===0)throw new b("AuthManager: no BATs available and minting failed");let n=this.pool.pop();return this.logger.debug("AuthManager: BAT requested",{method:e17,path:t2,remaining:this.pool.length}),Po(n)})}importPool(e17,t2="replace"){t2==="replace"&&(this.pool=[]);let n=new Map(this.pool.map(e18=>[e18.secret,e18]));for(let t3 of e17)!t3||!t3.secret||!t3.C||!t3.id||n.has(t3.secret)||(this.pool.push(t3),n.set(t3.secret,t3))}exportPool(){return this.pool.map(e17=>({...e17,dleq:e17.dleq?{...e17.dleq}:void 0}))}parseJwtExpSec(e17){if(!e17)return;let t2=e17.split(".");if(t2.length===3)try{let e18=new TextDecoder("utf-8").decode(Xe(t2[1])),n=JSON.parse(e18),r=typeof n.exp=="number"?n.exp:Number(n.exp);if(Number.isFinite(r)&&r>0)return r}catch{this.logger.warn("JWT access token was malformed.")}}async withLock(e17){let t2=this.lockChain??Promise.resolve(),n,r=new Promise(e18=>{n=e18}),i=t2.then(()=>r);this.lockChain=i;try{return await t2,await e17()}finally{n(),this.lockChain===i&&(this.lockChain=void 0)}}async init(){if(!this.info){let e17=await this.req({endpoint:G(this.mintUrl,"/v1/info"),method:"GET",logger:this.logger});this.info=new Y(e17,this.logger)}if(!this.keychain){let[e17,t2]=await Promise.all([this.req({endpoint:G(this.mintUrl,"/v1/auth/blind/keysets"),method:"GET",logger:this.logger}),this.req({endpoint:G(this.mintUrl,"/v1/auth/blind/keys"),method:"GET",logger:this.logger})]);if(!Array.isArray(e17.keysets)||!Array.isArray(t2.keysets))throw new b("AuthManager: mint returned malformed auth keysets");if(e17.keysets.length>1e4||t2.keysets.length>1e4)throw new b("AuthManager: mint returned more auth keysets than can be processed");let n=e17.keysets.map(e18=>ra(e18)),r=t2.keysets.map(e18=>ia(e18)),i=Ka.mintToCacheDTO(this.mintUrl,n,r);this.keychain=Ka.fromCache(this.mintUrl,"auth",i),this.keychain.getCheapestKeyset()}}getBatMaxMint(){if(!this.info)throw new b("AuthManager: mint info not loaded");let e17=this.info.nuts[22],t2=J(e17?.bat_max_mint,"nuts.22.bat_max_mint",this.maxPerMint);return Math.max(1,Math.min(this.maxPerMint,t2))}getActiveKeys(){if(!this.keychain)throw new b("AuthManager: keyset not loaded for active keyset");return this.keychain.getCheapestKeyset()}async topUp(e17){if(!this.info)throw new b("AuthManager: mint info not loaded");let t2=this.info.requiresClearAuthToken("POST","/v1/auth/blind/mint"),n=this.sessionGeneration,r;if(t2){if(r=await this.ensureCAT(),this.sessionGeneration!==n)throw new b("AuthManager: session changed while obtaining BATs");if(!r)throw new b("AuthManager: Clear-auth token required for /v1/auth/blind/mint but not available. Authenticate with the mint to obtain a CAT first.")}let i=this.getActiveKeys(),a=Z.createRandomData(e17,i),o={outputs:a.map(e18=>e18.blindedMessage)},s={};r&&(s["Clear-auth"]=r);let c=await this.req({endpoint:G(this.mintUrl,"/v1/auth/blind/mint"),method:"POST",headers:s,...r?{redirect:"error"}:{},requestBody:o,logger:this.logger});if(!Array.isArray(c?.signatures)||c.signatures.length!==a.length)throw new b("AuthManager: bad BAT mint response");let l=c.signatures.map(e18=>({...e18,amount:A.from(e18.amount)})),u=a.map((e18,t3)=>e18.toProof(l[t3],i));for(let e18 of u)if(!Ji(e18,i))throw new b("AuthManager: mint returned BAT with invalid DLEQ");if(t2&&this.sessionGeneration!==n)throw new b("AuthManager: session changed while obtaining BATs");this.pool.push(...u),this.logger.debug("AuthManager: performed topUp",{minted:u.length,pool:this.pool.length})}};Mo=No,Mo.MIN_VALID_SECS=30;function Po(e17){return`authA${Ye(utf8ToBytes3(JSON.stringify({id:e17.id,secret:e17.secret,C:e17.C})))}`}import{computeSmartDenominations,getWallet,lookupInvoice,maxKeysetDenomination,missingDleqRecoveryDiagnostic,NwcError,parseNwcUri,payInvoiceReconciling,prepareP2PKMint,restoreProofsFromOutputs,serializeOutputData,swapFeeForProofs,toLockPubkey as toLockPubkey2}from"@dvmkit/sdk/internal";import{DRAIN_DELIVERY_RESERVE_SATS}from"@dvmkit/sdk/server";init_defaults();import{appendFileSync as appendFileSync2,chmodSync as chmodSync6,existsSync as existsSync11,mkdirSync as mkdirSync9,readFileSync as readFileSync11,writeFileSync as writeFileSync9}from"fs";function appendSwapped(entry){appendEntry2({...entry,kind:"swapped",ts:Date.now()})}function appendParked(entry){appendEntry2({...entry,kind:"parked",ts:Date.now()})}function appendMintQuote(entry){appendEntry2({...entry,kind:"mint_quote",ts:Date.now()})}function appendMintPaid(entry){appendEntry2({...entry,kind:"mint_paid",ts:Date.now()})}function appendMintPaymentAttempt(entry){appendEntry2({...entry,kind:"mint_payment_attempt",ts:Date.now()})}function appendMintPaymentRejected(entry){appendEntry2({...entry,kind:"mint_payment_rejected",ts:Date.now()})}function appendMintOutputs(entry){appendEntry2({...entry,kind:"mint_outputs",ts:Date.now()})}function appendMintAbandoned(entry){appendEntry2({...entry,kind:"mint_abandoned",ts:Date.now()})}function readUnparked(dvmId){return scan(dvmId).unparked}function readOpenMintQuotes(dvmId){return scan(dvmId).openQuotes}function scan(dvmId){if(!existsSync11(DRAIN_PARK_LOG_FILE))return{unparked:[],openQuotes:[]};const raw2=readFileSync11(DRAIN_PARK_LOG_FILE,"utf-8");const swapped=new Map;const parked=new Set;const quotes=new Map;const paid=new Map;const paymentRejected=new Map;const outputs=new Map;const abandoned=new Set;for(const line of raw2.split("\n")){if(!line)continue;let entry;try{entry=JSON.parse(line)}catch{continue}if(entry.dvm_id!==dvmId)continue;const key=`${entry.dvm_id}|${entry.credit_id}|${entry.drain_id}`;switch(entry.kind){case"swapped":swapped.set(key,entry);break;case"parked":parked.add(key);break;case"mint_quote":quotes.set(key,entry);break;case"mint_paid":paid.set(key,entry);break;case"mint_payment_attempt":if(paymentRejected.get(key)?.quote_id===entry.quote_id)paymentRejected.delete(key);break;case"mint_payment_rejected":paymentRejected.set(key,entry);break;case"mint_outputs":outputs.set(key,entry);break;case"mint_abandoned":abandoned.add(`${key}|${entry.quote_id}`);break}}const openQuotes=[];for(const[key,quote]of quotes){if(parked.has(key)||swapped.has(key)||abandoned.has(`${key}|${quote.quote_id}`))continue;const paidEntry=paid.get(key);const paymentRejectedEntry=paymentRejected.get(key);const outputsEntry=outputs.get(key);openQuotes.push({quote,...paidEntry?.quote_id===quote.quote_id?{paid:paidEntry}:{},...paymentRejectedEntry?.quote_id===quote.quote_id?{paymentRejected:paymentRejectedEntry}:{},...outputsEntry?.quote_id===quote.quote_id?{outputs:outputsEntry}:{}})}return{unparked:[...swapped.entries()].filter(([k2])=>!parked.has(k2)).map(([,e17])=>e17),openQuotes}}function appendEntry2(entry){if(!existsSync11(BUILDER_CONFIG_DIR)){mkdirSync9(BUILDER_CONFIG_DIR,{recursive:true,mode:448})}if(!existsSync11(DRAIN_PARK_LOG_FILE)){writeFileSync9(DRAIN_PARK_LOG_FILE,"",{mode:384})}else{chmodSync6(DRAIN_PARK_LOG_FILE,384)}appendFileSync2(DRAIN_PARK_LOG_FILE,JSON.stringify(entry)+"\n")}function bolt11AmountMsats(bolt11){const trimmed=bolt11.trim();const separator=trimmed.lastIndexOf("1");if(separator<=0)return null;const match=/^ln(?:bcrt|bc|tbs|tb|sb)(\d+)([munp])?$/i.exec(trimmed.slice(0,separator));if(!match)return null;const digits=Number(match[1]);if(!Number.isFinite(digits))return null;const multiplier=match[2]?.toLowerCase()??"";switch(multiplier){case"m":return digits*1e8;case"u":return digits*1e5;case"n":return digits*100;case"p":return Math.round(digits/10);default:return digits*1e11}}async function serviceDrains(ctx){const summary={fetched:false,drains_seen:0,drains_parked:0,drains_jit_minted:0,drains_failed:0,drains_queued:0,drains_manual:0,drains_channel:0,recovered:0,cashu_liability_sats_after:0};const recovery=new Map;summary.recovered+=await recoverParks(ctx,summary,recovery);await recoverMintQuotes(ctx,summary,recovery);let pending3;try{pending3=await ctx.client.getPendingDrains()}catch(err){rethrowIfBadSignature(err);rethrowIfAdminStateUnavailable(err);if(isMissingDrainSurface(err)){return{...summary,fetched:true}}logDrain(ctx,"drain_pending_fetch_failed",{error:err instanceof Error?err.message:String(err)});return summary}summary.fetched=true;summary.drains_seen=pending3.drains.length;const stillPending=new Set((await refreshedPendingIds(ctx,pending3.drains,summary)).map(d=>`${d.credit_id}|${d.drain_id}`));let cashuOutstandingSats=0;for(const drain of pending3.drains){if(!stillPending.has(`${drain.credit_id}|${drain.drain_id}`))continue;if(drain.method==="cashu"){const key=`${drain.credit_id}|${drain.drain_id}`;const recovered=recovery.get(key);if(recovered==="resolved"){continue}if(recovered){if(recovered==="failed")summary.drains_failed++;else summary.drains_queued++;cashuOutstandingSats+=drain.amount_sats??0;continue}const outcome=await parkOne(ctx,drain,pending3.mints??[]);if(outcome==="parked"||outcome==="jit_minted"){summary.drains_parked++;if(outcome==="jit_minted")summary.drains_jit_minted++}else{if(outcome==="queued")summary.drains_queued++;else summary.drains_failed++;cashuOutstandingSats+=drain.amount_sats??0}}else if(drain.settlement==="channel"){summary.drains_channel++;logDrain(ctx,"drain_channel_settlement_pending",{credit_id:drain.credit_id,drain_id:drain.drain_id,method:drain.method,channel_id:drain.channel_id,amount_micro:drain.amount_micro,hint:"Usually nothing to do \u2014 the caller's channel close settles this one, and their next drain poll finishes the reconciliation. It is not on `dvmctl credit drains-owed`. The exception is a Tempo close that landed on chain and refunded less than the ledger extinguished: that one never clears on a poll, and `dvmctl credit tempo-wedged` is where it shows up (tracked change)."})}else{summary.drains_manual++;logDrain(ctx,"drain_manual_settlement_required",{credit_id:drain.credit_id,drain_id:drain.drain_id,method:drain.method,payout:drain.payout,amount_micro:drain.amount_micro,amount_native:drain.amount_native,hint:`No builder-held on-chain send keys exist; send this refund yourself and record it with \`dvmctl credit drain-settle ${ctx.handle} ${drain.credit_id} ${drain.drain_id} --tx <hash>\`. \`dvmctl credit drains-owed ${ctx.handle}\` lists everything outstanding.`})}}summary.cashu_liability_sats_after=cashuOutstandingSats;return summary}async function recoverParks(ctx,summary,recovery){const unparked=readUnparked(ctx.dvmId);let recovered=0;for(const entry of unparked){const key=`${entry.credit_id}|${entry.drain_id}`;recovery.set(key,"queued");try{await ctx.client.parkDrain({credit_id:entry.credit_id,drain_id:entry.drain_id,token:entry.token,consumed_row_ids:entry.consumed_row_ids,keep_proofs:entry.keep_proofs,...entry.mint_evidence?{mint_evidence:entry.mint_evidence}:{}});appendParked({dvm_id:ctx.dvmId,credit_id:entry.credit_id,drain_id:entry.drain_id});recovered++;recovery.set(key,"resolved");if(entry.mint_evidence)summary.drains_jit_minted++;logDrain(ctx,"drain_park_recovered",{credit_id:entry.credit_id,drain_id:entry.drain_id})}catch(err){rethrowIfAdminStateUnavailable(err);logDrain(ctx,"drain_park_recovery_failed",{credit_id:entry.credit_id,drain_id:entry.drain_id,error:err instanceof Error?err.message:String(err)})}}return recovered}async function refreshedPendingIds(ctx,drains,summary){if(summary.recovered===0)return drains;try{const fresh=await ctx.client.getPendingDrains();return fresh.drains}catch(err){rethrowIfAdminStateUnavailable(err);return drains}}async function parkOne(ctx,drain,mints){const amountSats=drain.amount_sats;const refundPubkey=drain.payout.refund_pubkey;if(!amountSats||amountSats<=0||!refundPubkey){logDrain(ctx,"drain_park_unpriceable",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats});return"failed"}let batches;try{batches=(await ctx.client.getPendingBatches()).batches}catch(err){rethrowIfAdminStateUnavailable(err);logDrain(ctx,"drain_park_batches_fetch_failed",{error:err instanceof Error?err.message:String(err)});return"failed"}const jitAvailable=ctx.refundNwc!==void 0;const selected=await selectCoveringBatch(ctx,drain,amountSats,batches,jitAvailable);if(!selected){return jitMintOne(ctx,drain,amountSats,refundPubkey,mints)}const{batch,wallet,inputProofs,keypair}=selected;let send;let keep;try{const result=await wallet.ops.send(amountSats,inputProofs).asLocked({pubkey:refundPubkey}).keepAsLocked({pubkey:batch.lock_pubkey}).privkey(keypair.privkey).includeFees(false).run();send=result.send;keep=result.keep}catch(err){const recoveryDiagnostic=missingDleqRecoveryDiagnostic(inputProofs,err);logDrain(ctx,"drain_swap_failed",{credit_id:drain.credit_id,drain_id:drain.drain_id,mint_url:batch.mint_url,error:err instanceof Error?err.message:String(err),...recoveryDiagnostic?{recovery:recoveryDiagnostic}:{}});return"failed"}const inputIndexBySecret=new Map(batch.proofs.map((p,i)=>[p.secret,i]));const untouchedInputs=new Set;const change=[];for(const p of keep){const index=inputIndexBySecret.get(p.secret);if(index===void 0)change.push(p);else untouchedInputs.add(index)}const consumedRowIds=batch.row_ids.filter((_,i)=>!untouchedInputs.has(i));const keepProofs=change.map(p=>({id:p.id,amount:amountForJson(p.amount),secret:p.secret,C:p.C,...p.dleq?{dleq:{...p.dleq}}:{}}));if(consumedRowIds.length===0){logDrain(ctx,"drain_park_no_consumed_rows",{credit_id:drain.credit_id,drain_id:drain.drain_id,mint_url:batch.mint_url,batch_rows:batch.row_ids.length});return"failed"}const encoded=ki({mint:batch.mint_url,proofs:rehydrateLocalProofs(send)});appendSwapped({dvm_id:ctx.dvmId,credit_id:drain.credit_id,drain_id:drain.drain_id,token:encoded,consumed_row_ids:consumedRowIds,keep_proofs:keepProofs});try{await ctx.client.parkDrain({credit_id:drain.credit_id,drain_id:drain.drain_id,token:encoded,consumed_row_ids:consumedRowIds,keep_proofs:keepProofs})}catch(err){rethrowIfAdminStateUnavailable(err);logDrain(ctx,"drain_park_post_failed",{credit_id:drain.credit_id,drain_id:drain.drain_id,error:err instanceof Error?err.message:String(err)});return"failed"}appendParked({dvm_id:ctx.dvmId,credit_id:drain.credit_id,drain_id:drain.drain_id});logDrain(ctx,"drain_parked",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats,mint_url:batch.mint_url});return"parked"}async function jitMintOne(ctx,drain,amountSats,refundPubkey,mints){const ids={credit_id:drain.credit_id,drain_id:drain.drain_id};if(!ctx.refundNwc){logDrain(ctx,"drain_jit_unconfigured",{...ids,amount_sats:amountSats,display:"This refund needs sats bought from the hub, and no send wallet is configured to buy them.",hint:"Pass `--refund-nwc <wallet connection URI>` (or set DVMKIT_REFUND_NWC_URL) with a send-capable NWC connection on the wallet holding your Bitcoin deposits. The refund waits, visible in `dvmctl credit drains-owed`, until one is wired."});return"queued"}const keypair=ctx.currentKeypair;if(!keypair){logDrain(ctx,"drain_jit_no_lock_key",{...ids,display:"This refund needs to be minted, and no current builder lock key was resolved to sign the mint quote.",hint:"The mint quote is locked to your builder key (NUT-20) so nobody else can redeem the invoice you pay for. Check `~/.dvmkit/builder.mnemonic` is present and that this DVM is registered in `~/.dvmkit/builder.json`."});return"queued"}let conn;try{conn=parseNwcUri(ctx.refundNwc.uri)}catch(err){logDrain(ctx,"drain_jit_nwc_invalid",{...ids,error:err instanceof Error?err.message:String(err),display:"The refund send wallet's connection string could not be read, so nothing was paid.",hint:"Re-copy the `wallet connection URI` URI from the wallet that holds your Bitcoin deposits. The refund stays owed and retries on the next tick."});return"queued"}const tried=[];for(const mintUrl of mints){tried.push(mintUrl);let wallet;let quote;try{wallet=await(ctx.walletProvider??getWallet)(mintUrl);quote=await wallet.createLockedMintQuote(amountSats,keypair.pubkey)}catch(err){logDrain(ctx,"drain_jit_quote_failed",{...ids,mint_url:mintUrl,amount_sats:amountSats,error:err instanceof Error?err.message:String(err)});continue}const invoiceMsats=bolt11AmountMsats(quote.request);const ceilingMsats=(amountSats+DRAIN_DELIVERY_RESERVE_SATS)*1e3;if(invoiceMsats===null||invoiceMsats>ceilingMsats){logDrain(ctx,"drain_jit_quote_refused",{...ids,mint_url:mintUrl,quote_id:quote.quote,reason:invoiceMsats===null?"invoice_unreadable":"above_ceiling",face_sats:amountSats,invoice_msats:invoiceMsats,ceiling_msats:ceilingMsats,display:invoiceMsats===null?`${mintUrl} asked for this refund's ecash with an invoice whose amount could not be read, so nothing was paid.`:`${mintUrl} wants more for this refund's ecash than the refund is worth, so nothing was paid.`,hint:"Nothing left the wallet, and the unpaid quote simply expires at the mint. Another accepted mint is tried next; if every one of them is refused this way, check the mints' own fee settings before adding one that is cheaper."});continue}const entry={dvm_id:ctx.dvmId,credit_id:drain.credit_id,drain_id:drain.drain_id,mint_url:mintUrl,quote_id:quote.quote,bolt11:quote.request,invoice_msats:invoiceMsats,face_sats:amountSats,reserve_sats:DRAIN_DELIVERY_RESERVE_SATS,expires_at:quote.expiry??null,refund_pubkey:refundPubkey};appendMintQuote(entry);logDrain(ctx,"drain_jit_quoted",{...ids,mint_url:mintUrl,quote_id:quote.quote,face_sats:amountSats,invoice_msats:entry.invoice_msats});return advanceMintQuote(ctx,conn,keypair,{quote:{...entry,kind:"mint_quote",ts:Date.now()}})}logDrain(ctx,"drain_jit_no_mint",{...ids,amount_sats:amountSats,mints_tried:tried,display:tried.length===0?"This refund has to be bought at a Cashu mint and this DVM has none configured, so nothing could be minted.":"No accepted mint would quote for this refund, so nothing was bought and nothing was paid.",hint:tried.length===0?"Set DVMKIT_CASHU_MINTS on the DVM. A non-channel Bitcoin refund is P2PK-locked ecash and nothing else, so without a mint there is no shape it can take.":`Each mint's own error is on the \`drain_jit_quote_failed\` line above it. The refund stays owed and retries every tick \u2014 nothing here needs undoing, and no payment was attempted.`});return"queued"}async function advanceMintQuote(ctx,conn,keypair,open){const entry=open.quote;const refundPubkey=entry.refund_pubkey;const ids={credit_id:entry.credit_id,drain_id:entry.drain_id};const base3={...ids,mint_url:entry.mint_url,quote_id:entry.quote_id};let wallet;try{wallet=await(ctx.walletProvider??getWallet)(entry.mint_url)}catch(err){logDrain(ctx,"drain_jit_mint_unreachable",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint holding this refund's quote is not answering, so the refund is still on its way.",hint:"Nothing is lost and nothing needs undoing \u2014 the quote is recorded and the next tick picks it up where it left off. If the mint stays down, its own status page is the place to look."});return"queued"}let paid=Boolean(open.paid);let feesPaidMsats=open.paid?.fees_paid_msats??null;let checked;if(!paid){if(quoteDead(entry)){appendMintAbandoned({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id,reason:"quote_expired_unpaid"});logDrain(ctx,"drain_jit_quote_abandoned",{...base3,reason:"quote_expired_unpaid",display:"The mint's quote for this refund ran out before it could be paid, so it was dropped unpaid.",hint:"Nothing left the wallet \u2014 the refund is still owed and the next tick asks for a fresh quote. If this repeats, the wallet is the place to look: an exhausted budget or an empty balance keeps a quote from being paid until it expires."});return"queued"}appendMintPaymentAttempt({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id});try{const outcome=await(ctx.payInvoice??payInvoiceReconciling)(conn,entry.bolt11);paid=true;feesPaidMsats=outcome.feesPaidMsats??null;appendMintPaid({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id,preimage:outcome.preimage,...outcome.feesPaidMsats!==void 0?{fees_paid_msats:outcome.feesPaidMsats}:{},...outcome.outcome==="paid"?{}:{recovered:true}});logDrain(ctx,"drain_jit_invoice_paid",{...base3,pay_outcome:outcome.outcome,invoice_msats:entry.invoice_msats,fees_paid_msats:outcome.feesPaidMsats??null})}catch(err){const code=err instanceof NwcError?err.code:"pay_failed";const definitivelyRejected=err instanceof NwcError&&err.method==="pay_invoice"&&code.toLowerCase()!=="payment_unknown";if(definitivelyRejected){appendMintPaymentRejected({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id,error_code:code})}logDrain(ctx,code==="payment_unknown"?"drain_jit_payment_unknown":"drain_jit_payment_failed",{...base3,error_code:code,error:err instanceof Error?err.message:String(err),display:code==="payment_unknown"?"The wallet buying this refund never answered, so we cannot yet say whether the payment went out.":"The wallet could not pay for this refund's ecash, so no money left and the refund is still owed.",hint:code==="payment_unknown"?"Nothing is retried until this resolves \u2014 the next tick asks the wallet about this exact invoice, so it cannot be paid twice. Check the wallet is online and reachable over its relays.":"The wallet's own error is on this line. A balance too low or a budget exhausted are the usual two; the same invoice is retried on the next tick once the wallet can pay it."});return"queued"}}try{checked=await wallet.checkMintQuoteBolt11(entry.quote_id)}catch(err){logDrain(ctx,"drain_jit_quote_state_failed",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint would not say whether it has been paid for this refund yet, so it stays in flight.",hint:"The payment is recorded, so nothing is re-sent. The next tick asks again."});return"queued"}let proofs;if(checked.state===sa.ISSUED){if(!open.outputs){logDrain(ctx,"drain_jit_issued_unrecoverable",{...base3,display:"This refund's ecash was already issued by the mint, but this machine has no record of the outputs needed to collect it.",hint:"Do not re-run the refund \u2014 the drain is deliberately held so it cannot be bought twice. This means another host minted the same quote, or `~/.dvmkit/drain-park.log` lost a line. Check for a second worker against this DVM before doing anything else."});return"failed"}try{proofs=await restoreProofsFromOutputs(wallet,open.outputs.keyset_id,open.outputs.outputs)}catch(err){logDrain(ctx,"drain_jit_restore_failed",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint has this refund's ecash and would not hand back the signatures for it this time.",hint:"The outputs are on disk, so this is recoverable \u2014 the next tick asks the mint again. Nothing was paid twice."});return"queued"}logDrain(ctx,"drain_jit_restored",{...base3,proofs:proofs.length})}else if(checked.state===sa.PAID){const denominations=computeSmartDenominations(entry.face_sats,{maxDenomination:maxKeysetDenomination(wallet),includeTinyTail:false});let preview;try{preview=await prepareP2PKMint(wallet,entry.face_sats,checked,keypair.privkey,refundPubkey,denominations)}catch(err){logDrain(ctx,"drain_jit_prepare_failed",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint has been paid for this refund but would not prepare the notes this time.",hint:"The payment stands and is not repeated \u2014 the next tick prepares them again."});return"queued"}const previewKeysetId=preview.outputData[0]?.blindedMessage.id;if(!previewKeysetId||preview.outputData.some(output=>output.blindedMessage.id!==previewKeysetId)){logDrain(ctx,"drain_jit_prepare_failed",{...base3,error:"The prepared Cashu outputs do not share one keyset.",display:"The mint has been paid for this refund but returned malformed note metadata this time.",hint:"The payment stands and is not repeated \u2014 the next tick prepares the notes again."});return"queued"}appendMintOutputs({dvm_id:ctx.dvmId,...ids,quote_id:entry.quote_id,keyset_id:previewKeysetId,outputs:serializeOutputData(preview.outputData)});try{proofs=await wallet.completeMint(preview)}catch(err){logDrain(ctx,"drain_jit_mint_failed",{...base3,error:err instanceof Error?err.message:String(err),display:"The mint has been paid for this refund and did not return the notes, so it is still in flight.",hint:"The blinded outputs are recorded, so the next tick can collect the same notes from the mint \u2014 nothing is bought twice."});return"queued"}}else{if(quoteExpired(checked)){logDrain(ctx,"drain_jit_quote_expired_paid",{...base3,invoice_msats:entry.invoice_msats,display:"The hub paid for this refund's ecash and the mint's quote expired before it credited the payment.",hint:`Do not re-run the refund \u2014 the drain is held so it cannot be bought twice. Ask ${entry.mint_url} about quote ${entry.quote_id}; the payment either sits with them or was returned by Lightning. Settle it there, then remove this quote's lines from \`~/.dvmkit/drain-park.log\` to release the drain.`});return"failed"}logDrain(ctx,"drain_jit_awaiting_credit",{...base3,quote_state:checked.state,display:"The hub has paid for this refund's ecash and the mint has not credited the payment yet.",hint:"Ordinary for a moment after a Lightning payment. The next tick collects the notes; nothing is paid again in the meantime."});return"queued"}const evidence={source:"jit_mint",mint_url:entry.mint_url,quote_id:entry.quote_id,face_sats:entry.face_sats,reserve_sats:entry.reserve_sats,invoice_msats:entry.invoice_msats,routing_fee_msats:feesPaidMsats};const encoded=ki({mint:entry.mint_url,proofs:rehydrateLocalProofs(proofs)});appendSwapped({dvm_id:ctx.dvmId,...ids,token:encoded,consumed_row_ids:[],keep_proofs:[],mint_evidence:evidence});try{await ctx.client.parkDrain({...ids,token:encoded,consumed_row_ids:[],keep_proofs:[],mint_evidence:evidence})}catch(err){rethrowIfAdminStateUnavailable(err);logDrain(ctx,"drain_park_post_failed",{...base3,error:err instanceof Error?err.message:String(err)});return"queued"}appendParked({dvm_id:ctx.dvmId,...ids});logDrain(ctx,"drain_jit_parked",{...base3,face_sats:entry.face_sats,reserve_sats:entry.reserve_sats,invoice_msats:entry.invoice_msats,routing_fee_msats:feesPaidMsats,reserve_remainder_msats:entry.reserve_sats*1e3-deliveryCostMsats(entry,feesPaidMsats)});return"jit_minted"}var MINT_QUOTE_STALE_MS=24*60*60*1e3;function quoteDead(entry){if(entry.expires_at!==null)return entry.expires_at*1e3<Date.now();return Date.now()-entry.ts>MINT_QUOTE_STALE_MS}function quoteExpired(quote){return typeof quote.expiry==="number"&"e.expiry*1e3<Date.now()}function deliveryCostMsats(entry,routingFeeMsats){return entry.invoice_msats-entry.face_sats*1e3+(routingFeeMsats??0)}async function recoverMintQuotes(ctx,summary,recovery){const open=readOpenMintQuotes(ctx.dvmId);if(open.length===0)return;const keypair=ctx.currentKeypair;let conn;if(ctx.refundNwc){try{conn=parseNwcUri(ctx.refundNwc.uri)}catch{conn=void 0}}for(const item of open){const key=`${item.quote.credit_id}|${item.quote.drain_id}`;recovery.set(key,"queued");if(!conn||!keypair){logDrain(ctx,"drain_jit_recovery_unconfigured",{credit_id:item.quote.credit_id,drain_id:item.quote.drain_id,quote_id:item.quote.quote_id,display:"A refund purchase from a previous run is unfinished and cannot be checked without the send wallet.",hint:"Re-wire `--refund-nwc` (or DVMKIT_REFUND_NWC_URL) before the next tick. The refund is deliberately held until then, because the earlier payment may already have gone out."});continue}let carried=item;if(!item.paid){const settled=await reconcileQuotePayment(ctx,conn,item.quote,item.paymentRejected);if(settled==="unknown")continue;if(settled!=="unpaid")carried={...item,paid:settled}}const outcome=await advanceMintQuote(ctx,conn,keypair,carried);if(outcome==="jit_minted"){summary.recovered++;summary.drains_jit_minted++;recovery.set(key,"resolved")}else if(outcome==="failed"){recovery.set(key,"failed")}}}async function reconcileQuotePayment(ctx,conn,entry,paymentRejected){const base3={credit_id:entry.credit_id,drain_id:entry.drain_id,quote_id:entry.quote_id,mint_url:entry.mint_url};let tx;try{tx=await(ctx.lookupInvoiceImpl??lookupInvoice)(conn,{invoice:entry.bolt11})}catch(err){const code=err instanceof NwcError?err.code:"lookup_failed";if(code==="NOT_FOUND"){logDrain(ctx,"drain_jit_payment_never_sent",base3);return"unpaid"}logDrain(ctx,"drain_jit_recovery_lookup_failed",{...base3,error_code:code,error:err instanceof Error?err.message:String(err),display:"A refund purchase from a previous run could not be checked, so it is being left alone.",hint:"Nothing is re-sent while this is unanswered \u2014 that is what stops a refund being bought twice. The next tick asks the wallet again."});return"unknown"}if(tx.settledAt){const paid={dvm_id:ctx.dvmId,credit_id:entry.credit_id,drain_id:entry.drain_id,quote_id:entry.quote_id,preimage:tx.preimage??"",...tx.feesPaidMsats!==void 0?{fees_paid_msats:tx.feesPaidMsats}:{},recovered:true};appendMintPaid(paid);logDrain(ctx,"drain_jit_payment_recovered",{...base3,fees_paid_msats:tx.feesPaidMsats??null});return{...paid,kind:"mint_paid",ts:Date.now()}}if(tx.expiresAt&&tx.expiresAt*1e3<Date.now()){logDrain(ctx,"drain_jit_payment_expired_unpaid",base3);return"unpaid"}if(paymentRejected){logDrain(ctx,"drain_jit_payment_retrying",{...base3,error_code:paymentRejected.error_code,display:"The wallet rejected the previous attempt and confirms this refund invoice is still unpaid, so the same invoice is being retried.",hint:"No new mint quote was opened. If the wallet rejects this attempt too, its error is reported and the same safe check runs again next tick."});return"unpaid"}logDrain(ctx,"drain_jit_payment_in_flight",{...base3,display:"A refund purchase from a previous run is still in flight, so nothing new was attempted for it.",hint:"The refund is held until the wallet reports one way or the other \u2014 that is what keeps it from being paid for twice."});return"unknown"}function rehydrateLocalProofs(proofs){return proofs.map(proof=>({...proof,amount:localAmount(proof.amount)}))}function amountForJson(amount2){return localAmount(amount2).toNumber()}function localAmount(amount2){if(typeof amount2==="number"||typeof amount2==="bigint"||typeof amount2==="string"){return A.from(amount2)}if(amount2&&typeof amount2==="object"&&"toBigInt"in amount2){const toBigInt3=amount2.toBigInt;if(typeof toBigInt3==="function"){const value=toBigInt3.call(amount2);if(typeof value==="bigint")return A.from(value)}}throw new TypeError("Cashu proof amount must be a primitive AmountLike or expose toBigInt()")}async function selectCoveringBatch(ctx,drain,amountSats,batches,jitAvailable){const nextStep=jitAvailable?"The refund is minted just in time from the hub instead \u2014 see the `drain_jit_*` lines below.":"";let closestShortfall;const unpriceableMints=new Set;for(const batch of batches){const keypair=ctx.keypairsByPubkey.get(toLockPubkey2(batch.lock_pubkey));if(!keypair)continue;if(batch.total_sats<amountSats)continue;let wallet;let inputProofs;let reserveSats;try{wallet=await(ctx.walletProvider??getWallet)(batch.mint_url);inputProofs=batch.proofs.map(p=>({id:p.id,amount:p.amount,secret:p.secret,C:p.C,...p.dleq?{dleq:{...p.dleq}}:{}}));reserveSats=swapFeeForProofs(wallet,inputProofs)}catch(err){unpriceableMints.add(batch.mint_url);logDrain(ctx,"drain_park_batch_unpriceable",{credit_id:drain.credit_id,drain_id:drain.drain_id,mint_url:batch.mint_url,error:err instanceof Error?err.message:String(err)});continue}const requiredSats=amountSats+reserveSats;if(batch.total_sats>=requiredSats)return{batch,wallet,inputProofs,keypair};if(!closestShortfall||requiredSats-batch.total_sats<closestShortfall.requiredSats-closestShortfall.batch.total_sats){closestShortfall={batch,requiredSats}}}if(closestShortfall){const{batch,requiredSats}=closestShortfall;const shortBySats=requiredSats-batch.total_sats;logDrain(ctx,"drain_park_batch_below_swap_cost",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats,mint_url:batch.mint_url,total_sats:batch.total_sats,required_sats:requiredSats,short_by_sats:shortBySats,batches_seen:batches.length,unpriceable_mints:[...unpriceableMints],hint:`A batch at ${batch.mint_url} holds ${batch.total_sats} sats, which covers the ${amountSats}-sat refund but not the ${requiredSats-amountSats} sats that mint charges to swap it. ${nextStep||`It parks automatically once ${shortBySats} more sats land on that lock key; to intervene, fund the DVM or settle manually.`}`});return void 0}if(unpriceableMints.size>0){const mints=[...unpriceableMints];logDrain(ctx,"drain_park_no_priceable_batch",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats,batches_seen:batches.length,unpriceable_mints:mints,hint:`No accumulator batch could be priced: ${mints.join(", ")} would not answer for its keyset, so the refund's swap cost is unknown. This is a mint problem, not a funding one${nextStep?`. ${nextStep}`:" \u2014 the drain retries on the next tick"}, and the per-batch \`drain_park_batch_unpriceable\` lines carry each mint's error.`});return void 0}logDrain(ctx,"drain_park_insufficient_batch",{credit_id:drain.credit_id,drain_id:drain.drain_id,amount_sats:amountSats,batches_seen:batches.length,hint:`No single accumulator batch covers this refund yet. ${nextStep||"It parks automatically once enough value accumulates on one lock key at one mint; to intervene, fund the DVM or settle manually."}`});return void 0}function isMissingDrainSurface(err){return err instanceof AdminApiError&&err.status===404}function logDrain(ctx,level,fields){console.log(JSON.stringify({level,ts:new Date().toISOString(),dvm_id:ctx.dvmId,handle:ctx.handle,...fields}))}var DEFAULT_INTERVAL_SECONDS=60;var MIN_INTERVAL_SECONDS=10;var MAX_INTERVAL_SECONDS=3600;var DEFAULT_HOLD_ALARM_AFTER="24h";async function meltPending(handle2,opts){const ctx=await resolveContext(handle2,opts);if(!opts.watch){const summary=await runTick(ctx);emitTickSummary(summary,!!opts.human,ctx.handle);const failure=runFailure(ctx,summary);if(failure)throw failure;recordCleanRun(ctx,summary);return}await runWatchLoop(ctx,opts)}async function resolveContext(handle2,opts){const selected=opts.endpoint?void 0:await resolveDvm(handle2,opts);const{canonicalDvmId,currentKeypair,keypairsByPubkey}=selected?resolveBuilderLockKeyring(selected.dvmId):await resolveBuilderLockKeyringByHandle(handle2,opts.endpoint);const endpoint=await resolveEndpoint(handle2,opts.endpoint,selected);const drainsOnly=!!opts.drainsOnly;const payoutLnAddress=opts.payout??getBuilderDvm(canonicalDvmId)?.payout_ln_address;const payoutNwc=parsePayoutNwc(opts.payoutNwc??process.env.DVMKIT_MELT_PAYOUT_NWC_URL);if(!payoutLnAddress&&!payoutNwc&&!drainsOnly){throw new DvmError28("no_payout_destination","No payout destination configured.","Pass `--payout <ln-address>` or set a default with `dvmctl set-payout "+handle2+" <ln-address>`. To melt into a wallet reachable over NWC instead, pass `--payout-nwc <wallet connection URI>` or set DVMKIT_MELT_PAYOUT_NWC_URL.")}const refundNwcUri=opts.refundNwc??process.env.DVMKIT_REFUND_NWC_URL;const client=new AdminCashuClient({endpoint,dvmId:canonicalDvmId,privkeyHex:currentKeypair.privkey});return{handle:handle2,dvmId:canonicalDvmId,endpoint,currentKeypair,keypairsByPubkey,payoutLnAddress:payoutLnAddress??"",...payoutNwc?{payoutNwc}:{},drainsOnly,holdAlarmAfterMs:resolveHoldAlarmAfterMs(opts.holdAlarmAfter),client,drainCtx:{dvmId:canonicalDvmId,handle:handle2,client,keypairsByPubkey,currentKeypair,...refundNwcUri?{refundNwc:{uri:refundNwcUri}}:{}},fetchImpl:globalThis.fetch.bind(globalThis),human:!!opts.human}}function parsePayoutNwc(uri){if(!uri)return void 0;try{return parseNwcUri2(uri)}catch(err){throw new DvmError28("invalid_payout_nwc",`Melt payout NWC connection could not be read: ${err instanceof Error?err.message:String(err)}`,"Re-copy the `wallet connection URI` URI from the wallet the melt should land in. Nothing was melted \u2014 the run refuses rather than paying the Lightning address you did not name.")}}async function payoutInvoice(ctx,msats){if(ctx.payoutNwc){const invoice=await makeInvoice(ctx.payoutNwc,{amountMsats:msats,description:`dvmkit melt \xB7 ${ctx.handle}`});if(!invoice.invoice){throw new DvmError28("payout_invoice_missing","The payout wallet returned no bolt11 for the melt.","The wallet answered `make_invoice` without an invoice. Check the connection permits `make_invoice`, then re-run \u2014 nothing has melted.")}return invoice.invoice}return fetchLnurlPayInvoice(ctx.payoutLnAddress,msats)}function resolveHoldAlarmAfterMs(input){try{return parseDurationMs(input??DEFAULT_HOLD_ALARM_AFTER)}catch(err){throw new DvmError28("invalid_duration",err instanceof Error?err.message:String(err),"`--hold-alarm-after` takes one count and one unit \u2014 e.g. `6h`, `2d`. Raise it to give a flaky DVM more rope; lower it to hear about a stalled melt sooner.")}}async function resolveEndpoint(handle2,override,selected){if(override)return override.replace(/\/+$/,"");const{token,platformUrl}=selected??requireAuth();const{dvm}=await getDvm(platformUrl,token,selected?.dvmId??handle2);if(!dvm.url){throw new DvmError28("dvm_url_unset",`DVM "${handle2}" has no platform URL yet.`,"If the DVM is still deploying, wait for the deploy to finish. Otherwise pass `--endpoint <url>` (e.g. for self-hosted DVMs).")}return dvm.url.replace(/\/+$/,"")}async function runTick(ctx){const recovered=await runRecovery(ctx);const drains=await serviceDrains(ctx.drainCtx);const meltHeld=!drains.fetched||drains.cashu_liability_sats_after>0;const unknownSince=recordDrainState(ctx.dvmId,drains.fetched);const heldForMs=drainHoldElapsedMs(unknownSince);if(heldForMs!==null&&heldForMs>=ctx.holdAlarmAfterMs){logErr(ctx,"melt_pending_drain_hold_sustained",new Error(`Pending drains have been unreadable since ${unknownSince}; the payout melt has been held ever since.`),{drain_state_unknown_since:unknownSince,hold_alarm_after_ms:ctx.holdAlarmAfterMs})}const summaryBase={tick:new Date().toISOString(),dvm_id:ctx.dvmId,endpoint:ctx.endpoint,recovered,drains_seen:drains.drains_seen,drains_parked:drains.drains_parked,drains_jit_minted:drains.drains_jit_minted,drains_failed:drains.drains_failed,drains_queued:drains.drains_queued,drains_manual:drains.drains_manual,drains_channel:drains.drains_channel,drains_recovered:drains.recovered,drain_state_known:drains.fetched,drain_state_unknown_since:unknownSince,melt_held:meltHeld};const noBatches={batches_seen:0,batches_melted:0,batches_skipped:0,batches_failed:0,sats_melted:0};if(ctx.drainsOnly){logEvent(ctx,"melt_pending_skipped_drains_only",{drain_liability_sats:drains.cashu_liability_sats_after,drain_state_known:drains.fetched});return{...summaryBase,...noBatches,melt_skipped:"drains_only"}}if(meltHeld){logEvent(ctx,"melt_pending_held_for_drains",{drain_liability_sats:drains.cashu_liability_sats_after,drain_state_known:drains.fetched});return{...summaryBase,...noBatches,melt_skipped:null}}let res;try{res=await ctx.client.getPendingBatches()}catch(err){rethrowIfBadSignature(err);rethrowIfAdminStateUnavailable(err);throw new DvmError28("pending_batches_fetch_failed","Failed to fetch pending batches from the DVM admin endpoint.",err instanceof Error?err.message:String(err))}let melted=0;let skipped=0;let failed=0;let satsMelted=0;for(const batch of res.batches){const outcome=await meltBatch(ctx,batch);if(outcome==="melted"){melted++;satsMelted+=batch.total_sats}else if(outcome==="skipped")skipped++;else failed++}return{...summaryBase,batches_seen:res.batches.length,batches_melted:melted,batches_skipped:skipped,batches_failed:failed,sats_melted:satsMelted,melt_skipped:null}}async function meltBatch(ctx,batch){const batchKeypair=ctx.keypairsByPubkey.get(toLockPubkey3(batch.lock_pubkey));if(!batchKeypair){logEvent(ctx,"melt_pending_skip_unknown_lock",{mint_url:batch.mint_url,lock_pubkey:batch.lock_pubkey,row_ids:batch.row_ids,total_sats:batch.total_sats});return"skipped"}let inputFees;try{inputFees=await getInputFeesForProofs(batch.mint_url,batch.proofs)}catch(err){logErr(ctx,"melt_pending_input_fee_lookup_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids});return"failed"}if(batch.total_sats<=inputFees){logEvent(ctx,"melt_pending_input_fees_exceed_batch",{mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,input_fees:inputFees});return"skipped"}let bolt11;try{bolt11=await payoutInvoice(ctx,(batch.total_sats-inputFees)*1e3)}catch(err){logErr(ctx,"melt_pending_payout_invoice_failed",err,{destination:ctx.payoutNwc?"nwc":"lnurl",mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,input_fees:inputFees});return"failed"}let quote;try{quote=await fetchMeltQuote(batch.mint_url,bolt11)}catch(err){logErr(ctx,"melt_pending_quote_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids});return"failed"}if(batch.total_sats<quote.amountSats+quote.feeReserveSats+inputFees){const target=batch.total_sats-quote.feeReserveSats-inputFees;if(target<=0){logEvent(ctx,"melt_pending_fee_reserve_exceeds_batch",{mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,fee_reserve_sats:quote.feeReserveSats,input_fees:inputFees});return"skipped"}try{bolt11=await payoutInvoice(ctx,target*1e3)}catch(err){logErr(ctx,"melt_pending_payout_invoice_failed",err,{destination:ctx.payoutNwc?"nwc":"lnurl",mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,target_sats:target});return"failed"}try{quote=await fetchMeltQuote(batch.mint_url,bolt11)}catch(err){logErr(ctx,"melt_pending_quote_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids});return"failed"}if(batch.total_sats<quote.amountSats+quote.feeReserveSats+inputFees){logEvent(ctx,"melt_pending_fee_reserve_too_high",{mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,amount_sats:quote.amountSats,fee_reserve_sats:quote.feeReserveSats,input_fees:inputFees,retry:true});return"skipped"}}const proofs=batch.proofs.map(p=>({id:p.id,amount:p.amount,secret:p.secret,C:p.C,...p.dleq?{dleq:{...p.dleq}}:{}}));appendPreMelt({dvm_id:ctx.dvmId,row_ids:batch.row_ids,mint_url:batch.mint_url,quote_id:quote.rawQuote.quote,lock_pubkey:batch.lock_pubkey,total_sats:batch.total_sats});let preimage;try{const meltResult=await meltProofsWithQuoteSigned(batch.mint_url,proofs,quote,batchKeypair.privkey);preimage=meltResult.preimage}catch(err){const recoveryDiagnostic=missingDleqRecoveryDiagnostic2(proofs,err);appendPostMelt({dvm_id:ctx.dvmId,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote,status:"failed",error:err instanceof Error?err.message:String(err)});logErr(ctx,"melt_pending_melt_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote,...recoveryDiagnostic?{recovery:recoveryDiagnostic}:{}});return"failed"}if(!preimage){logErr(ctx,"melt_pending_missing_preimage_after_success",new Error("mint returned PAID without payment_preimage"),{mint_url:batch.mint_url,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote});return"failed"}try{await ctx.client.markMelted({row_ids:batch.row_ids,melt_quote_id:quote.rawQuote.quote,payment_preimage:preimage})}catch(err){rethrowIfAdminStateUnavailable(err);logErr(ctx,"melt_pending_mark_melted_failed",err,{mint_url:batch.mint_url,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote});return"failed"}appendPostMelt({dvm_id:ctx.dvmId,row_ids:batch.row_ids,quote_id:quote.rawQuote.quote,status:"success",preimage});logEvent(ctx,"melt_pending_batch_melted",{mint_url:batch.mint_url,row_ids:batch.row_ids,total_sats:batch.total_sats,quote_id:quote.rawQuote.quote});return"melted"}async function meltProofsWithQuoteSigned(mintUrl,proofs,quote,privkeyHex){const{getWallet:getWallet2}=await import("@dvmkit/sdk/internal");const wallet=await getWallet2(mintUrl);const{quote:melted}=await wallet.meltProofsBolt11(quote.rawQuote,proofs,{privkey:privkeyHex});return{preimage:melted.payment_preimage??null}}async function runRecovery(ctx){const inFlight=readInFlight(ctx.dvmId);if(inFlight.length===0)return 0;let recovered=0;for(const entry of inFlight){const result=await recoverOne(ctx,entry);if(result==="recovered")recovered++}return recovered}async function recoverOne(ctx,entry){let quote;try{quote=await checkMeltQuoteState(entry.mintUrl,entry.quoteId)}catch(err){logErr(ctx,"melt_pending_recovery_check_failed",err,{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"pending"}if(quote.state==="PENDING"){logEvent(ctx,"melt_pending_recovery_pending",{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"pending"}if(quote.state==="UNPAID"){appendPostMelt({dvm_id:ctx.dvmId,row_ids:entry.rowIds,quote_id:entry.quoteId,status:"failed",error:"ln_unpaid_on_recovery"});logEvent(ctx,"melt_pending_recovery_abandoned",{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"abandoned"}const preimage=quote.payment_preimage;if(!preimage){logErr(ctx,"melt_pending_recovery_paid_no_preimage",new Error("mint returned PAID without payment_preimage"),{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"pending"}try{await ctx.client.markMelted({row_ids:entry.rowIds,melt_quote_id:entry.quoteId,payment_preimage:preimage})}catch(err){rethrowIfAdminStateUnavailable(err);logErr(ctx,"melt_pending_recovery_mark_melted_failed",err,{mint_url:entry.mintUrl,quote_id:entry.quoteId});return"pending"}appendPostMelt({dvm_id:ctx.dvmId,row_ids:entry.rowIds,quote_id:entry.quoteId,status:"success",preimage});logEvent(ctx,"melt_pending_recovery_marked_melted",{mint_url:entry.mintUrl,quote_id:entry.quoteId,row_ids:entry.rowIds});return"recovered"}async function runWatchLoop(ctx,opts){const requestedInterval=opts.interval??DEFAULT_INTERVAL_SECONDS;const intervalSeconds=Math.min(Math.max(MIN_INTERVAL_SECONDS,requestedInterval),MAX_INTERVAL_SECONDS);let stopping=false;let inFlight=null;const fatalHolder={err:null};logEvent(ctx,"melt_pending_watch_started",{interval_seconds:intervalSeconds,endpoint:ctx.endpoint});async function tick(){if(stopping)return;if(inFlight){logEvent(ctx,"melt_pending_tick_skipped_in_flight",{});return}inFlight=(async()=>{try{const summary=await runTick(ctx);emitTickSummary(summary,ctx.human,ctx.handle);const failure=runFailure(ctx,summary);if(failure){logErr(ctx,"melt_pending_tick_not_recorded",failure)}else{recordCleanRun(ctx,summary)}}catch(err){if(err instanceof DvmError28&&err.code==="admin_bad_signature"){fatalHolder.err=err;shutdown();return}logErr(ctx,"melt_pending_tick_error",err)}finally{inFlight=null}})();await inFlight}const timer=setInterval(()=>{void tick()},intervalSeconds*1e3);const shutdown=()=>{if(stopping)return;stopping=true;clearInterval(timer);logEvent(ctx,"melt_pending_watch_stopping",{})};process.on("SIGTERM",shutdown);process.on("SIGINT",shutdown);await tick();await new Promise(resolve10=>{const poll=setInterval(()=>{if(stopping&&!inFlight){clearInterval(poll);resolve10()}},100);if(typeof poll.unref==="function")poll.unref()});if(fatalHolder.err)throw fatalHolder.err}function runFailure(ctx,summary){if(summary.batches_failed>0){return new DvmError28("batches_failed",`${summary.batches_failed} batch(es) failed during this sweep.`,"Inspect the per-batch logs above. Transient failures retry on next run.")}if(ctx.drainsOnly)return drainsUnsettled(summary);return holdSustained(summary,ctx.holdAlarmAfterMs)}function recordCleanRun(ctx,summary){recordMeltSuccess(ctx.dvmId,ctx.drainsOnly?"drains_only":"sweep",{handle:ctx.handle,batches_melted:summary.batches_melted,sats_melted:summary.sats_melted,drains_parked:summary.drains_parked})}function drainsUnsettled(summary){if(!summary.drain_state_known){return new DvmError28("drain_state_unknown",`Could not read this DVM's pending credit drains, so ${settledBeforeFetchFailed(summary)} and this run cannot say what it still owes.`,"See `drain_pending_fetch_failed` above for the underlying error, then check the DVM is reachable and still advertises the lock pubkey this mnemonic derives. Every drain counter except `drains_recovered` reads zero for want of an answer, not for want of work.")}const unsettled=summary.drains_failed+summary.drains_manual+summary.drains_queued;if(unsettled===0)return null;return new DvmError28("drains_unsettled",`${unsettled} credit drain(s) went unsettled (failed=${summary.drains_failed}, manual=${summary.drains_manual}, queued=${summary.drains_queued}).`,unsettledDrainHint(summary))}function holdSustained(summary,holdAlarmAfterMs){const heldForMs=drainHoldElapsedMs(summary.drain_state_unknown_since);if(heldForMs===null||heldForMs<holdAlarmAfterMs)return null;return new DvmError28("drain_state_unknown_sustained",`This DVM's pending credit drains have been unreadable since ${summary.drain_state_unknown_since} (${Math.floor(heldForMs/36e5)}h), so the payout melt has been held that whole time and no owed refund has parked.`,"See `drain_pending_fetch_failed` above for the underlying error. Check the DVM is up and its admin endpoint reachable \u2014 nothing melts and no caller gets refunded until it answers. Raise `--hold-alarm-after` if this DVM is expected to be offline this long.")}function settledBeforeFetchFailed(summary){if(summary.drains_recovered===0)return"nothing was settled";return`only the ${summary.drains_recovered} park(s) replayed from the local log were settled`}function unsettledDrainHint(summary){const hints=[];if(summary.drains_failed>0){hints.push("`failed`: inspect the per-drain logs above \u2014 `drain_park_insufficient_batch` means no single accumulator batch covers the refund yet, so fund the DVM or wait for accumulation and it parks on a later run.")}if(summary.drains_manual>0){hints.push("`manual`: x402/tempo refunds have no builder-held send keys \u2014 list them with `dvmctl credit drains-owed <handle>`, send each one yourself, and record it with `dvmctl credit drain-settle <handle> <credit-id> <drain-id> --tx <hash>`.")}if(summary.drains_queued>0){hints.push("`queued`: nothing was attempted for these \u2014 the `drain_jit_*` lines above say why. `drain_jit_unconfigured` means no send wallet is wired to buy the refund's ecash; `drain_jit_no_mint` means no accepted mint would quote; anything naming a payment in flight is being held on purpose so the refund cannot be bought twice.")}return hints.join(" ")}function emitTickSummary(summary,human,slug){if(human){info(`[${summary.tick}] dvm=${summary.dvm_id} seen=${summary.batches_seen} melted=${summary.batches_melted} skipped=${summary.batches_skipped} failed=${summary.batches_failed} sats=${summary.sats_melted} recovered=${summary.recovered} drains=${summary.drains_seen} parked=${summary.drains_parked} drain_failed=${summary.drains_failed} drain_queued=${summary.drains_queued} drain_manual=${summary.drains_manual}${drainStateNote(summary)}${meltNote(summary)}`)}else{json({...summary,dvmId:summary.dvm_id,slug})}}function drainStateNote(summary){if(summary.drain_state_known)return"";if(!summary.drain_state_unknown_since)return" (drain state unknown)";return` (drain state unknown since ${summary.drain_state_unknown_since})`}function meltNote(summary){if(summary.melt_skipped==="drains_only")return" (melt skipped: --drains-only)";return summary.melt_held?" (melt held for drains)":""}function logEvent(ctx,level,fields){console.log(JSON.stringify({level,ts:new Date().toISOString(),dvm_id:ctx.dvmId,handle:ctx.handle,...fields}))}function logErr(ctx,level,err,fields={}){console.error(JSON.stringify({level,ts:new Date().toISOString(),dvm_id:ctx.dvmId,handle:ctx.handle,error:err instanceof Error?err.message:String(err),...err instanceof DvmError28?{code:err.code,...err.hint?{hint:err.hint}:{},...err.display?{display:err.display}:{}}:err instanceof AdminApiError?{status:err.status,reason:err.body.reason,code:err.body.error}:{},...fields}))}import{DvmError as DvmError29}from"@dvmkit/sdk/internal";init_builder_store();init_defaults();init_output();function meltStatus(handle2,opts){const maxAgeMs=resolveMaxAgeMs(opts.maxAge);const records=readMeltSuccesses();const nowMs=Date.now();const except=validatedExcept(opts.except??[]);const configured=configuredTargets();const all=targets(handle2,configured);refuseAmbiguousExcept(all,except);const watched=all.filter(target=>!except.has(target.handle));const excepted=all.filter(target=>except.has(target.handle)).map(t2=>t2.handle);const configuredIds=new Set(configured.map(target=>target.dvmId));const orphaned=[...records.keys()].filter(dvmId=>!configuredIds.has(dvmId)).sort();const dvms=all.map(target=>{const record2=records.get(target.dvmId)??null;return entryFor(target,record2,except.has(target.handle)?null:maxAgeMs,nowMs)});emit(dvms,{maxAgeMs,excepted,orphaned,human:!!opts.human});if(maxAgeMs!==null&&watched.length===0)nothingToWatch(all.length>0);const stale=dvms.filter(entry=>entry.stale);if(stale.length>0)throw staleError(stale,opts.maxAge??"")}function entryFor(target,record2,maxAgeMs,nowMs){const sweep=record2?.sweep??null;const drainsOnly=record2?.drains_only??null;const sweepAgeMs=meltRunAgeMs(sweep,nowMs);const drainsOnlyAgeMs=meltRunAgeMs(drainsOnly,nowMs);return{handle:target.handle,dvm_id:target.dvmId,last_success_at:sweep?.at??null,age_seconds:sweepAgeMs===null?null:Math.floor(sweepAgeMs/1e3),stale:maxAgeMs!==null&&(sweepAgeMs===null||sweepAgeMs>maxAgeMs),batches_melted:sweep?.batches_melted??null,sats_melted:sweep?.sats_melted??null,drains_parked:sweep?.drains_parked??null,last_drains_only_at:drainsOnly?.at??null,drains_only_age_seconds:drainsOnlyAgeMs===null?null:Math.floor(drainsOnlyAgeMs/1e3)}}var HANDLE_PATTERN=/^[a-z0-9][a-z0-9-]{0,62}$/;function validatedExcept(handles){for(const handle2 of handles){if(HANDLE_PATTERN.test(handle2))continue;throw new DvmError29("invalid_except_handle",`\`--except ${handle2||"<empty>"}\` is not a DVM handle.`,"A handle is lowercase letters, digits and hyphens. This most often means the value was swallowed from the next flag \u2014 `--except --max-age 30h` reads `--max-age` as the handle and leaves no window, which turns the alarm into a plain read that always exits 0. Put a handle after every `--except`, and repeat the flag for each one.")}return new Set(handles)}function refuseAmbiguousExcept(all,except){for(const handle2 of except){const matches2=all.filter(target=>target.handle===handle2);if(matches2.length<=1)continue;throw new DvmError29("ambiguous_dvm_handle",`${matches2.length} builder.json entries claim the handle "${handle2}", so \`--except ${handle2}\` cannot pick between them.`,`Excepting by handle would drop every one of them from the alarm, including a DVM that is still melting. Candidates: ${matches2.map(target=>target.dvmId).join(", ")}. Remove the entry you no longer operate from ${BUILDER_FILE}, then except the handle.`)}}function targets(handle2,configured){if(handle2){const entry=requireBuilderDvmByHandle(handle2);return[{handle:entry.handle,dvmId:entry.canonical_dvm_id}]}return configured}function configuredTargets(){return Object.values(loadBuilderStore().dvms).map(entry=>({handle:entry.handle,dvmId:entry.canonical_dvm_id})).sort((a,b2)=>a.handle.localeCompare(b2.handle))}function nothingToWatch(allExcepted){throw new DvmError29("no_dvms_recorded",allExcepted?"Every DVM on this machine was excluded by `--except`, so `--max-age` has nothing to check.":`No DVMs are recorded in ${BUILDER_FILE}, so \`--max-age\` has nothing to check.`,allExcepted?"Exiting 0 here would be an alarm that can never fire, so this refuses instead. Drop an `--except` flag, or drop `--max-age` if you only wanted to read the record.":"Exiting 0 here would be an alarm that can never fire, so this refuses instead. The usual cause is the command running against the wrong state directory rather than a machine with no DVMs \u2014 a cron or launchd job runs in a minimal environment, so check `HOME` is the account that deployed these DVMs, or set `DVMKIT_CONFIG_DIR` explicitly in the job.")}function resolveMaxAgeMs(input){if(!input)return null;try{return parseDurationMs(input)}catch(err){throw new DvmError29("invalid_duration",err instanceof Error?err.message:String(err),"`--max-age` takes one count and one unit \u2014 e.g. `30h`, `2d`. Set it a little longer than your melt cadence so a single late run is not an alarm.")}}function staleError(stale,maxAge){const named=stale.map(entry=>entry.last_success_at?`${entry.handle} (last swept ${entry.last_success_at})`:`${entry.handle} (never swept on this machine)`).join(", ");return new DvmError29("melt_stale",`${stale.length} DVM(s) have not melted successfully within ${maxAge}: ${named}.`,"Nothing is being swept to your payout destination and no caller refund is parking for these DVMs. Check the scheduled `dvmctl melt-pending` is still running at all \u2014 a cron that stopped firing or a `--watch` daemon that was killed is the usual cause \u2014 then run it by hand and read the error it gives you. A `--drains-only` run does not count here: it settles refunds and sweeps nothing. If one of these DVMs has no Cashu rail and is never meant to melt, exclude it with `--except <handle>`.")}function emit(dvms,ctx){if(!ctx.human){json({dvms,max_age_seconds:ctx.maxAgeMs===null?null:Math.floor(ctx.maxAgeMs/1e3),excepted:ctx.excepted,orphaned:ctx.orphaned,state_file:MELT_SUCCESS_FILE});return}if(dvms.length===0){info("No configured DVMs to report on.")}else{for(const entry of dvms){info(`${entry.handle}: ${entry.last_success_at?`last clean sweep ${entry.last_success_at} (${describeAge(entry.age_seconds)} ago)`:"no clean sweep recorded on this machine"}${entry.stale?" \u2014 STALE":""}${entry.last_drains_only_at?` \xB7 last drains-only ${describeAge(entry.drains_only_age_seconds)} ago`:""}`)}}if(ctx.excepted.length>0)info(`Excepted: ${ctx.excepted.join(", ")}`);if(ctx.orphaned.length>0){info(`Orphaned melt records (not watched): ${ctx.orphaned.join(", ")}`)}info(`Record: ${MELT_SUCCESS_FILE}`)}function describeAge(seconds2){if(seconds2===null)return"unknown";if(seconds2<3600)return`${Math.floor(seconds2/60)}m`;if(seconds2<86400)return`${Math.floor(seconds2/3600)}h`;return`${Math.floor(seconds2/86400)}d`}init_output();async function metrics(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const hours2=opts.hours?Number(opts.hours):24;const result=await getMetrics(platformUrl,token,dvmId,hours2);if(opts.human){if(result.length===0){info(`No metrics for "${slug}" in the last ${hours2} hours.`);return}let total=0;let ok=0;let clientErr=0;let serverErr=0;let latencyMs=0;for(const m of result){total+=m.totalRequests;ok+=m.status2xx;clientErr+=m.status4xx;serverErr+=m.status5xx;latencyMs+=m.totalLatencyMs}const pct=n=>total>0?(n/total*100).toFixed(1):"0.0";const avgLatency=total>0?Math.round(latencyMs/total):0;info(` Last ${hours2} hours:`);info(` Total requests: ${total.toLocaleString()}`);info(` Success (2xx): ${ok.toLocaleString()} (${pct(ok)}%)`);info(` Client err (4xx): ${clientErr.toLocaleString()} (${pct(clientErr)}%)`);info(` Server err (5xx): ${serverErr.toLocaleString()} (${pct(serverErr)}%)`);info(` Avg latency: ${avgLatency}ms`)}else{json({dvmId,slug,hours:hours2,metrics:result})}}init_output();async function orgs(opts){const{token,platformUrl}=requireAuth();const activeOrg=loadActiveOrg();const memberships=await listBuilderOrgs(platformUrl,token);if(opts.human){printHuman(memberships,activeOrg);return}const sharedCount=memberships.filter(membership=>!membership.isPersonal).length;json({activeOrg,memberships:memberships.map(membership=>outputMembership(membership,activeOrg)),display:sharedCount===0?`No shared org memberships. Active context: ${activeOrg??"personal"}.`:`${sharedCount} shared org membership${sharedCount===1?"":"s"}. Active context: ${activeOrg??"personal"}.`,hint:sharedCount===0?"Create or join a shared org in the dashboard. After you join, run `dvmctl switch <handle>`.":"Run `dvmctl switch <handle>` to choose a shared org, or `dvmctl switch --personal` for your personal context."})}function outputMembership(membership,activeOrg){const active=membership.isPersonal?activeOrg===null:membership.handle===activeOrg;if(membership.isPersonal){return{displayName:membership.displayName,role:membership.role,personal:true,active}}return{handle:membership.handle,displayName:membership.displayName,role:membership.role,personal:false,active}}function printHuman(memberships,activeOrg){info(`Active context: ${activeOrg??"personal"}`);const shared=memberships.filter(membership=>!membership.isPersonal);if(shared.length===0)info("No shared org memberships.");if(memberships.length===0)return;const rows=memberships.map(membership=>({handle:membership.isPersonal?"\u2014":membership.handle,name:membership.isPersonal?`${membership.displayName??"Personal context"} (personal)`:membership.displayName??"\u2014",role:membership.role,active:membership.isPersonal?activeOrg===null:membership.handle===activeOrg}));const handleW=Math.max(6,...rows.map(row=>row.handle.length));const nameW=Math.max(4,...rows.map(row=>row.name.length));const roleW=Math.max(4,...rows.map(row=>row.role.length));info("");info(` ${"HANDLE".padEnd(handleW)} ${"NAME".padEnd(nameW)} ${"ROLE".padEnd(roleW)} ACTIVE`);for(const row of rows){info(` ${row.handle.padEnd(handleW)} ${row.name.padEnd(nameW)} ${row.role.padEnd(roleW)} ${row.active?"yes":"no"}`)}}init_output();async function pause(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await pauseDvm(platformUrl,token,dvmId);if(opts.human){for(const m of result.machines){info(`${m.id}: ${m.state}`)}info(`Paused "${slug}". It's no longer serving traffic and its machines are stopping. Data, secrets and database are untouched \u2014 run \`dvmctl resume ${slug}\` to bring it back.`)}else{json({...result,dvmId,slug})}}init_output();async function restart(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await restartMachines(platformUrl,token,dvmId,{machine:opts.machine});if(opts.human){for(const m of result.machines){info(`${m.id}: ${m.state}`)}info(`Restarted ${result.restarted} machine${result.restarted===1?"":"s"}.`)}else{json({...result,dvmId,slug})}}init_output();async function resume(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await resumeDvm(platformUrl,token,dvmId);if(opts.human){for(const m of result.machines){info(`${m.id}: ${m.state}`)}info(`Resumed "${slug}". It's serving traffic again on the same image.`)}else{json({...result,dvmId,slug})}}import{writeFileSync as writeFileSync10}from"fs";init_output();async function revenueCsv(opts){const{token,platformUrl}=requireAuth();const{csv,org}=await getRevenueCsv(platformUrl,token,{from:opts.from,to:opts.to,currency:opts.currency,rail:opts.rail,org:resolveOrgScope(opts)});info(` Org: ${org}`);if(opts.out){writeFileSync10(opts.out,csv,"utf-8");info(` CSV written to ${opts.out}`)}else{process.stdout.write(csv)}}init_output();async function revenueEvents(opts){const{token,platformUrl}=requireAuth();const result=await getRevenueEvents(platformUrl,token,{from:opts.from,to:opts.to,rail:opts.rail,limit:opts.limit!==void 0?Number(opts.limit):void 0,org:resolveOrgScope(opts)});if(opts.human){info(` Org: ${scopeLabel(result.org)}`);if(result.events.length===0){info(` No revenue events found for ${scopeLabel(result.org)}.`);return}info(` ${result.total} total events (showing ${result.events.length})`);info("");const dateW=10;const railW=Math.max(4,...result.events.map(e17=>e17.rail.length));const typeW=Math.max(4,...result.events.map(e17=>e17.source_type.length));const slugW=Math.max(3,...result.events.map(e17=>e17.dvm_slug.length));info(` ${"DATE".padEnd(dateW)} ${"RAIL".padEnd(railW)} ${"TYPE".padEnd(typeW)} ${"DVM".padEnd(slugW)} ${"AMOUNT".padStart(12)} DESCRIPTION`);for(const e17 of result.events){const cur=e17.fiat_currency.toUpperCase();info(` ${e17.date.padEnd(dateW)} ${e17.rail.padEnd(railW)} ${e17.source_type.padEnd(typeW)} ${e17.dvm_slug.padEnd(slugW)} ${formatMinor(e17.net_fiat_minor,cur).padStart(12)} ${e17.line_description}`)}}else{json(result)}}function formatMinor(minor,currency){const major=(minor/100).toFixed(2);const symbols={GBP:"\xA3",EUR:"\u20AC",USD:"$",CHF:"CHF "};const sym=symbols[currency]??`${currency} `;return`${sym}${major}`}init_output();async function revenueSummary(opts){const{token,platformUrl}=requireAuth();const result=await getRevenueSeries(platformUrl,token,{from:opts.from,to:opts.to,currency:opts.currency,org:resolveOrgScope(opts)});if(opts.human){const s=result.summary;const cur=s.fiat_currency.toUpperCase();info(` Revenue summary for ${scopeLabel(result.org)} (${s.period.from} to ${s.period.to})`);info("");info(` Total: ${formatMinor2(s.total_gross_fiat_minor,cur)} (${s.total_count} events)`);info("");if(s.by_source_type_rail.length>0){const typeW=Math.max(4,...s.by_source_type_rail.map(r=>r.source_type.length));const railW=Math.max(4,...s.by_source_type_rail.map(r=>r.rail.length));info(` ${"TYPE".padEnd(typeW)} ${"RAIL".padEnd(railW)} ${"AMOUNT".padStart(12)} COUNT`);for(const row of s.by_source_type_rail){info(` ${row.source_type.padEnd(typeW)} ${row.rail.padEnd(railW)} ${formatMinor2(row.gross_fiat_minor,cur).padStart(12)} ${row.count}`)}}if(s.cross_rate_note){info("");info(` Note: ${s.cross_rate_note}`)}for(const w of result.stale_fx_warnings){info(` ! ${w}`)}}else{json(result)}}function formatMinor2(minor,currency){const major=(minor/100).toFixed(2);const symbols={GBP:"\xA3",EUR:"\u20AC",USD:"$",CHF:"CHF "};const sym=symbols[currency]??`${currency} `;return`${sym}${major}`}init_output();async function rollback(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const{deployId,rolledBackTo}=await rollbackDvm(platformUrl,token,dvmId,{to:opts.to});if(opts.human){info(`Rolling back ${slug} to deploy ${rolledBackTo}...`);info(` Deploy queued: ${deployId}`)}else{progress({event:"queued",deploy_id:deployId,rolled_back_to:rolledBackTo})}const result=await streamDeployLogs(platformUrl,token,deployId,{onLog:line=>{if(opts.human)info(` ${line}`);else progress({event:"log",line})},onPhase:({status:status2,elapsedMs})=>{if(opts.human)info(` ${status2}... (${fmtElapsed(elapsedMs)})`);else progress({event:"phase",phase:status2,elapsed_ms:elapsedMs})}});if(opts.human){info(`
|
|
2433
|
+
Rolled back to ${result.url}`);if(result.dvmkitUrl)info(` Public URL: ${result.dvmkitUrl}`);info("")}else{json({status:"deployed",url:result.url,dvmkitUrl:result.dvmkitUrl,slug,dvmId,deployId,rolledBackTo})}}import{deriveBuilderLockKeypair as deriveBuilderLockKeypair3,DvmError as DvmError30}from"@dvmkit/sdk/internal";init_builder_mnemonic();init_builder_lock_identity();init_builder_store();init_output();async function rotate(handle2,opts){const mnemonic=readBuilderMnemonic();if(!mnemonic){throw new DvmError30("no_builder_mnemonic","No builder mnemonic found.","Run `dvmctl lock create` first to generate or import a mnemonic.")}const selected=opts.endpoint?void 0:await resolveDvm(handle2,opts);let directKeyring;let builderEntry;if(selected){builderEntry=requireSelectedBuilderDvm(selected.dvmId)}else{directKeyring=await resolveBuilderLockKeyringByHandle(handle2,opts.endpoint);builderEntry=requireSelectedBuilderDvm(directKeyring.canonicalDvmId)}const currentIndex=builderEntry.current_rotation_index;const nextIndex=currentIndex+1;const nextKeypair=deriveBuilderLockKeypair3(mnemonic,builderEntry.canonical_dvm_id,nextIndex);const target=await resolveRotationTarget(handle2,builderEntry.canonical_dvm_id,opts.endpoint,!!builderEntry.self_hosted,selected);let response;let resyncedFrom409=false;let platformSyncWarning;if(target.kind==="platform-isolate"){try{const platformResponse=await rotateDvmLockPubkey(target.platformUrl,target.token,builderEntry.canonical_dvm_id,nextKeypair.pubkey);response={current:platformResponse.current,retired:platformResponse.retired};if(platformResponse.lock_pubkey_sync_warning){platformSyncWarning=platformResponse.lock_pubkey_sync_warning}}catch(err){if(err instanceof DvmError30&&err.code==="no_op_rotation"){response={current:nextKeypair.pubkey,retired:[]};resyncedFrom409=true}else{throw err}}}else{const currentKeypair=directKeyring?.currentKeypair??deriveBuilderLockKeypair3(mnemonic,builderEntry.canonical_dvm_id,currentIndex);const client=new AdminCashuClient({endpoint:target.endpoint,dvmId:builderEntry.canonical_dvm_id,privkeyHex:currentKeypair.privkey});try{response=await client.rotateLockPubkey({new_pubkey:nextKeypair.pubkey})}catch(err){if(err instanceof AdminApiError&&err.isBadSignature){throw new DvmError30("admin_bad_signature","DVM admin endpoint rejected our signed challenge (bad_signature).","The DVM's currently-published lock pubkey does not match the privkey derived from this mnemonic + current rotation_index. Confirm `~/.dvmkit/builder.json` is in sync with the DVM.")}if(err instanceof AdminApiError&&err.status===409){response={current:nextKeypair.pubkey,retired:[]};resyncedFrom409=true}else{throw err}}if(!builderEntry.self_hosted){try{const{token,platformUrl}=requireAuth();await setDvmLockPubkey(platformUrl,token,builderEntry.canonical_dvm_id,nextKeypair.pubkey)}catch(err){throw new DvmError30("platform_lock_sync_failed",`Rotated "${handle2}" on the DVM, but could not update the platform's record of its lock pubkey: ${err instanceof Error?err.message:String(err)}`,`The rotation itself landed and builder.json is at index ${nextIndex}. Re-run this command from a machine with platform auth, or run \`dvmctl rotate ${handle2}\` without \`--endpoint\`, before the next \`dvmctl deploy\` \u2014 a deploy against the stale record re-injects the old pubkey and every melt then fails admin_bad_signature.`)}}}patchBuilderDvm(builderEntry.canonical_dvm_id,{current_rotation_index:nextIndex});if(opts.human){info(resyncedFrom409?`Resynced builder.json \u2014 DVM was already at rotation_index ${nextIndex} (prior rotate landed without bumping the local index).`:`Rotated lock pubkey for "${handle2}".`);info(` rotation_index: ${currentIndex} \u2192 ${nextIndex}`);info(` new pubkey: ${response.current}`);if(response.retired.length>0){info(` retired pubkeys in grace window:`);for(const r of response.retired){info(` ${r.pubkey} (retired ${new Date(r.retired_at_ms).toISOString()})`)}}if(platformSyncWarning){info(` Warning: platform bookkeeping sync failed \u2014 ${platformSyncWarning}`);info(" Re-run `dvmctl rotate` once the platform is reachable, or update via dashboard.")}}else{json({status:resyncedFrom409?"resynced":"rotated",handle:handle2,dvmId:builderEntry.canonical_dvm_id,slug:handle2,canonical_dvm_id:builderEntry.canonical_dvm_id,previous_rotation_index:currentIndex,current_rotation_index:nextIndex,current_pubkey:response.current,retired:response.retired,platform_sync_warning:platformSyncWarning})}}async function resolveRotationTarget(handle2,dvmId,override,selfHosted,selected){if(override){return{kind:"sdk-admin",endpoint:override.replace(/\/+$/,"")}}if(selfHosted){throw new DvmError30("endpoint_required",`Self-hosted DVM "${handle2}" needs an explicit \`--endpoint <url>\`.`,"Platform lookup is skipped for self-hosted DVMs \u2014 pass the DVM's public URL.")}if(!resolveAuth()){throw new DvmError30("auth_required","Not authenticated.","Set DVMKIT_API_KEY or run `dvmctl auth` so the CLI can resolve the DVM endpoint via the platform.")}const{token,platformUrl}=selected??requireAuth();const{dvm}=await getDvm(platformUrl,token,dvmId);if(dvm.runtime==="isolate"){return{kind:"platform-isolate",platformUrl,token}}if(!dvm.url){throw new DvmError30("dvm_url_unset",`DVM "${handle2}" has no platform URL yet.`,"If the DVM is still deploying, wait for it to finish. Otherwise pass `--endpoint <url>`.")}return{kind:"sdk-admin",endpoint:dvm.url.replace(/\/+$/,"")}}import{DvmError as DvmError31}from"@dvmkit/sdk/internal";init_output();async function scale(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);if(opts.count===void 0&&opts.size===void 0){throw new DvmError31("bad_request","Nothing to scale.",`Pass --count <n> and/or --size <vm-size>, e.g. dvmctl scale ${slug} --count 2.`)}let count;if(opts.count!==void 0){count=Number(opts.count);if(!Number.isInteger(count)||count<1||count>8){throw new DvmError31("bad_request","--count must be an integer between 1 and 8.")}}const result=await scaleDvm(platformUrl,token,dvmId,{count,size:opts.size});if(opts.human){const{before,after}=result;info(`Scaled ${result.slug}:`);if(before.maxMachines!==after.maxMachines){info(` machines: ${before.maxMachines} \u2192 ${after.maxMachines}`)}const sizeBefore=`${before.cpuCount}\xD7 ${before.cpuKind} CPU, ${before.memoryMb} MB`;const sizeAfter=`${after.cpuCount}\xD7 ${after.cpuKind} CPU, ${after.memoryMb} MB`;if(sizeBefore!==sizeAfter){info(` size: ${sizeBefore} \u2192 ${sizeAfter}`)}}else{json({...result,dvmId,slug})}}init_output();async function secretsList(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const secrets=await listSecrets(platformUrl,token,dvmId);if(opts.human){if(secrets.length===0){info("No secrets set.")}else{for(const s of secrets){info(` ${s.name} (applied ${s.last_applied_at})`)}}}else{json({dvmId,slug,secrets})}}init_builder_store();init_output();import{DvmError as DvmError32,validateLnAddress}from"@dvmkit/sdk/internal";async function setPayout(handle2,lnAddress,opts){if(opts.selfHosted&&opts.org){throw new DvmError32("invalid_scope","--self-hosted cannot be combined with --org.","Use --self-hosted for the local DVM created by `dvmctl init`, or omit it to select a platform DVM with --org.")}const selected=opts.selfHosted?void 0:await resolveDvm(handle2,opts);const existing=selected?requireSelectedBuilderDvm(selected.dvmId):requireBuilderDvmByHandle(handle2);const dvmId=selected?.dvmId??existing.canonical_dvm_id;if(!opts.skipPreflight){await validateLnAddress(lnAddress)}patchBuilderDvm(dvmId,{payout_ln_address:lnAddress});if(opts.human){info(`Payout address for "${handle2}" set to ${lnAddress}.`);info("\n`dvmctl melt-pending "+handle2+"` now melts to this address by default. Override per-run with `--payout <addr>`.")}else{json({status:"set",handle:handle2,dvmId,slug:handle2,payout_ln_address:lnAddress})}}init_output();async function ssh(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);if(!opts.command){const code=await openSshSession(platformUrl,token,dvmId,{machine:opts.machine});process.exit(code)}const result=await execCommand(platformUrl,token,dvmId,opts.command,{machine:opts.machine});if(opts.human){if(result.stdout)raw(result.stdout.replace(/\n$/,""));if(result.stderr)info(result.stderr.replace(/\n$/,""));if(result.exit_code!==0)info(`(exit code ${result.exit_code})`)}else{json({...result,dvmId,slug})}process.exit(result.exit_code)}init_output();async function status(slug,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const result=await getMachineStatus(platformUrl,token,dvmId);if(opts.human){if(result.suspensionReason==="builder_pause"){info(`"${slug}" is paused. Run \`dvmctl resume ${slug}\` to bring it back online.`)}else if(result.suspensionReason==="free_tier_idle"){info(`"${slug}" is idle \u2014 the platform stopped its machines after a quiet spell. The next request wakes it automatically; nothing to fix. Run \`dvmctl resume ${slug}\` to bring it back now.`)}else if(result.status==="suspended"){const reason=result.suspensionReason??"operator";const pause2=result.paused?` Your pause is still on record \u2014 "${slug}" returns to paused once the suspension is lifted.`:"";info(`"${slug}" is suspended by the platform (${reason}); \`dvmctl resume\` won't lift it.${pause2}`)}if(result.machines.length===0){info("No machines (DVM is not currently running any).")}for(const m of result.machines){info("");info(` Machine: ${m.id}`);info(` State: ${m.state}`);info(` Region: ${m.region??"\u2014"}`);info(` Image: ${m.image.version??"\u2014"}`);info(` Created: ${fmtDate5(m.created)}`);info(` Started: ${fmtDate5(m.started)}`);if(m.checks.length>0){info(" Checks:");for(const check2 of m.checks){const endpoint=check2.endpoint?` (${check2.endpoint})`:"";info(` ${check2.name??"?"}: ${check2.status??"?"}${endpoint}`)}}}info("");const vm=result.scale.vm_size;const size4=vm?`${vm.cpus??"?"}\xD7 ${vm.cpu_kind??"?"}, ${vm.memory_mb??"?"}MB`:"\u2014";info(` Scale: ${result.scale.count} machine${result.scale.count===1?"":"s"} (${size4})`)}else{json({...result,dvmId,slug})}}function fmtDate5(iso){if(!iso)return"\u2014";const ms=Date.parse(iso);if(Number.isNaN(ms))return iso;return new Date(ms).toISOString().replace("T"," ").replace(/\.\d+Z$/," UTC")}import{DvmError as DvmError33}from"@dvmkit/sdk/internal";init_output();async function switchCmd(handle2,opts){if(opts.personal&&handle2!=null){throw new DvmError33("bad_arguments","Cannot pass both <handle> and --personal.","Use `dvmctl switch <handle>` to set, or `dvmctl switch --personal` to clear.")}if(opts.personal){clearActiveOrg();if(opts.human){info("Switched to personal context.")}else{json({activeOrg:null})}return}if(handle2==null){const active=loadActiveOrg();if(opts.human){info(active?`Active org: ${active}`:"Active context: personal")}else{json({activeOrg:active})}return}const creds=resolveAuth();if(!creds){throw new DvmError33("auth_required","Not authenticated.","Set DVMKIT_API_KEY or run `dvmctl auth`.")}const platformUrl=process.env.DVMKIT_PLATFORM_URL??"https://api.dvmkit.dev";const membership=await getOrgMembership(platformUrl,creds.token,handle2);saveActiveOrg(membership.handle);if(opts.human){info(`Switched to ${membership.handle} (${membership.role}).`);info("Subsequent `dvmctl` commands read from this org, and deploys create DVMs under it.")}else{json({activeOrg:membership.handle,role:membership.role})}}init_output();import{DvmError as DvmError34}from"@dvmkit/sdk/internal";var MAX_LIMIT2=50;async function tempoLosses(handle2,opts){const limit=resolveLimit2(opts.limit);const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.getTempoCreditLosses({limit}));if(opts.human){if(res.losses.length===0){info("No Tempo-backed credits have been closed for lost collection.");return}for(const loss of res.losses){raw(`${loss.credit_id} ${loss.currency} former=${String(loss.former_balance_micro)} micro settled=${loss.settled_on_chain_native} voucher=${loss.highest_voucher_native} channel=${loss.channel_id}`)}info("These are audit records. The credits expose no drawable or reclaimable balance.");return}json({op:"credit_tempo_losses",handle:handle2,dvmId,slug:handle2,losses:res.losses,loss_count:res.losses.length,display:res.losses.length===0?"No Tempo-backed credits have been closed for lost collection.":`${res.losses.length} Tempo-backed credit loss record(s). These credits are terminal and expose no drawable or reclaimable balance.`,hint:"This is a read-only audit surface; there is no refund, retry, or mark-sent action."})}async function tempoWedged(handle2,opts){const limit=resolveLimit2(opts.limit);const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.getTempoDrains({limit,...opts.after===void 0?{}:{after:opts.after},...opts.includeResolved?{includeResolved:true}:{},...opts.minAgeMs===void 0?{}:{minAgeMs:opts.minAgeMs},...opts.evidence===false?{evidence:false}:{}}));const unresolved=res.drains.filter(d=>d.written_off_at===null);const awaitingClose=unresolved.filter(d=>d.chain?.chain==="unconfirmed");const wedged=unresolved.filter(d=>d.chain?.chain!=="unconfirmed");const repairable=wedged.filter(d=>coversDebit(d));const short=wedged.filter(d=>isShortRefund(d));if(opts.human){if(res.drains.length===0){info("No Tempo closes are stuck between chain and ledger. Nothing to repair.");return}for(const drain of res.drains){raw(`${drain.credit_id} ${drain.drain_id} ${drain.status} ${describeChain(drain)} owed=${drain.amount_native??"-"} native (${String(drain.amount_micro)} ${drain.currency} micro)`+(drain.written_off_at===null?"":` written-off${noteSuffix(drain.write_off_note)}`))}info(`${wedged.length} awaiting a decision, ${repairable.length} whose on-chain refund covers the debit. Finish one with \`dvmctl credit tempo-reconcile ${handle2} <credit-id> <drain-id>\`.`);if(short.length>0){info(`${short.length} refunded the caller less than the ledger extinguished. A reconcile refuses those; \`dvmctl credit tempo-write-off\` is how one is closed.`)}if(awaitingClose.length>0){info(`${awaitingClose.length} more have no confirmed close on chain yet \u2014 those are the caller's to finish, not yours, and are not counted above.`)}if(!opts.includeResolved){info("A written-off close still holds its caller's debited balance, and is not on this page \u2014 `--include-resolved` lists those too.")}if(res.next_after)info(`More rows: re-run with \`--after ${res.next_after}\`.`);return}json({op:"credit_tempo_wedged",handle:handle2,dvmId,slug:handle2,drains:res.drains,wedged_count:wedged.length,repairable_count:repairable.length,short_refund_count:short.length,awaiting_close_count:awaitingClose.length,...res.next_after?{next_after:res.next_after}:{},display:wedged.length===0?awaitingClose.length===0?"No Tempo channel closes are waiting on an operator decision.":`No Tempo close is waiting on an operator decision. ${awaitingClose.length} pending drain(s) have no confirmed close on chain yet, which is the caller's to finish rather than yours.`:`${wedged.length} Tempo close(s) landed on chain without the caller's credit balance being booked as paid. ${repairable.length} paid enough to cover the debit and can be finished.`+(short.length>0?` ${short.length} refunded the caller less than was extinguished \u2014 those cannot be reconciled and need a decision.`:"")+(awaitingClose.length>0?` A further ${awaitingClose.length} pending drain(s) have no confirmed close on chain yet and are not counted here.`:""),hint:"Finish one with `dvmctl credit tempo-reconcile <handle> <credit-id> <drain-id>` \u2014 the amount comes off the close receipt, not from you. If the refund was genuinely short, close it with `dvmctl credit tempo-write-off`."+(opts.includeResolved?"":" Drains you have already written off are not counted here; re-run with `--include-resolved` to see those.")})}async function tempoReconcile(handle2,creditId,drainId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.reconcileTempoDrain({credit_id:creditId,drain_id:drainId}));if(opts.human){info(res.replayed?`Already booked (drain ${res.drain_id} on ${res.credit_id}) \u2014 nothing moved.`:`Booked the ${res.settled_amount??"on-chain"} refund against drain ${res.drain_id} on ${res.credit_id}.`);return}json({op:"credit_tempo_reconcile",handle:handle2,dvmId,slug:handle2,credit_id:res.credit_id,drain_id:res.drain_id,channel_id:res.channel_id,transaction:res.transaction,settled_amount:res.settled_amount,amount_micro:res.amount_micro,amount_native:res.amount_native,currency:res.currency,replayed:res.replayed,display:res.replayed?`This drain was already booked. Nothing moved.`:`Booked drain ${res.drain_id} on ${res.credit_id} against the refund the channel close already paid (${res.transaction??"no transaction recorded"}).`,hint:"The reclaim is reported to the platform on the DVM's own retry loop, so its liability view catches up without another command."})}async function tempoWriteOff(handle2,creditId,drainId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.writeOffTempoDrain({credit_id:creditId,drain_id:drainId,...opts.note===void 0?{}:{note:opts.note}}));if(opts.human){info(res.replayed?`Already written off (drain ${res.drain_id} on ${res.credit_id})${noteSuffix(res.note)}. Nothing changed.`:`Wrote off drain ${res.drain_id} on ${res.credit_id}. Nothing was booked.`);return}json({op:"credit_tempo_write_off",handle:handle2,dvmId,slug:handle2,credit_id:res.credit_id,drain_id:res.drain_id,channel_id:res.channel_id,amount_micro:res.amount_micro,amount_native:res.amount_native,currency:res.currency,note:res.note,replayed:res.replayed,display:res.replayed?`This drain was already written off${res.note?`, with the note "${res.note}"`:""}. Nothing changed, and your note was not recorded over it.`:"Closed this drain without booking it. No ledger row moved: the caller keeps the on-chain refund the close paid them, and the shortfall against what was extinguished is not expressible here \u2014 make it good out of band if you owe it.",hint:"Reversible: `dvmctl credit tempo-reconcile` still accepts a written-off drain if you change your mind."})}function coversDebit(drain){return compareRefund(drain)==="covers"}function isShortRefund(drain){return compareRefund(drain)==="short"}function compareRefund(drain){if(drain.chain?.chain!=="found"||drain.amount_native===null)return"incomparable";try{return BigInt(drain.chain.refundedToPayer)>=BigInt(drain.amount_native)?"covers":"short"}catch{return"incomparable"}}function describeChain(drain){const evidence=drain.chain;if(!evidence)return"chain=not-checked";switch(evidence.chain){case"found":return`chain=refunded:${evidence.refundedToPayer}${isShortRefund(drain)?" (short)":""}`;case"unreported":return"chain=no-receipt";case"unconfirmed":return"chain=no-close";default:return"chain=unreachable"}}function noteSuffix(note){return note?` \u2014 note on record: "${note}"`:""}function resolveLimit2(limit){if(limit===void 0)return 20;if(!Number.isSafeInteger(limit)||limit<1||limit>MAX_LIMIT2){throw new DvmError34("invalid_limit",`--limit must be an integer in 1..${MAX_LIMIT2} (got ${limit}).`,"Leave it unset for the default page of 20, then follow `next_after` for the rest. The ceiling is low because every row on the page may cost a chain read.")}return limit}function renderTrace(trace,opts){const lines=[];const c=opts.color?ansi:noColor;const statusLabel=trace.status==="error"?c.red("ERROR"):c.green("OK");const dimParts=[];for(const key of["builder_id","dvm_id","dvm_slug","rail"]){const val=trace.dimensions[key];if(val!=null)dimParts.push(`${key.replace("_id","")} ${stringify2(val)}`)}lines.push(`trace ${trace.trace_id} duration ${fmtMs(trace.duration_ms)} status ${statusLabel}`+(dimParts.length>0?` ${dimParts.join(" ")}`:""));lines.push("");if(trace.truncated){lines.push(c.yellow("WARNING: trace contains more than 10000 spans; showing first 10000 ordered by start time."));lines.push(c.yellow("This usually means a runaway span emitter (e.g. a tight loop logging)."));lines.push("")}const childrenOf=new Map;for(const span of trace.spans){const key=span.parent_span_id;let list2=childrenOf.get(key);if(!list2){list2=[];childrenOf.set(key,list2)}list2.push(span)}for(const list2 of childrenOf.values()){list2.sort((a,b2)=>a.started_at_ms-b2.started_at_ms)}const flat=[];function walk3(parentId,prefixStack){const children=childrenOf.get(parentId);if(!children)return;for(let i=0;i<children.length;i++){const span=children[i];const isLast=i===children.length-1;const hasChildren=childrenOf.has(span.span_id);let glyph;if(prefixStack.length===0){glyph=hasChildren?"\u2500\u252C\u2500 ":"\u2500\u2500\u2500 "}else{const connector=isLast?"\u2514":"\u251C";const branch=hasChildren?"\u2500\u252C\u2500 ":"\u2500\u2500 ";glyph=connector+branch}const prefix=prefixStack.join("")+glyph;flat.push({span,prefix});const continuation=prefixStack.length===0?"":isLast?" ":"\u2502 ";walk3(span.span_id,[...prefixStack,continuation])}}walk3(null,[]);const rendered=new Set(flat.map(e17=>e17.span.span_id));for(const span of trace.spans){if(!rendered.has(span.span_id)){flat.push({span,prefix:"\u2500\u2500\u2500 "})}}const traceStart=trace.started_at_ms;for(const{span,prefix}of flat){const offset=span.started_at_ms-traceStart;const offsetStr=c.dim(`${String(offset).padStart(5)}ms `);const isLog=span.duration_ms===0;let line;if(isLog){const icon=levelIcon(span.level,c);const attrs=inlineKV(span.dimensions,span.attributes);line=`${offsetStr}${c.dim(prefix)}${icon} ${span.name}${attrs}`}else{const dur=`[${fmtMs(span.duration_ms).padStart(7)}]`;const statusWord=span.status==="error"?c.red("error"):span.status==="ok"?c.green("ok"):"";const attrs=inlineKV(span.dimensions,span.attributes);line=`${offsetStr}${c.dim(prefix)}${span.name}${attrs} ${dur} ${statusWord}`}lines.push(line)}if(Object.keys(trace.dimensions).length>0){lines.push("");lines.push("attributes:");const maxKeyLen=Math.max(...Object.keys(trace.dimensions).map(k2=>k2.length));for(const[k2,v]of Object.entries(trace.dimensions)){lines.push(` ${k2.padEnd(maxKeyLen+2)}${String(v)}`)}}return lines.join("\n")}function fmtMs(ms){if(ms<1e3)return`${ms}ms`;if(ms<6e4)return`${(ms/1e3).toFixed(1)}s`;return`${(ms/6e4).toFixed(1)}m`}function levelIcon(level,c){switch(level){case"error":return c.red("\u2716");case"warn":return c.yellow("\u26A0");default:return c.blue("\u2139")}}function inlineKV(dims,attrs){const headerKeys=new Set(["builder_id","dvm_id","dvm_slug","rail"]);const merged=[];for(const[k2,v]of Object.entries(dims)){if(!headerKeys.has(k2))merged.push([k2,v])}for(const[k2,v]of Object.entries(attrs)){merged.push([k2,v])}if(merged.length===0)return"";const parts=merged.map(([k2,v])=>{const s=stringify2(v);return`${k2}: ${s.length>60?s.slice(0,57)+"...":s}`});return` {${parts.join(", ")}}`}function stringify2(val){if(typeof val==="object"&&val!==null)return JSON.stringify(val);return String(val)}var ansi={red:s=>`\x1B[31m${s}\x1B[0m`,green:s=>`\x1B[32m${s}\x1B[0m`,yellow:s=>`\x1B[33m${s}\x1B[0m`,blue:s=>`\x1B[34m${s}\x1B[0m`,dim:s=>`\x1B[2m${s}\x1B[0m`};var noColor={red:s=>s,green:s=>s,yellow:s=>s,blue:s=>s,dim:s=>s};init_output();async function traceGet(traceId,opts){const{token,platformUrl}=requireAuth();const result=await getBuilderTrace(platformUrl,token,traceId,{org:resolveOrgScope(opts)});if(opts.human){const useColor=opts.color!==false&&process.stdout.isTTY;info(renderTrace(result,{color:useColor}))}else{json(result)}}import{DvmError as DvmError35}from"@dvmkit/sdk/internal";init_output();async function transfer(slug,to,opts){const{token,platformUrl,dvmId}=await resolveDvm(slug,opts);const body=opts.createOrg?{to:{create:{handle:to,displayName:opts.displayName}}}:{to};const result=await transferDvm(platformUrl,token,dvmId,body);if(result.status==="noop"){throw new DvmError35("noop",`DVM "${slug}" is already in the target destination.`)}if(opts.human){if(result.org){info(`Created org "${result.org.handle}" and transferred ${slug} into it.`)}else{info(`Transferred ${slug} \u2192 ${result.to}`)}if(result.treasuryRekeyPending){info("Warning: Treasury re-key pending \u2014 redeploy the DVM (`dvmctl deploy`) to update the Cashu lock pubkey under the new org.")}}else{json({...result,dvmId,slug})}}init_builder_store();init_output();async function whoami(opts){const{token,platformUrl}=requireAuth();const activeOrg=loadActiveOrg();const identity=readLocalIdentity();const[builder,memberships]=await Promise.all([getAuthenticatedBuilderProfile(platformUrl,token),listBuilderOrgs(platformUrl,token)]);if(opts.human){printHuman2(builder,memberships,activeOrg,identity);return}json({identity_pubkey:identity.pubkey,identity_status:identity.status,...identity.status==="unreadable"?{identity_detail:identity.detail}:{},builder,activeOrg,memberships:memberships.map(membership=>outputMembership2(membership,activeOrg)),display:`Builder ${builder.email??builder.handle??builder.id}. Active context: ${activeOrg??"personal"}.`,hint:identity.status==="missing"?"Run `dvmctl identity create` before a cloud or Connect deploy.":identity.status==="unreadable"?"Repair the local builder configuration before a cloud or Connect deploy.":"Every listed membership can deploy a new DVM. The role shows its existing access level."})}function readLocalIdentity(){try{const pubkey=loadIdentityPubkey();if(pubkey===null)return{status:"missing",pubkey:null};if(!/^[0-9a-f]{64}$/.test(pubkey)){return{status:"unreadable",pubkey:null,detail:"Local builder identity pubkey is not a 64-character hexadecimal key."}}return{status:"available",pubkey}}catch(error51){return{status:"unreadable",pubkey:null,detail:error51 instanceof Error?error51.message:String(error51)}}}function outputMembership2(membership,activeOrg){const active=membership.isPersonal?activeOrg===null:membership.handle===activeOrg;if(membership.isPersonal){return{displayName:membership.displayName,role:membership.role,personal:true,deployable:true,active}}return{handle:membership.handle,displayName:membership.displayName,role:membership.role,personal:false,deployable:true,active}}function printHuman2(builder,memberships,activeOrg,identity){info(`Builder: ${builder.displayName??builder.email??builder.handle??builder.id}`);info(` id: ${builder.id}`);info(` email: ${builder.email??"\u2014"}`);info(` handle: ${builder.handle??"\u2014"}`);info(` identity pubkey: ${identity.pubkey??"\u2014"} (${identity.status})`);if(identity.status==="unreadable")info(` identity detail: ${identity.detail}`);info(`Active context: ${activeOrg??"personal"}`);if(memberships.length===0){info("No org memberships found.");return}const rows=memberships.map(membership=>({handle:membership.isPersonal?"\u2014":membership.handle,name:membership.isPersonal?`${membership.displayName??"Personal context"} (personal)`:membership.displayName??"\u2014",role:membership.role,active:membership.isPersonal?activeOrg===null:membership.handle===activeOrg}));const handleW=Math.max(6,...rows.map(row=>row.handle.length));const nameW=Math.max(4,...rows.map(row=>row.name.length));const roleW=Math.max(4,...rows.map(row=>row.role.length));info("");info(` ${"HANDLE".padEnd(handleW)} ${"NAME".padEnd(nameW)} ${"ROLE".padEnd(roleW)} DEPLOY ACTIVE`);for(const row of rows){info(` ${row.handle.padEnd(handleW)} ${row.name.padEnd(nameW)} ${row.role.padEnd(roleW)} yes ${row.active?"yes":"no"}`)}}init_output();async function x402ExactWedged(handle2,opts){const limit=opts.limit??20;if(!Number.isSafeInteger(limit)||limit<1||limit>50){throw new Error("limit must be an integer in 1..50")}const{client,dvmId}=await connectAdmin(handle2,opts);const response=await adminCall(()=>client.getX402ExactSettlements({limit,...opts.includeResolved?{includeResolved:true}:{}}));if(opts.human){if(response.settlements.length===0){info("No exact x402 payments are waiting for recovery.");return}for(const settlement of response.settlements){raw(`${settlement.settlement_intent_id} ${settlement.status} tx=${settlement.transaction??"unknown"} credit=${settlement.credit_id??"-"} job=${settlement.job_id??"-"}`)}info(`Finish a chain-evidenced payment with \`dvmctl credit x402-exact-reconcile ${handle2} <settlement-intent-id>\`.`);return}json({op:"credit_x402_exact_wedged",handle:handle2,dvmId,slug:handle2,settlements:response.settlements,wedged_count:response.settlements.filter(settlement=>settlement.status!=="complete"&&settlement.status!=="rejected").length,display:response.settlements.length===0?"No exact x402 payments are waiting for recovery.":`${response.settlements.length} exact x402 payment(s) need an operator decision or local finalization.`,hint:"Run `dvmctl credit x402-exact-reconcile <handle> <settlement-intent-id>` only after this queue shows the authorization; the DVM derives the transaction and amount from its own evidence."})}async function x402ExactReconcile(handle2,settlementIntentId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const response=await adminCall(()=>client.reconcileX402ExactSettlement(settlementIntentId));const admissionPending=response.settlement_status==="local_committed";if(opts.human){info(admissionPending?`Recorded settlement ${response.transaction??response.settlement_intent_id}; its original job will be admitted when the caller retries the same request.`:response.replayed?`Settlement ${response.settlement_intent_id} was already recorded locally. Nothing changed.`:`Recorded settlement ${response.transaction??response.settlement_intent_id} against its original local effect.`);return}json({op:"credit_x402_exact_reconcile",handle:handle2,dvmId,slug:handle2,...response,display:admissionPending?`Recorded exact x402 transaction ${response.transaction??"from the DVM's chain evidence"}; its original job is still waiting for admission.`:response.replayed?"This exact x402 payment was already finalized locally. Nothing changed.":`Finalized the original local effect for exact x402 transaction ${response.transaction??"recorded by the DVM"}.`,hint:admissionPending?"Have the caller retry the identical signed request and x402 authorization. The DVM will reuse the settled payment and original job id; do not create a new authorization.":response.job_id?"The caller can retry or query its original request; no new payment authorization is needed.":"The original credit funding is now recorded; the caller can read that credit without paying again."})}init_output();import{DvmError as DvmError36}from"@dvmkit/sdk/internal";var MAX_LIMIT3=50;async function x402Wedged(handle2,opts){const limit=resolveLimit3(opts.limit);const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.getX402Settlements({limit,...opts.after===void 0?{}:{after:opts.after},...opts.includeResolved?{includeResolved:true}:{},...opts.minAgeMs===void 0?{}:{minAgeMs:opts.minAgeMs},...opts.evidence===false?{evidence:false}:{}}));const unresolved=res.settlements.filter(s=>s.status!=="written_off");const repairable=unresolved.filter(s=>s.chain?.chain==="found");const held=res.settlements.filter(s=>s.spending_blocked&&(s.credit_balance_micro??0)>0);if(opts.human){if(res.settlements.length===0){info("No x402 settlements are stuck between chain and ledger. Nothing to repair.");return}for(const settlement of res.settlements){raw(`${settlement.settlement_id} ${settlement.status} ${describeChain2(settlement)} credit=${settlement.credit_id??"-"} drain=${settlement.drain_id??"-"} ${describeHold(settlement)}`)}info(`${unresolved.length} awaiting a decision, ${repairable.length} with a matching refund on chain. Finish one with \`dvmctl credit x402-reconcile ${handle2} <settlement-id>\`.`);if(held.length>0){info(`${held.length} of these hold a caller's balance: it can be reclaimed but not spent until the settlement is closed out.`)}if(!opts.includeResolved){info("A written-off settlement keeps holding its caller's balance for good, and is not on this page \u2014 `--include-resolved` lists those too.")}if(res.next_after)info(`More rows: re-run with \`--after ${res.next_after}\`.`);return}json({op:"credit_x402_wedged",handle:handle2,dvmId,slug:handle2,settlements:res.settlements,wedged_count:unresolved.length,repairable_count:repairable.length,holding_balance_count:held.length,...res.next_after?{next_after:res.next_after}:{},display:unresolved.length===0?"No x402 refunds are waiting on an operator decision.":`${unresolved.length} x402 refund(s) settled on chain without the caller's credit balance being cleared. ${repairable.length} of them have a matching refund the chain can confirm.`+(held.length>0?` ${held.length} are holding a caller's balance, which they can reclaim but not spend until the settlement is closed out.`:""),hint:"Finish one with `dvmctl credit x402-reconcile <handle> <settlement-id>` \u2014 the amount comes off the chain, not from you. If the chain and the ledger disagree, close it with `dvmctl credit x402-write-off`."+(opts.includeResolved?"":" A written-off settlement holds its caller's balance for good and is not counted here; re-run with `--include-resolved` to see those.")})}async function x402Reconcile(handle2,settlementId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.reconcileX402Settlement({settlement_id:settlementId}));if(opts.human){info(res.replayed?`Already booked (drain ${res.drain_id} on ${res.credit_id}) \u2014 nothing moved.`:`Booked the ${res.settled_amount??"on-chain"} refund against drain ${res.drain_id} on ${res.credit_id}.`);return}json({op:"credit_x402_reconcile",handle:handle2,dvmId,slug:handle2,settlement_id:res.settlement_id,channel_id:res.channel_id,credit_id:res.credit_id,drain_id:res.drain_id,transaction:res.transaction,settled_amount:res.settled_amount,amount_micro:res.amount_micro,currency:res.currency,replayed:res.replayed,display:res.replayed?`This settlement was already booked against drain ${res.drain_id}. Nothing moved.`:`Cleared the caller's balance on ${res.credit_id} against the refund the chain already paid (${res.transaction??"no transaction recorded"}).`,hint:"The reclaim is reported to the platform on the DVM's own retry loop, so its liability view catches up without another command."})}async function x402WriteOff(handle2,settlementId,opts){const{client,dvmId}=await connectAdmin(handle2,opts);const res=await adminCall(()=>client.writeOffX402Settlement({settlement_id:settlementId,...opts.note===void 0?{}:{note:opts.note}}));if(opts.human){info(res.replayed?`Already written off (${res.settlement_id})${res.note?` \u2014 note on record: "${res.note}"`:""}. Nothing changed.`:`Wrote off settlement ${res.settlement_id}. Nothing was booked.`);return}json({op:"credit_x402_write_off",handle:handle2,dvmId,slug:handle2,settlement_id:res.settlement_id,channel_id:res.channel_id,effect_id:res.effect_id,note:res.note,replayed:res.replayed,display:res.replayed?`This settlement was already written off${res.note?`, with the note "${res.note}"`:""}. Nothing changed, and your note was not recorded over it.`:"Closed this settlement without booking it. No ledger row moved: if the refund did reach the chain, the caller still holds the matching credit balance here and can reclaim it with a new drain.",hint:"Reversible: `dvmctl credit x402-reconcile` still accepts a written-off settlement if you change your mind."})}function describeChain2(settlement){const evidence=settlement.chain;if(!evidence)return"chain=not-checked";switch(evidence.chain){case"found":return`chain=paid:${evidence.amount}`;case"absent":return"chain=nothing-found";case"unbookmarked":return"chain=no-bookmark";default:return"chain=unreachable"}}function describeHold(settlement){const balance=settlement.credit_balance_micro;if(balance===null)return"balance=-";const amount2=`${String(balance)}${settlement.credit_currency?` ${settlement.credit_currency}`:""} micro`;return settlement.spending_blocked?`balance=${amount2} (spend-blocked)`:`balance=${amount2}`}function resolveLimit3(limit){if(limit===void 0)return 20;if(!Number.isSafeInteger(limit)||limit<1||limit>MAX_LIMIT3){throw new DvmError36("invalid_limit",`--limit must be an integer in 1..${MAX_LIMIT3} (got ${limit}).`,"Leave it unset for the default page of 20, then follow `next_after` for the rest. The ceiling is low because every row on the page may cost a chain log scan.")}return limit}init_output();import{asProviderText as asProviderText2,DvmError as DvmError37}from"@dvmkit/sdk/internal";init_output();import{formatFiat}from"@dvmkit/sdk";import{formatUsd,fundingRailLabel,shellQuoteArg,x402NetworkByCaip2,x402NetworkLabel}from"@dvmkit/sdk/internal";function takeCreditNoticeFields(){const taken={...pending};pending={};return taken}var pending={};init_output();import{shellQuoteArg as shellQuoteArg2}from"@dvmkit/sdk/internal";function takeFeedbackNoticeFields(){const taken={...pending2};pending2={};return taken}var pending2={};function catchErrors(fn,human){try{const result=fn();if(result instanceof Promise){result.then(()=>process.exit(process.exitCode??0),err=>handleError(err,human))}}catch(err){handleError(err,human)}}function handleError(err,human){if(err instanceof DvmError37){if(human){const dataDisplay=err.data?.display;const display=typeof dataDisplay==="string"?dataDisplay:err.display;const dataNextStep=err.data?.next_step;const nextStep=typeof dataNextStep==="string"?dataNextStep:void 0;info([`Error: ${err.message}`,display,nextStep,err.hint].filter(Boolean).join("\n"))}else{const error51={code:err.code,message:err.message,...err.display?{display:err.display}:{},...err.hint?{hint:err.hint}:{},...err.data??{}};for(const field of["message","display","hint"]){const value=error51[field];if(err.proseSources?.[field]==="provider"&&typeof value==="string"){error51[field]=asProviderText2(value)}}json({error:error51,...takeCreditNoticeFields(),...takeFeedbackNoticeFields()})}process.exit(1)}const diagnostic=unknownErrorDiagnostic(err);const message2=`An unexpected internal error occurred (${diagnostic.label}).`;if(human){info(`Error: ${message2}`)}else{json({error:{code:"internal",message:message2,error_name:diagnostic.name,...diagnostic.code?{error_code:diagnostic.code}:{}},...takeCreditNoticeFields(),...takeFeedbackNoticeFields()})}process.exit(1)}function unknownErrorDiagnostic(err){const name=unknownErrorName(err);const code=unknownErrorCode(err);return{name,...code?{code}:{},label:code?`${name}:${code}`:name}}function unknownErrorName(err){if(!(err instanceof Error))return`thrown_${typeof err}`;try{const prototype=Object.getPrototypeOf(err);const constructor=prototype?.constructor;const name=typeof constructor==="function"?constructor.name:"";return/^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/.test(name)?name:"Error"}catch{return"Error"}}function unknownErrorCode(err){if(typeof err!=="object"&&typeof err!=="function"||err===null)return void 0;try{const code=err.code;return typeof code==="string"&&/^E[A-Z0-9_]{1,31}$/.test(code)?code:void 0}catch{return void 0}}init_http();init_output();function buildProgram(){const program2=new Command;program2.name("dvmctl").description("Builder CLI for creating and deploying DVMs").version(CLI_VERSION);program2.command("create <name>").description("Scaffold a new DVM project").option("--price <price>","Static price (default: $0.01)").option("--name <name>","DVM display name (default: derived from directory)").option("--description <text>","DVM description").action((dir,opts)=>{catchErrors(()=>create(dir,opts))});program2.command("init <handle>").description("Bootstrap a self-hosted DVM: generate a canonical_dvm_id and persist it to ~/.dvmkit/builder.json").option("--self-hosted","Mark the DVM as self-hosted (required \u2014 platform-hosted DVMs get their canonical_dvm_id at deploy time)").option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>{init(handle2,opts)},opts.human)});program2.command("dev <handler>").description("Start a local development server for a DVM handler").option("--port <port>","HTTP port (default: PORT from .env or 3000)").option("--no-reload","Disable hot reload on file changes").action((handler,opts)=>{catchErrors(async()=>{const{dev:dev2}=await Promise.resolve().then(()=>(init_dev(),dev_exports));await dev2(handler,opts)})});program2.command("deploy").description("Deploy a DVM project").option("--target <target>","Deploy target: cloud, self-host, or local").option("--name <slug>","DVM slug for cloud deploy (default: from package.json)").option("--runtime <runtime>","Runtime tier: container or isolate (default: auto-detect)").option("--endpoint-url <url>","Connect-tier upstream URL (required on plans where the platform doesn't host compute)").option("--local","Register a locally-running DVM into the local platform (no Fly), pointing at its localhost URL").option("--url <url>","Localhost URL the DVM is running at, for --local (default http://localhost:<PORT or 3000>)").option("--dry-run","Validate the project (slug, package.json, vmConfig) and build the Dockerfile locally without contacting the platform").option("--yes","Skip the SDK-staleness confirmation prompt and proceed automatically").option("--create-identity","Create the builder signing identity when it is missing (required for noninteractive first deploys)").option("--allow-dirty","Allow a cloud image to include uncommitted packaged files").option("--org <handle>","Deploy under this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>deploy(opts),opts.human)});program2.command("deploy-status <deployId>").description("Show the current status of a deploy by ID (recovery handle for `dvmctl deploy`)").option("--human","Human-readable output instead of JSON").action((deployId,opts)=>{catchErrors(()=>deployStatus(deployId,opts),opts.human)});program2.command("validate").description("Validate the handler and `package.json#dvmkit` locally without contacting the platform").option("--handler <path>","Handler module (default: handler.ts or handler.js)").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>validate4(opts),opts.human)});program2.command("doctor").description("Diagnose builder-side local state").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>builderDoctor(opts),opts.human)});program2.command("serve <handler>").description("Start a production DVM server").option("--port <port>","HTTP port (default: PORT env var or 8080)").option("--dvm <handle>","Serve under the builder-store lock identity for <handle> \u2014 advertises the lock pubkey derived from your recovery mnemonic, so `dvmctl melt-pending <handle>` and `dvmctl rotate <handle>` can sign for this DVM (self-hosted deploys)").action((handler,opts)=>{catchErrors(async()=>{const{builderServe:builderServe2}=await Promise.resolve().then(()=>(init_serve(),serve_exports));await builderServe2(handler,opts)})});program2.command("list").description("List the deployed DVMs in your current org context").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>list(opts),opts.human)});program2.command("info <slug>").description("Show details for a deployed DVM").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>dvmInfo(slug,opts),opts.human)});program2.command("status <slug>").description("Show a deployed DVM's live Fly runtime state (machines, region, image, health)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>status(slug,opts),opts.human)});program2.command("destroy <slug>").description("Destroy a deployed DVM and its paired Postgres cluster").option("--confirm","Skip confirmation prompt (required in non-interactive mode)").option("--keep-db","Preserve the Postgres cluster for re-attachment on redeploy").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>destroy(slug,opts),opts.human)});program2.command("metrics <slug>").description("Show request metrics for a deployed DVM").option("--hours <hours>","Number of hours to look back (default: 24)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>metrics(slug,opts),opts.human)});program2.command("events <slug>").description("Show recent events for a deployed DVM (deploys, restarts, scale, env, machine state)").option("--since <duration>","Look-back window (e.g. 30s, 5m, 2h, 7d; default: 7d)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>events(slug,opts),opts.human)});const feedbackCmd=program2.command("feedback").description("View caller-submitted feedback and toggle collection per DVM");feedbackCmd.command("list <slug>").description("List caller-submitted feedback for one of your DVMs (newest-first)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--since <duration>","Look-back window (e.g. 24h, 7d, ISO 8601)").option("--cursor <c>","Opaque cursor from a prior page's next_cursor").option("--limit <n>","Max rows per page (1-100, default 50)").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>feedbackList(slug,opts),opts.human)});feedbackCmd.command("enable <slug>").description("Enable caller-feedback collection for one of your DVMs").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>feedbackEnable(slug,opts),opts.human)});feedbackCmd.command("disable <slug>").description("Disable caller-feedback collection for one of your DVMs").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>feedbackDisable(slug,opts),opts.human)});const traceCmd=program2.command("trace").description("Inspect request traces for your DVMs");traceCmd.command("get <traceId>").description("Fetch a trace by ID (isolate-dataset spans only)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--human","Human-readable trace waterfall instead of JSON").option("--no-color","Disable ANSI colors in human output").action((traceId,opts)=>{catchErrors(()=>traceGet(traceId,opts),opts.human)});program2.command("env <slug>").description("View or update environment variables for a deployed DVM").option("--set <KEY=value...>","Set environment variables (repeatable)").option("--unset <KEY...>","Unset environment variables (repeatable)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>env(slug,opts),opts.human)});program2.command("logs <slug>").description("View or stream logs for a deployed DVM").option("--tail","Stream live logs until interrupted (Ctrl-C)").option("--since <duration>","Only show logs newer than this (e.g. 30s, 5m, 2h, 1d)").option("--lines <count>","Max recent lines to show in non-tail mode (default: 100)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").action((slug,opts)=>{catchErrors(()=>logs(slug,opts))});program2.command("ssh <slug>").description("Open an interactive shell (or run a one-shot --command) on a deployed DVM's Fly machine").option("--command <cmd>","Run a one-shot command instead of opening an interactive shell").option("--machine <id>","Target a specific machine (default: first running machine)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON (one-shot --command only)").action((slug,opts)=>{catchErrors(()=>ssh(slug,opts),opts.human)});program2.command("restart <slug>").description("Restart a deployed DVM's Fly machines without a redeploy").option("--machine <id>","Restart a single machine (default: all running machines)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>restart(slug,opts),opts.human)});program2.command("pause <slug>").description("Take a DVM offline \u2014 stops its machines, keeps its slug, data and database").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>pause(slug,opts),opts.human)});program2.command("resume <slug>").description("Bring a paused or idle DVM back online on the same image (no redeploy)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>resume(slug,opts),opts.human)});const dbCmd=program2.command("db").description("Connect to a DVM's per-DVM database");dbCmd.command("connect <slug>").description("Open an interactive psql session against the DVM's database (requires local psql)").option("--machine <id>","Broker through a specific machine (default: first running machine)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Print connection status to stderr").action((slug,opts)=>{catchErrors(()=>dbConnect(slug,opts),opts.human)});dbCmd.command("proxy <slug>").description("Bind a local port to the DVM's database so any Postgres client can connect (pg_dump, drizzle-kit, GUI clients)").option("--port <n>","Local port to bind (default: an OS-assigned free port)").option("--machine <id>","Broker through a specific machine (default: first running machine)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>dbProxy(slug,opts),opts.human)});program2.command("rollback <slug>").description("Revert a deployed DVM to a previous successful deploy's image").option("--to <deploy-id>","Roll back to a specific deploy_id (default: previous deploy)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>rollback(slug,opts),opts.human)});program2.command("scale <slug>").description("Change a deployed DVM's machine count and/or VM size (no redeploy)").option("--count <n>","Number of machines to run (1-8)").option("--size <vm-size>","Fly VM size, e.g. shared-cpu-1x, shared-cpu-2x, performance-1x").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>scale(slug,opts),opts.human)});program2.command("switch [handle]").description("Set the active org context for reads and deploys. Omit handle to show current; --personal to clear.").option("--personal","Clear org context (read and deploy as personal builder)").option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>switchCmd(handle2,opts),opts.human)});program2.command("orgs").description("List your personal and shared org memberships").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>orgs(opts),opts.human)});program2.command("whoami").description("Show your local identity, builder profile, and org access").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>whoami(opts),opts.human)});program2.command("transfer <slug> <to>").description("Transfer a DVM to an org (by handle) or back to personal").option("--create-org","Create the target org if it doesn't exist (to = desired handle)").option("--display-name <name>","Display name for the new org (with --create-org)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,to,opts)=>{catchErrors(()=>transfer(slug,to,opts),opts.human)});program2.command("auth").description("Authenticate with the dvmkit platform").option("--status","Show current auth status").option("--logout","Remove stored credentials").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>auth(opts),opts.human)});const handleCmd=program2.command("handle").description("Manage your builder handle for *.dvmkit.ai subdomains");handleCmd.command("set").argument("<handle>","Handle to claim (2-20 chars, lowercase, no '--')").option("--human","Human-readable output instead of JSON").action((h,opts)=>{catchErrors(()=>handle(h,opts),opts.human)});handleCmd.command("check").argument("<handle>","Handle to check availability for").option("--human","Human-readable output instead of JSON").action((h,opts)=>{catchErrors(()=>handleCheck(h,opts),opts.human)});const identityCmd=program2.command("identity").description("Manage your builder signing identity (deploy attestations, /v1/info#builder)");identityCmd.command("create").description("Generate a per-workstation secp256k1 identity keypair (tracked change). Persists pubkey to ~/.dvmkit/builder.json and secret to ~/.dvmkit/builder.key (0600).").option("--force","Overwrite an existing identity. Any DVMs deployed under the old key will need re-deploy to refresh their /v1/info attestation.").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>{identityCreate(opts)},opts.human)});identityCmd.command("show").description("Print the builder identity pubkey from ~/.dvmkit/builder.json").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>{identityShow(opts)},opts.human)});const lockCmd=program2.command("lock").description("Manage your builder Cashu P2PK lock keypair (BIP-39 mnemonic)");lockCmd.command("create").description("Generate a BIP-39 mnemonic for builder Cashu lock keypairs").option("--import <mnemonic>","Import an existing 12-word BIP-39 mnemonic").option("--force","Replace an existing mnemonic with a freshly generated one. The old words are copied to a timestamped .bak sibling; proofs locked to lock pubkeys derived from them stop being spendable.").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>{lockCreate(opts)},opts.human)});const domainsCmd=program2.command("domains").description("Manage custom domains for deployed DVMs");domainsCmd.command("add").argument("<slug>","DVM slug").argument("<domain>","Custom domain (e.g. api.example.com)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,domain2,opts)=>{catchErrors(()=>domains("add",slug,{domain:domain2,human:opts.human,org:opts.org}),opts.human)});domainsCmd.command("remove").argument("<slug>","DVM slug").argument("<domain>","Custom domain to remove").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,domain2,opts)=>{catchErrors(()=>domains("remove",slug,{domain:domain2,human:opts.human,org:opts.org}),opts.human)});domainsCmd.command("verify").argument("<slug>","DVM slug").argument("<domain>","Custom domain to verify").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,domain2,opts)=>{catchErrors(()=>domains("verify",slug,{domain:domain2,human:opts.human,org:opts.org}),opts.human)});domainsCmd.command("list").argument("<slug>","DVM slug").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>domains("list",slug,{human:opts.human,org:opts.org}),opts.human)});const secretsCmd=program2.command("secrets").description("Inspect and set secrets for a DVM");secretsCmd.command("list").argument("<slug>","DVM slug").description("List secret names + last-applied timestamps for a DVM. Never returns values; platform-injected keys are excluded.").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((slug,opts)=>{catchErrors(()=>secretsList(slug,opts),opts.human)});const revenueCmd=program2.command("revenue").description("View revenue data across your DVMs");revenueCmd.command("summary").description("Show revenue summary with totals and by-rail breakdown").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").requiredOption("--from <date>","Start date (YYYY-MM-DD)").requiredOption("--to <date>","End date (YYYY-MM-DD)").option("--currency <c>","Reporting currency (gbp, eur, usd, chf)").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>revenueSummary(opts),opts.human)});revenueCmd.command("events").description("List individual revenue events (requires admin role in a shared org)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").option("--from <date>","Start date (YYYY-MM-DD)").option("--to <date>","End date (YYYY-MM-DD)").option("--rail <r>","Filter by payment rail (cashu, lightning, tempo, x402)").option("--limit <n>","Max events to return (default: 50)").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>revenueEvents(opts),opts.human)});revenueCmd.command("csv").description("Export revenue data as CSV (requires admin role in a shared org)").option("--org <handle>","Read as this org, overriding the `dvmctl switch` context").requiredOption("--from <date>","Start date (YYYY-MM-DD)").requiredOption("--to <date>","End date (YYYY-MM-DD)").option("--currency <c>","Reporting currency (gbp, eur, usd, chf)").option("--rail <r>","Filter by payment rail").option("--out <path>","Write CSV to file instead of stdout").action(opts=>{catchErrors(()=>revenueCsv(opts))});const apiKeysCmd=program2.command("api-keys").description("Manage builder API keys");apiKeysCmd.command("list").description("List your API keys").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>apiKeysList(opts),opts.human)});apiKeysCmd.command("create").description("Create a new API key").option("--label <text>","Label for the key").option("--human","Human-readable output instead of JSON").action(opts=>{catchErrors(()=>apiKeysCreate(opts),opts.human)});apiKeysCmd.command("revoke <id>").description("Revoke (delete) an API key").option("--human","Human-readable output instead of JSON").action((id,opts)=>{catchErrors(()=>apiKeysRevoke(id,opts),opts.human)});program2.command("rotate <handle>").description("Rotate the per-DVM Cashu lock pubkey \u2014 derives the next BIP-32 child, publishes it to the DVM, demotes the prior pubkey to retired (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; required for self-hosted DVMs)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>rotate(handle2,opts),opts.human)});program2.command("melt-pending <handle>").description("Drain a DVM's pending Cashu accumulator batches \u2014 derives the per-DVM lock privkey locally, melts at the mint, posts mark-melted to the DVM admin endpoint").option("--payout <ln-address>","Lightning address to melt to (overrides any default set via `dvmctl set-payout`)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--watch","Run as a long-lived daemon polling every --interval seconds").option("--interval <seconds>","Poll cadence under --watch (default: 60, range 10\u20133600)",v=>Number(v)).option("--drains-only","Service the credit refunds you owe callers and stop \u2014 never sweep accumulator batches to the payout address. No --payout needed. Use when settling refunds out of band from the scheduled melt").option("--hold-alarm-after <duration>","How long this DVM's drain surface may stay unreadable before a one-shot sweep exits non-zero instead of holding the melt again (default: 24h). Nothing melts and no refund parks while it is held, so this is the ceiling on a silent stall").option("--refund-nwc <uri>","Send-capable NWC connection used to buy a caller's refund when no accumulator batch covers it \u2014 the notes are minted just in time and paid for from this wallet (env: DVMKIT_REFUND_NWC_URL). It only ever pays invoices this command obtained from your own accepted mints").option("--payout-nwc <uri>","Mint the payout invoice from this NWC wallet instead of resolving --payout over LNURL (env: DVMKIT_MELT_PAYOUT_NWC_URL). Use when the melt destination is a node with no Lightning address of its own").option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>meltPending(handle2,opts),opts.human)});program2.command("melt-status [handle]").description("Report when `dvmctl melt-pending` last completed cleanly for each DVM on this machine \u2014 the liveness signal a scheduled melt leaves behind, readable with no platform involved").option("--max-age <duration>","Exit non-zero when a DVM has not swept successfully within this window (e.g. `30h`, `2d`). Cron this and the exit code alarms on a melt job that stopped running at all. Every DVM is watched, and one that has never swept counts as stale").option("--except <handle>","Do not alarm on this DVM under --max-age (repeatable). For a DVM with no Cashu rail, which never melts and would otherwise hold the alarm red forever",(value,previous)=>[...previous,value],[]).option("--human","Human-readable output instead of JSON").action((handle2,opts)=>{catchErrors(()=>{meltStatus(handle2,opts)},opts.human)});const creditCmd=program2.command("credit").description("Reconcile prepaid-credit money your DVM could not apply on its own");creditCmd.command("blocked <handle>").description("List Lightning top-ups your DVM received but could never credit \u2014 the queue behind every `lightning_settlement_blocked` log line (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Page size (default: 50, max 200)",v=>Number(v)).option("--after <cursor>","Continue from a previous run's `next_after` value").option("--include-resolved","Also list rows you already reconciled or wrote off \u2014 the audit view").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>blockedInvoices(handleArg,opts),opts.human)});creditCmd.command("reconcile <handle> <payment-hash>").description("Credit a blocked Lightning payment onto a credit the caller holds. The amount, currency and caller all come off the invoice your DVM recorded; you name only the credit. Idempotent").option("--credit-id <id>","Credit the payment should land on (required)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,paymentHash,opts)=>{catchErrors(()=>reconcileInvoice(handleArg,paymentHash,opts),opts.human)});creditCmd.command("write-off <handle> <payment-hash>").description("Record that you reviewed a blocked Lightning payment and are not crediting it. Moves no money and is reversible \u2014 the row just leaves the queue").option("--note <text>","Why you are not crediting it. Recorded on the invoice row").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,paymentHash,opts)=>{catchErrors(()=>writeOffInvoice(handleArg,paymentHash,opts),opts.human)});creditCmd.command("drains-owed <handle>").description("List the stablecoin refunds your DVM owes callers that nothing will ever pay on its own \u2014 one-payment x402 and Tempo reclaims, the queue behind every `drain_manual_settlement_required` log line (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>drainsOwed(handleArg,opts),opts.human)});creditCmd.command("liability <handles...>").description("Show the satoshis your DVMs owe callers \u2014 undrawn Bitcoin deposits plus reclaims in flight \u2014 and how much of your hub balance is earnings you can sweep. Name every DVM the hub backs (tracked change)").option("--hub-sats <sats>","Your hub's spendable balance, in sats. Supply it to get the sweepable figure directly").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArgs,opts)=>{catchErrors(()=>creditLiability(handleArgs,opts),opts.human)});creditCmd.command("drain-settle <handle> <credit-id> <drain-id>").description("Record that you settled an owed stablecoin refund on chain. Moves no money \u2014 the ledger catches up with a payout you already made, the caller's poll sees it settled, and the reclaim stops counting against your liability. Idempotent").option("--tx <hash>","On-chain transaction that paid the refund (required)").option("--note <text>","Recorded alongside the transaction, e.g. which wallet sent it").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,creditId,drainId,opts)=>{catchErrors(()=>drainSettle(handleArg,creditId,drainId,opts),opts.human)});creditCmd.command("x402-wedged <handle>").description("List x402 cooperative refunds that settled on chain but never cleared the caller's balance, with what the chain says about each (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Page size (default: 20, max 50)",v=>Number(v)).option("--after <cursor>","Continue from a previous run's `next_after` value").option("--include-resolved","Also list settlements you already wrote off \u2014 the audit view").option("--min-age-ms <ms>","How long a settlement must have sat before it counts as stuck (default: 300000)",v=>Number(v)).option("--no-evidence","Skip the per-row chain lookups \u2014 a fast read of the queue itself").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>x402Wedged(handleArg,opts),opts.human)});creditCmd.command("x402-reconcile <handle> <settlement-id>").description("Finish the ledger leg of an x402 refund the chain already paid. The amount is re-derived from chain evidence, never sent from here; a chain/ledger disagreement refuses. Idempotent").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,settlementId,opts)=>{catchErrors(()=>x402Reconcile(handleArg,settlementId,opts),opts.human)});creditCmd.command("x402-write-off <handle> <settlement-id>").description("Record that you reviewed a wedged x402 settlement and are not booking it. Books nothing and is reversible \u2014 the row just leaves the queue").option("--note <text>","Why you are not booking it. Recorded on the settlement row").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,settlementId,opts)=>{catchErrors(()=>x402WriteOff(handleArg,settlementId,opts),opts.human)});creditCmd.command("x402-exact-wedged <handle>").description("List exact x402 authorizations whose chain settlement has not finished its original local credit or job effect").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Rows to return (default: 20, max 50)",v=>Number(v)).option("--include-resolved","Also list completed and rejected intents").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>x402ExactWedged(handleArg,opts),opts.human)});creditCmd.command("x402-exact-reconcile <handle> <settlement-intent-id>").description("Finish the original local effect of a chain-evidenced exact x402 payment. The transaction and amount come from the DVM, never this command").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,settlementIntentId,opts)=>{catchErrors(()=>x402ExactReconcile(handleArg,settlementIntentId,opts),opts.human)});creditCmd.command("tempo-losses <handle>").description("List Tempo-backed credits terminalized after their channel finalized before the DVM collected accepted value").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Rows to return (default: 20, max 50)",v=>Number(v)).option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>tempoLosses(handleArg,opts),opts.human)});creditCmd.command("tempo-wedged <handle>").description("List Tempo cooperative closes that landed on chain but never booked the caller's drain, with what the close receipt says about each (tracked change)").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--limit <n>","Page size (default: 20, max 50)",v=>Number(v)).option("--after <cursor>","Continue from a previous run's `next_after` value").option("--include-resolved","Also list drains you already wrote off \u2014 the audit view").option("--min-age-ms <ms>","How long a drain must have sat before it counts as stuck (default: 300000)",v=>Number(v)).option("--no-evidence","Skip the per-row chain lookups \u2014 a fast read of the queue itself").option("--human","Human-readable output instead of JSON").action((handleArg,opts)=>{catchErrors(()=>tempoWedged(handleArg,opts),opts.human)});creditCmd.command("tempo-reconcile <handle> <credit-id> <drain-id>").description("Book a Tempo drain whose channel close already paid. The amount is re-read from the close receipt, never sent from here; a refund short of the debit refuses. Idempotent").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,creditId,drainId,opts)=>{catchErrors(()=>tempoReconcile(handleArg,creditId,drainId,opts),opts.human)});creditCmd.command("tempo-write-off <handle> <credit-id> <drain-id>").description("Record that you reviewed a wedged Tempo close and are not booking it. Books nothing and is reversible \u2014 the row just leaves the queue").option("--note <text>","Why you are not booking it. Recorded on the drain row").option("--endpoint <url>","DVM admin endpoint URL (skips the platform getDvm lookup; use for self-hosted DVMs or local dev)").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handleArg,creditId,drainId,opts)=>{catchErrors(()=>tempoWriteOff(handleArg,creditId,drainId,opts),opts.human)});program2.command("set-payout <handle> <ln-address>").description("Persist the default Lightning payout address for `dvmctl melt-pending <handle>` (pre-flights the LNURL-pay endpoint)").option("--skip-preflight","Skip the LNURL pre-flight check (use when the provider is temporarily down)").option("--self-hosted","Resolve this handle from local builder.json state instead of asking the platform which DVM it is. Named for the self-hosted case it was built for, but it reaches any entry recorded on this machine \u2014 including one a `dvmctl deploy` wrote, whose payout address it will rewrite").option("--org <handle>","Target this org, overriding the `dvmctl switch` context").option("--human","Human-readable output instead of JSON").action((handle2,lnAddress,opts)=>{catchErrors(()=>setPayout(handle2,lnAddress,opts),opts.human)});return program2}if(process.argv[1]&&realpathSync3(process.argv[1])===fileURLToPath3(import.meta.url)){installGlobalAcceptEncoding();setOutputTraceId(randomTraceId());buildProgram().parse()}export{buildProgram};
|
|
2434
2434
|
/*! Bundled license information:
|
|
2435
2435
|
|
|
2436
2436
|
@noble/hashes/utils.js:
|