@turbobase/cli 1.39.0 → 1.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/turbobase-standalone.mjs +173 -170
- package/dist/turbobase.js +162 -159
- package/package.json +1 -1
|
@@ -1,49 +1,49 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __tbCreateRequire } from 'node:module';
|
|
3
3
|
const require = __tbCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(l=l.concat([r.wrap(u,o,0),""]));let p=r.visibleArguments(e).map(
|
|
4
|
+
var GT=Object.create;var Sl=Object.defineProperty;var JT=Object.getOwnPropertyDescriptor;var YT=Object.getOwnPropertyNames;var XT=Object.getPrototypeOf,QT=Object.prototype.hasOwnProperty;var ts=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),rs=(t,e)=>{for(var r in e)Sl(t,r,{get:e[r],enumerable:!0})},eR=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of YT(e))!QT.call(t,o)&&o!==r&&Sl(t,o,{get:()=>e[o],enumerable:!(n=JT(e,o))||n.enumerable});return t};var $l=(t,e,r)=>(r=t!=null?GT(XT(t)):{},eR(e||!t||!t.__esModule?Sl(r,"default",{value:t,enumerable:!0}):r,t));var ns=B(Rl=>{var Oi=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Tl=class extends Oi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Rl.CommanderError=Oi;Rl.InvalidArgumentError=Tl});var Ni=B(Pl=>{var{InvalidArgumentError:tR}=ns(),El=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new tR(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function rR(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Pl.Argument=El;Pl.humanReadableArgName=rR});var Cl=B(kg=>{var{humanReadableArgName:nR}=Ni(),Al=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden);if(e._hasImplicitHelpCommand()){let[,n,o]=e._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/),s=e.createCommand(n).helpOption(!1);s.description(e._helpCommandDescription),o&&s.arguments(o),r.push(s)}return this.sortSubcommands&&r.sort((n,o)=>n.name().localeCompare(o.name())),r}compareOptions(e,r){let n=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._hasHelpOption&&e._helpShortFlag&&!e._findOption(e._helpShortFlag),o=e._hasHelpOption&&!e._findOption(e._helpLongFlag);if(n||o){let s;n?o?s=e.createOption(e._helpFlags,e._helpDescription):s=e.createOption(e._helpShortFlag,e._helpDescription):s=e.createOption(e._helpLongFlag,e._helpDescription),r.push(s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let o=n.options.filter(s=>!s.hidden);r.push(...o)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>nR(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,o)=>Math.max(n,r.subcommandTerm(o).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,o)=>Math.max(n,r.argumentTerm(o).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let o=e.parent;o;o=o.parent)n=o.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),o=r.helpWidth||80,s=2,i=2;function a(m,w){if(w){let $=`${m.padEnd(n+i)}${w}`;return r.wrap($,o-s,n+i)}return m}function c(m){return m.join(`
|
|
5
|
+
`).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(l=l.concat([r.wrap(u,o,0),""]));let p=r.visibleArguments(e).map(m=>a(r.argumentTerm(m),r.argumentDescription(m)));p.length>0&&(l=l.concat(["Arguments:",c(p),""]));let b=r.visibleOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));if(b.length>0&&(l=l.concat(["Options:",c(b),""])),this.showGlobalOptions){let m=r.visibleGlobalOptions(e).map(w=>a(r.optionTerm(w),r.optionDescription(w)));m.length>0&&(l=l.concat(["Global Options:",c(m),""]))}let f=r.visibleCommands(e).map(m=>a(r.subcommandTerm(m),r.subcommandDescription(m)));return f.length>0&&(l=l.concat(["Commands:",c(f),""])),l.join(`
|
|
6
6
|
`)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,o=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",i=new RegExp(`[\\n][${s}]+`);if(e.match(i))return e;let a=r-n;if(a<o)return e;let c=e.slice(0,n),l=e.slice(n).replace(`\r
|
|
7
7
|
`,`
|
|
8
8
|
`),u=" ".repeat(n),b="\\s\u200B",f=new RegExp(`
|
|
9
|
-
|.{1,${a-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),
|
|
10
|
-
`?"":(
|
|
11
|
-
`)}};
|
|
9
|
+
|.{1,${a-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),m=l.match(f)||[];return c+m.map((w,$)=>w===`
|
|
10
|
+
`?"":($>0?u:"")+w.trimEnd()).join(`
|
|
11
|
+
`)}};kg.Help=Al});var Nl=B(Li=>{var{InvalidArgumentError:oR}=ns(),Il=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=xg(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new oR(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return sR(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ol=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let o=this.negativeOptions.get(n).presetArg,s=o!==void 0?o:!1;return r.negate===(s===e)}};function sR(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function xg(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}Li.Option=Il;Li.splitOptionFlags=xg;Li.DualOptions=Ol});var $g=B(Sg=>{function iR(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let o=1;o<=t.length;o++){let s=1;t[o-1]===e[n-1]?s=0:s=1,r[o][n]=Math.min(r[o-1][n]+1,r[o][n-1]+1,r[o-1][n-1]+s),o>1&&n>1&&t[o-1]===e[n-2]&&t[o-2]===e[n-1]&&(r[o][n]=Math.min(r[o][n],r[o-2][n-2]+1))}return r[t.length][e.length]}function aR(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(i=>i.slice(2)));let n=[],o=3,s=.4;return e.forEach(i=>{if(i.length<=1)return;let a=iR(t,i),c=Math.max(t.length,i.length);(c-a)/c>s&&(a<o?(o=a,n=[i]):a===o&&n.push(i))}),n.sort((i,a)=>i.localeCompare(a)),r&&(n=n.map(i=>`--${i}`)),n.length>1?`
|
|
12
12
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
13
|
-
(Did you mean ${n[0]}?)`:""}
|
|
14
|
-
- specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this.commands.push(e),e.parent=this,this}createArgument(e,r){return new
|
|
15
|
-
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new zl(e,r,n)),Fe.exit(e)}action(e){let r=n=>{let o=this.registeredArguments.length,s=n.slice(0,o);return this._storeOptionsAsProperties?s[o]=this:s[o]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=r,this}createOption(e,r){return new
|
|
13
|
+
(Did you mean ${n[0]}?)`:""}Sg.suggestSimilar=aR});var Cg=B(Ag=>{var cR=ts("events").EventEmitter,Ll=ts("child_process"),Tr=ts("path"),jl=ts("fs"),Fe=ts("process"),{Argument:lR,humanReadableArgName:uR}=Ni(),{CommanderError:zl}=ns(),{Help:dR}=Cl(),{Option:Tg,splitOptionFlags:pR,DualOptions:hR}=Nl(),{suggestSimilar:Rg}=$g(),Dl=class t extends cR{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>Fe.stdout.write(r),writeErr:r=>Fe.stderr.write(r),getOutHelpWidth:()=>Fe.stdout.isTTY?Fe.stdout.columns:void 0,getErrHelpWidth:()=>Fe.stderr.isTTY?Fe.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._hasHelpOption=!0,this._helpFlags="-h, --help",this._helpDescription="display help for command",this._helpShortFlag="-h",this._helpLongFlag="--help",this._addImplicitHelpCommand=void 0,this._helpCommandName="help",this._helpCommandnameAndArgs="help [command]",this._helpCommandDescription="display help for command",this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._hasHelpOption=e._hasHelpOption,this._helpFlags=e._helpFlags,this._helpDescription=e._helpDescription,this._helpShortFlag=e._helpShortFlag,this._helpLongFlag=e._helpLongFlag,this._helpCommandName=e._helpCommandName,this._helpCommandnameAndArgs=e._helpCommandnameAndArgs,this._helpCommandDescription=e._helpCommandDescription,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let o=r,s=n;typeof o=="object"&&o!==null&&(s=o,o=null),s=s||{};let[,i,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(i);return o&&(c.description(o),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this.commands.push(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new dR,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
14
|
+
- specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this.commands.push(e),e.parent=this,this}createArgument(e,r){return new lR(e,r)}argument(e,r,n,o){let s=this.createArgument(e,r);return typeof n=="function"?s.default(o).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}addHelpCommand(e,r){return e===!1?this._addImplicitHelpCommand=!1:(this._addImplicitHelpCommand=!0,typeof e=="string"&&(this._helpCommandName=e.split(" ")[0],this._helpCommandnameAndArgs=e),this._helpCommandDescription=r||this._helpCommandDescription),this}_hasImplicitHelpCommand(){return this._addImplicitHelpCommand===void 0?this.commands.length&&!this._actionHandler&&!this._findCommand("help"):this._addImplicitHelpCommand}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
15
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new zl(e,r,n)),Fe.exit(e)}action(e){let r=n=>{let o=this.registeredArguments.length,s=n.slice(0,o);return this._storeOptionsAsProperties?s[o]=this:s[o]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=r,this}createOption(e,r){return new Tg(e,r)}_callParseArg(e,r,n,o){try{return e.parseArg(r,n)}catch(s){if(s.code==="commander.invalidArgument"){let i=`${o} ${s.message}`;this.error(i,{exitCode:s.exitCode,code:s.code})}throw s}}addOption(e){let r=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");this.options.push(e);let o=(s,i,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let c=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,c,i):s!==null&&e.variadic&&(s=e._concatValue(s,c)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,a)};return this.on("option:"+r,s=>{let i=`error: option '${e.flags}' argument '${s}' is invalid.`;o(s,i,"cli")}),e.envVar&&this.on("optionEnv:"+r,s=>{let i=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;o(s,i,"env")}),this}_optionEx(e,r,n,o,s){if(typeof r=="object"&&r instanceof Tg)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(r,n);if(i.makeOptionMandatory(!!e.mandatory),typeof o=="function")i.default(s).argParser(o);else if(o instanceof RegExp){let a=o;o=(c,l)=>{let u=a.exec(c);return u?u[0]:l},i.default(s).argParser(o)}else i.default(o);return this.addOption(i)}option(e,r,n,o){return this._optionEx({},e,r,n,o)}requiredOption(e,r,n,o){return this._optionEx({mandatory:!0},e,r,n,o)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){if(this._passThroughOptions=!!e,this.parent&&e&&!this.parent._enablePositionalOptions)throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");return this}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");r=r||{},e===void 0&&(e=Fe.argv,Fe.versions&&Fe.versions.electron&&(r.from="electron")),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":Fe.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,p){let b=Tr.resolve(u,p);if(jl.existsSync(b))return b;if(o.includes(Tr.extname(p)))return;let f=o.find(m=>jl.existsSync(`${b}${m}`));if(f)return`${b}${f}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=jl.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Tr.resolve(Tr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let p=Tr.basename(this._scriptPath,Tr.extname(this._scriptPath));p!==this._name&&(u=s(a,`${p}-${e._name}`))}i=u||i}n=o.includes(Tr.extname(i));let c;Fe.platform!=="win32"?n?(r.unshift(i),r=Pg(Fe.execArgv).concat(r),c=Ll.spawn(Fe.argv[0],r,{stdio:"inherit"})):c=Ll.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=Pg(Fe.execArgv).concat(r),c=Ll.spawn(Fe.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{Fe.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;l?c.on("close",()=>{l(new zl(Fe.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Fe.exit.bind(Fe)),c.on("error",u=>{if(u.code==="ENOENT"){let p=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",b=`'${i}' does not exist
|
|
16
16
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
17
17
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
18
|
-
- ${p}`;throw new Error(b)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Fe.exit(1);else{let p=new zl(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,l(p)}}),this.runningCommand=c}_dispatchSubcommand(e,r,n){let o=this._findCommand(e);o||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(o._executableHandler)this._executeSubCommand(o,r.concat(n));else return o._parseCommand(r,n)}),s}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._helpLongFlag||this._helpShortFlag])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,o,s)=>{let i=o;if(o!==null&&n.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${n.name()}'.`;i=this._callParseArg(n,o,s,a)}return i};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,o)=>{let s=n.defaultValue;n.variadic?o<this.args.length?(s=this.args.slice(o),n.parseArg&&(s=s.reduce((i,a)=>e(n,a,i),n.defaultValue))):s===void 0&&(s=[]):o<this.args.length&&(s=this.args[o],n.parseArg&&(s=e(n,s,n.defaultValue))),r[o]=s}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,o=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[r]!==void 0).forEach(s=>{s._lifeCycleHooks[r].forEach(i=>{o.push({hookedCommand:s,callback:i})})}),r==="postAction"&&o.reverse(),o.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let o=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{o=this._chainOrCall(o,()=>s(this,r))}),o}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._hasImplicitHelpCommand()&&e[0]===this._helpCommandName)return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return
|
|
18
|
+
- ${p}`;throw new Error(b)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Fe.exit(1);else{let p=new zl(1,"commander.executeSubCommandAsync","(error)");p.nestedError=u,l(p)}}),this.runningCommand=c}_dispatchSubcommand(e,r,n){let o=this._findCommand(e);o||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,o,"preSubcommand"),s=this._chainOrCall(s,()=>{if(o._executableHandler)this._executeSubCommand(o,r.concat(n));else return o._parseCommand(r,n)}),s}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._helpLongFlag||this._helpShortFlag])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,o,s)=>{let i=o;if(o!==null&&n.parseArg){let a=`error: command-argument value '${o}' is invalid for argument '${n.name()}'.`;i=this._callParseArg(n,o,s,a)}return i};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,o)=>{let s=n.defaultValue;n.variadic?o<this.args.length?(s=this.args.slice(o),n.parseArg&&(s=s.reduce((i,a)=>e(n,a,i),n.defaultValue))):s===void 0&&(s=[]):o<this.args.length&&(s=this.args[o],n.parseArg&&(s=e(n,s,n.defaultValue))),r[o]=s}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,o=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[r]!==void 0).forEach(s=>{s._lifeCycleHooks[r].forEach(i=>{o.push({hookedCommand:s,callback:i})})}),r==="postAction"&&o.reverse(),o.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let o=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{o=this._chainOrCall(o,()=>s(this,r))}),o}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._hasImplicitHelpCommand()&&e[0]===this._helpCommandName)return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return Eg(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),Eg(this,n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(s,e,r)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))o(),this._processArguments(),this.parent.emit(s,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let o=e.find(s=>n.conflictsWith.includes(s.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],o=r,s=e.slice();function i(c){return c.length>1&&c[0]==="-"}let a=null;for(;s.length;){let c=s.shift();if(c==="--"){o===n&&o.push(c),o.push(...s);break}if(a&&!i(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,i(c)){let l=this._findOption(c);if(l){if(l.required){let u=s.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;s.length>0&&!i(s[0])&&(u=s.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(i(c)&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(c)){r.push(c),s.length>0&&n.push(...s);break}else if(c===this._helpCommandName&&this._hasImplicitHelpCommand()){r.push(c),s.length>0&&r.push(...s);break}else if(this._defaultCommandName){n.push(c),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){o.push(c),s.length>0&&o.push(...s);break}o.push(c)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let o=this.options[n].attributeName();e[o]=o===this._versionOptionName?this._version:this[o]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
|
|
19
19
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
20
20
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
21
|
-
`),this.outputHelp({error:!0}));let n=r||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in Fe.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,Fe.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
22
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>
|
|
21
|
+
`),this.outputHelp({error:!0}));let n=r||{},o=n.exitCode||1,s=n.code||"commander.error";this._exit(o,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in Fe.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,Fe.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new hR(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(o=>!r(o)).forEach(o=>{this.setOptionValueWithSource(o,n.implied[o],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=i=>{let a=i.attributeName(),c=this.getOptionValue(a),l=this.options.find(p=>p.negate&&a===p.attributeName()),u=this.options.find(p=>!p.negate&&a===p.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||i},o=i=>{let a=n(i),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${o(e)} cannot be used with ${o(r)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let o=[],s=this;do{let i=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);o=o.concat(i),s=s.parent}while(s&&!s._enablePositionalOptions);r=Rg(e,o)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(s=>{o.push(s.name()),s.alias()&&o.push(s.alias())}),r=Rg(e,o)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let o=this.createOption(r,n);return this._versionOptionName=o.attributeName(),this.options.push(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
22
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>uR(n));return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Tr.basename(e,Tr.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=o=>this._outputConfiguration.writeErr(o):n=o=>this._outputConfiguration.writeOut(o),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let o=this.helpInformation(n);if(r&&(o=r(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._helpLongFlag&&this.emit(this._helpLongFlag),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,r){if(typeof e=="boolean")return this._hasHelpOption=e,this;this._helpFlags=e||this._helpFlags,this._helpDescription=r||this._helpDescription;let n=pR(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=Fe.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
23
23
|
Expecting one of '${n.join("', '")}'`);let o=`${e}Help`;return this.on(o,s=>{let i;typeof r=="function"?i=r({error:s.error,command:s.command}):i=r,i&&s.write(`${i}
|
|
24
|
-
`)}),this}};function Rg(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function Eg(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",o="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?o=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],o=s[4]),r&&o!=="0"?`${r}=${n}:${parseInt(o)+1}`:e})}Pg.Command=jl});var Ng=B((Yt,Og)=>{var{Argument:uR}=Oi(),{Command:Cg}=Ag(),{CommanderError:dR,InvalidArgumentError:Ig}=ts(),{Help:pR}=Al(),{Option:hR}=Ol();Yt=Og.exports=new Cg;Yt.program=Yt;Yt.Command=Cg;Yt.Option=hR;Yt.Argument=uR;Yt.Help=pR;Yt.CommanderError=dR;Yt.InvalidArgumentError=Ig;Yt.InvalidOptionArgumentError=Ig});function gn(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var rs=O(()=>{});var we,Dl,V,mr,ns=O(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(we||(we={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Dl||(Dl={}));V=we.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mr=t=>{switch(typeof t){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(t)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(t)?V.array:t===null?V.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?V.promise:typeof Map<"u"&&t instanceof Map?V.map:typeof Set<"u"&&t instanceof Set?V.set:typeof Date<"u"&&t instanceof Date?V.date:V.object;default:return V.unknown}}});var j,mR,kt,Li=O(()=>{ns();j=we.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),mR=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),kt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,we.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};kt.create=t=>new kt(t)});var fR,Rr,Ml=O(()=>{Li();ns();fR=(t,e)=>{let r;switch(t.code){case j.invalid_type:t.received===V.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case j.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,we.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:r=`Unrecognized key(s) in object: ${we.joinValues(t.keys,", ")}`;break;case j.invalid_union:r="Invalid input";break;case j.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${we.joinValues(t.options)}`;break;case j.invalid_enum_value:r=`Invalid enum value. Expected ${we.joinValues(t.options)}, received '${t.received}'`;break;case j.invalid_arguments:r="Invalid function arguments";break;case j.invalid_return_type:r="Invalid function return type";break;case j.invalid_date:r="Invalid date";break;case j.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:we.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case j.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case j.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case j.custom:r="Invalid input";break;case j.invalid_intersection_types:r="Intersection results could not be merged";break;case j.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case j.not_finite:r="Number must be finite";break;default:r=e.defaultError,we.assertNever(t)}return{message:r}},Rr=fR});function gR(t){jg=t}function no(){return jg}var jg,zi=O(()=>{Ml();jg=Rr});function Z(t,e){let r=no(),n=os({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Rr?void 0:Rr].filter(o=>!!o)});t.common.issues.push(n)}var os,yR,st,oe,yn,ht,ji,Di,Fr,oo,Ul=O(()=>{zi();Ml();os=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},yR=[];st=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return oe;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return oe;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},oe=Object.freeze({status:"aborted"}),yn=t=>({status:"dirty",value:t}),ht=t=>({status:"valid",value:t}),ji=t=>t.status==="aborted",Di=t=>t.status==="dirty",Fr=t=>t.status==="valid",oo=t=>typeof Promise<"u"&&t instanceof Promise});var Dg=O(()=>{});var G,Mg=O(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}))});function de(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function Bg(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function NR(t){return new RegExp(`^${Bg(t)}$`)}function Zg(t){let e=`${Fg}T${Bg(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function LR(t,e){return!!((e==="v4"||!e)&&RR.test(t)||(e==="v6"||!e)&&PR.test(t))}function zR(t,e){if(!xR.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function jR(t,e){return!!((e==="v4"||!e)&&ER.test(t)||(e==="v6"||!e)&&AR.test(t))}function DR(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function so(t){if(t instanceof St){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=xt.create(so(n))}return new St({...t._def,shape:()=>e})}else return t instanceof Ar?new Ar({...t._def,type:so(t.element)}):t instanceof xt?xt.create(so(t.unwrap())):t instanceof gr?gr.create(so(t.unwrap())):t instanceof fr?fr.create(t.items.map(e=>so(e))):t}function Fl(t,e){let r=mr(t),n=mr(e);if(t===e)return{valid:!0,data:t};if(r===V.object&&n===V.object){let o=we.objectKeys(e),s=we.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Fl(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===V.array&&n===V.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Fl(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===V.date&&n===V.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Vg(t,e){return new En({values:t,typeName:D.ZodEnum,...de(e)})}function qg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Hg(t,e={},r){return t?Zr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=qg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=qg(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Zr.create()}var Dt,Ug,he,bR,wR,_R,vR,kR,xR,SR,$R,TR,ql,RR,ER,PR,AR,CR,IR,Fg,OR,Br,bn,wn,_n,vn,io,kn,xn,Zr,Pr,Xt,ao,Ar,St,Sn,Er,Mi,$n,fr,Ui,co,lo,qi,Tn,Rn,En,Pn,Vr,Mt,xt,gr,An,Cn,uo,MR,ss,is,In,UR,D,qR,Kg,Wg,FR,BR,Gg,ZR,VR,HR,KR,WR,GR,JR,YR,XR,Bl,QR,eE,tE,rE,nE,oE,sE,iE,aE,cE,lE,uE,dE,pE,hE,mE,fE,gE,yE,bE,wE,_E,vE,kE,Jg=O(()=>{Li();zi();Mg();Ul();ns();Dt=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ug=(t,e)=>{if(Fr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new kt(t.common.issues);return this._error=r,this._error}}};he=class{get description(){return this._def.description}_getType(e){return mr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:mr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new st,ctx:{common:e.parent.common,data:e.data,parsedType:mr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(oo(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Ug(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Fr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Fr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(oo(o)?o:Promise.resolve(o));return Ug(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:j.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Mt({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return xt.create(this,this._def)}nullable(){return gr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ar.create(this)}promise(){return Vr.create(this,this._def)}or(e){return Sn.create([this,e],this._def)}and(e){return $n.create(this,e,this._def)}transform(e){return new Mt({...de(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new An({...de(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new ss({typeName:D.ZodBranded,type:this,...de(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Cn({...de(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return is.create(this,e)}readonly(){return In.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},bR=/^c[^\s-]{8,}$/i,wR=/^[0-9a-z]+$/,_R=/^[0-9A-HJKMNP-TV-Z]{26}$/i,vR=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,kR=/^[a-z0-9_-]{21}$/i,xR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,SR=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,$R=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,TR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",RR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ER=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,PR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,AR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,CR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,IR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Fg="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",OR=new RegExp(`^${Fg}$`);Br=class t extends he{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){let s=this._getOrReturnCtx(e);return Z(s,{code:j.invalid_type,expected:V.string,received:s.parsedType}),oe}let n=new st,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?Z(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Z(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")$R.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"email",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")ql||(ql=new RegExp(TR,"u")),ql.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"emoji",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")vR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"uuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")kR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"nanoid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")bR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")wR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid2",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")_R.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ulid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),Z(o,{validation:"url",code:j.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"regex",code:j.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Zg(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?OR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?NR(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?SR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"duration",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?LR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ip",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?zR(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"jwt",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?jR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cidr",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?CR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?IR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64url",code:j.invalid_string,message:s.message}),n.dirty()):we.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:j.invalid_string,...G.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...G.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...G.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...G.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...G.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...G.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...G.errToObj(r)})}nonempty(e){return this.min(1,G.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Br.create=t=>new Br({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...de(t)});bn=class t extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==V.number){let s=this._getOrReturnCtx(e);return Z(s,{code:j.invalid_type,expected:V.number,received:s.parsedType}),oe}let n,o=new st;for(let s of this._def.checks)s.kind==="int"?we.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:j.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?DR(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:j.not_finite,message:s.message}),o.dirty()):we.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&we.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};bn.create=t=>new bn({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...de(t)});wn=class t extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==V.bigint)return this._getInvalidInput(e);let n,o=new st;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):we.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Z(r,{code:j.invalid_type,expected:V.bigint,received:r.parsedType}),oe}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};wn.create=t=>new wn({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...de(t)});_n=class extends he{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.boolean,received:n.parsedType}),oe}return ht(e.data)}};_n.create=t=>new _n({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...de(t)});vn=class t extends he{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==V.date){let s=this._getOrReturnCtx(e);return Z(s,{code:j.invalid_type,expected:V.date,received:s.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Z(s,{code:j.invalid_date}),oe}let n=new st,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:j.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:j.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):we.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:G.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:G.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};vn.create=t=>new vn({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...de(t)});io=class extends he{_parse(e){if(this._getType(e)!==V.symbol){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.symbol,received:n.parsedType}),oe}return ht(e.data)}};io.create=t=>new io({typeName:D.ZodSymbol,...de(t)});kn=class extends he{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.undefined,received:n.parsedType}),oe}return ht(e.data)}};kn.create=t=>new kn({typeName:D.ZodUndefined,...de(t)});xn=class extends he{_parse(e){if(this._getType(e)!==V.null){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.null,received:n.parsedType}),oe}return ht(e.data)}};xn.create=t=>new xn({typeName:D.ZodNull,...de(t)});Zr=class extends he{constructor(){super(...arguments),this._any=!0}_parse(e){return ht(e.data)}};Zr.create=t=>new Zr({typeName:D.ZodAny,...de(t)});Pr=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ht(e.data)}};Pr.create=t=>new Pr({typeName:D.ZodUnknown,...de(t)});Xt=class extends he{_parse(e){let r=this._getOrReturnCtx(e);return Z(r,{code:j.invalid_type,expected:V.never,received:r.parsedType}),oe}};Xt.create=t=>new Xt({typeName:D.ZodNever,...de(t)});ao=class extends he{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.void,received:n.parsedType}),oe}return ht(e.data)}};ao.create=t=>new ao({typeName:D.ZodVoid,...de(t)});Ar=class t extends he{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==V.array)return Z(r,{code:j.invalid_type,expected:V.array,received:r.parsedType}),oe;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(Z(r,{code:i?j.too_big:j.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(Z(r,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(Z(r,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Dt(r,i,r.path,a)))).then(i=>st.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Dt(r,i,r.path,a)));return st.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:G.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:G.toString(r)}})}nonempty(e){return this.min(1,e)}};Ar.create=(t,e)=>new Ar({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...de(e)});St=class t extends he{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=we.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==V.object){let l=this._getOrReturnCtx(e);return Z(l,{code:j.invalid_type,expected:V.object,received:l.parsedType}),oe}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Xt&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Dt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Xt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(Z(o,{code:j.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Dt(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,b=await u.value;l.push({key:p,value:b,alwaysSet:u.alwaysSet})}return l}).then(l=>st.mergeObjectSync(n,l)):st.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return G.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:G.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of we.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of we.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return so(this)}partial(e){let r={};for(let n of we.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of we.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof xt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Vg(we.objectKeys(this.shape))}};St.create=(t,e)=>new St({shape:()=>t,unknownKeys:"strip",catchall:Xt.create(),typeName:D.ZodObject,...de(e)});St.strictCreate=(t,e)=>new St({shape:()=>t,unknownKeys:"strict",catchall:Xt.create(),typeName:D.ZodObject,...de(e)});St.lazycreate=(t,e)=>new St({shape:t,unknownKeys:"strip",catchall:Xt.create(),typeName:D.ZodObject,...de(e)});Sn=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new kt(a.ctx.common.issues));return Z(r,{code:j.invalid_union,unionErrors:i}),oe}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new kt(c));return Z(r,{code:j.invalid_union,unionErrors:a}),oe}}get options(){return this._def.options}};Sn.create=(t,e)=>new Sn({options:t,typeName:D.ZodUnion,...de(e)});Er=t=>t instanceof Tn?Er(t.schema):t instanceof Mt?Er(t.innerType()):t instanceof Rn?[t.value]:t instanceof En?t.options:t instanceof Pn?we.objectValues(t.enum):t instanceof An?Er(t._def.innerType):t instanceof kn?[void 0]:t instanceof xn?[null]:t instanceof xt?[void 0,...Er(t.unwrap())]:t instanceof gr?[null,...Er(t.unwrap())]:t instanceof ss||t instanceof In?Er(t.unwrap()):t instanceof Cn?Er(t._def.innerType):[],Mi=class t extends he{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.object)return Z(r,{code:j.invalid_type,expected:V.object,received:r.parsedType}),oe;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Z(r,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),oe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Er(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...de(n)})}};$n=class extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(ji(s)||ji(i))return oe;let a=Fl(s.value,i.value);return a.valid?((Di(s)||Di(i))&&r.dirty(),{status:r.value,value:a.data}):(Z(n,{code:j.invalid_intersection_types}),oe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};$n.create=(t,e,r)=>new $n({left:t,right:e,typeName:D.ZodIntersection,...de(r)});fr=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.array)return Z(n,{code:j.invalid_type,expected:V.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return Z(n,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;!this._def.rest&&n.data.length>this._def.items.length&&(Z(n,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Dt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>st.mergeArray(r,i)):st.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};fr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fr({items:t,typeName:D.ZodTuple,rest:null,...de(e)})};Ui=class t extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.object)return Z(n,{code:j.invalid_type,expected:V.object,received:n.parsedType}),oe;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Dt(n,a,n.path,a)),value:i._parse(new Dt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?st.mergeObjectAsync(r,o):st.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof he?new t({keyType:e,valueType:r,typeName:D.ZodRecord,...de(n)}):new t({keyType:Br.create(),valueType:e,typeName:D.ZodRecord,...de(r)})}},co=class extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.map)return Z(n,{code:j.invalid_type,expected:V.map,received:n.parsedType}),oe;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new Dt(n,a,n.path,[l,"key"])),value:s._parse(new Dt(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return oe;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return oe;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};co.create=(t,e,r)=>new co({valueType:e,keyType:t,typeName:D.ZodMap,...de(r)});lo=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.set)return Z(n,{code:j.invalid_type,expected:V.set,received:n.parsedType}),oe;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(Z(n,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(Z(n,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return oe;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new Dt(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:G.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};lo.create=(t,e)=>new lo({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...de(e)});qi=class t extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.function)return Z(r,{code:j.invalid_type,expected:V.function,received:r.parsedType}),oe;function n(a,c){return os({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,no(),Rr].filter(l=>!!l),issueData:{code:j.invalid_arguments,argumentsError:c}})}function o(a,c){return os({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,no(),Rr].filter(l=>!!l),issueData:{code:j.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Vr){let a=this;return ht(async function(...c){let l=new kt([]),u=await a._def.args.parseAsync(c,s).catch(f=>{throw l.addIssue(n(c,f)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(f=>{throw l.addIssue(o(p,f)),l})})}else{let a=this;return ht(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new kt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new kt([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:fr.create(e).rest(Pr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||fr.create([]).rest(Pr.create()),returns:r||Pr.create(),typeName:D.ZodFunction,...de(n)})}},Tn=class extends he{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Tn.create=(t,e)=>new Tn({getter:t,typeName:D.ZodLazy,...de(e)});Rn=class extends he{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Z(r,{received:r.data,code:j.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Rn.create=(t,e)=>new Rn({value:t,typeName:D.ZodLiteral,...de(e)});En=class t extends he{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{expected:we.joinValues(n),received:r.parsedType,code:j.invalid_type}),oe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{received:r.data,code:j.invalid_enum_value,options:n}),oe}return ht(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};En.create=Vg;Pn=class extends he{_parse(e){let r=we.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==V.string&&n.parsedType!==V.number){let o=we.objectValues(r);return Z(n,{expected:we.joinValues(o),received:n.parsedType,code:j.invalid_type}),oe}if(this._cache||(this._cache=new Set(we.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=we.objectValues(r);return Z(n,{received:n.data,code:j.invalid_enum_value,options:o}),oe}return ht(e.data)}get enum(){return this._def.values}};Pn.create=(t,e)=>new Pn({values:t,typeName:D.ZodNativeEnum,...de(e)});Vr=class extends he{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.promise&&r.common.async===!1)return Z(r,{code:j.invalid_type,expected:V.promise,received:r.parsedType}),oe;let n=r.parsedType===V.promise?r.data:Promise.resolve(r.data);return ht(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Vr.create=(t,e)=>new Vr({type:t,typeName:D.ZodPromise,...de(e)});Mt=class extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{Z(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return oe;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?oe:c.status==="dirty"?yn(c.value):r.value==="dirty"?yn(c.value):c});{if(r.value==="aborted")return oe;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?oe:a.status==="dirty"?yn(a.value):r.value==="dirty"?yn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?oe:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?oe:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Fr(i))return oe;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Fr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):oe);we.assertNever(o)}};Mt.create=(t,e,r)=>new Mt({schema:t,typeName:D.ZodEffects,effect:e,...de(r)});Mt.createWithPreprocess=(t,e,r)=>new Mt({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...de(r)});xt=class extends he{_parse(e){return this._getType(e)===V.undefined?ht(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xt.create=(t,e)=>new xt({innerType:t,typeName:D.ZodOptional,...de(e)});gr=class extends he{_parse(e){return this._getType(e)===V.null?ht(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gr.create=(t,e)=>new gr({innerType:t,typeName:D.ZodNullable,...de(e)});An=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===V.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};An.create=(t,e)=>new An({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...de(e)});Cn=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return oo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new kt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new kt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Cn.create=(t,e)=>new Cn({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...de(e)});uo=class extends he{_parse(e){if(this._getType(e)!==V.nan){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}};uo.create=t=>new uo({typeName:D.ZodNaN,...de(t)});MR=Symbol("zod_brand"),ss=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},is=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?oe:s.status==="dirty"?(r.dirty(),yn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?oe:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:D.ZodPipeline})}},In=class extends he{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Fr(o)&&(o.value=Object.freeze(o.value)),o);return oo(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};In.create=(t,e)=>new In({innerType:t,typeName:D.ZodReadonly,...de(e)});UR={object:St.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={}));qR=(t,e={message:`Input not instance of ${t.name}`})=>Hg(r=>r instanceof t,e),Kg=Br.create,Wg=bn.create,FR=uo.create,BR=wn.create,Gg=_n.create,ZR=vn.create,VR=io.create,HR=kn.create,KR=xn.create,WR=Zr.create,GR=Pr.create,JR=Xt.create,YR=ao.create,XR=Ar.create,Bl=St.create,QR=St.strictCreate,eE=Sn.create,tE=Mi.create,rE=$n.create,nE=fr.create,oE=Ui.create,sE=co.create,iE=lo.create,aE=qi.create,cE=Tn.create,lE=Rn.create,uE=En.create,dE=Pn.create,pE=Vr.create,hE=Mt.create,mE=xt.create,fE=gr.create,gE=Mt.createWithPreprocess,yE=is.create,bE=()=>Kg().optional(),wE=()=>Wg().optional(),_E=()=>Gg().optional(),vE={string:(t=>Br.create({...t,coerce:!0})),number:(t=>bn.create({...t,coerce:!0})),boolean:(t=>_n.create({...t,coerce:!0})),bigint:(t=>wn.create({...t,coerce:!0})),date:(t=>vn.create({...t,coerce:!0}))},kE=oe});var E={};es(E,{BRAND:()=>MR,DIRTY:()=>yn,EMPTY_PATH:()=>yR,INVALID:()=>oe,NEVER:()=>kE,OK:()=>ht,ParseStatus:()=>st,Schema:()=>he,ZodAny:()=>Zr,ZodArray:()=>Ar,ZodBigInt:()=>wn,ZodBoolean:()=>_n,ZodBranded:()=>ss,ZodCatch:()=>Cn,ZodDate:()=>vn,ZodDefault:()=>An,ZodDiscriminatedUnion:()=>Mi,ZodEffects:()=>Mt,ZodEnum:()=>En,ZodError:()=>kt,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>qi,ZodIntersection:()=>$n,ZodIssueCode:()=>j,ZodLazy:()=>Tn,ZodLiteral:()=>Rn,ZodMap:()=>co,ZodNaN:()=>uo,ZodNativeEnum:()=>Pn,ZodNever:()=>Xt,ZodNull:()=>xn,ZodNullable:()=>gr,ZodNumber:()=>bn,ZodObject:()=>St,ZodOptional:()=>xt,ZodParsedType:()=>V,ZodPipeline:()=>is,ZodPromise:()=>Vr,ZodReadonly:()=>In,ZodRecord:()=>Ui,ZodSchema:()=>he,ZodSet:()=>lo,ZodString:()=>Br,ZodSymbol:()=>io,ZodTransformer:()=>Mt,ZodTuple:()=>fr,ZodType:()=>he,ZodUndefined:()=>kn,ZodUnion:()=>Sn,ZodUnknown:()=>Pr,ZodVoid:()=>ao,addIssueToContext:()=>Z,any:()=>WR,array:()=>XR,bigint:()=>BR,boolean:()=>Gg,coerce:()=>vE,custom:()=>Hg,date:()=>ZR,datetimeRegex:()=>Zg,defaultErrorMap:()=>Rr,discriminatedUnion:()=>tE,effect:()=>hE,enum:()=>uE,function:()=>aE,getErrorMap:()=>no,getParsedType:()=>mr,instanceof:()=>qR,intersection:()=>rE,isAborted:()=>ji,isAsync:()=>oo,isDirty:()=>Di,isValid:()=>Fr,late:()=>UR,lazy:()=>cE,literal:()=>lE,makeIssue:()=>os,map:()=>sE,nan:()=>FR,nativeEnum:()=>dE,never:()=>JR,null:()=>KR,nullable:()=>fE,number:()=>Wg,object:()=>Bl,objectUtil:()=>Dl,oboolean:()=>_E,onumber:()=>wE,optional:()=>mE,ostring:()=>bE,pipeline:()=>yE,preprocess:()=>gE,promise:()=>pE,quotelessJson:()=>mR,record:()=>oE,set:()=>iE,setErrorMap:()=>gR,strictObject:()=>QR,string:()=>Kg,symbol:()=>VR,transformer:()=>hE,tuple:()=>nE,undefined:()=>HR,union:()=>eE,unknown:()=>GR,util:()=>we,void:()=>YR});var Fi=O(()=>{zi();Ul();Dg();ns();Jg();Li()});var On=O(()=>{Fi();Fi()});function Bi(t){let e=Zl.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Vl(t,e){let r=Zl.safeParse(t);if(!r.success)throw new Hr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Yg.test(e))throw new Hr('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let n=JSON.stringify(r.data);if(Yg.test(n))throw new Hr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Xg,Qg,Zl,Hr,Yg,ey=O(()=>{On();Xg=E.object({type:E.literal("connection"),source_system:E.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:E.string().min(1).max(200).optional()}),Qg=E.discriminatedUnion("type",[Xg]),Zl=E.object({inputs:E.array(Qg).optional()}).passthrough(),Hr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Yg=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Zi,Hl=O(()=>{Zi=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var Kl,ty,ry=O(()=>{On();rs();Hl();Kl=E.object({id:E.string().min(1,"hook id must be non-empty"),recordType:E.union([E.string().min(1),E.array(E.string().min(1)).min(1),E.literal("*")]),event:E.enum(Zi),source:E.string().min(1).optional(),when:E.unknown().optional(),run:E.unknown(),failClosed:E.boolean().optional(),timeoutMs:E.number().int().positive().optional(),description:E.string().optional(),systemReserved:E.boolean().optional()}).superRefine((t,e)=>{typeof t.run!="function"&&e.addIssue({code:"custom",path:["run"],message:"run must be a function"}),"when"in t&&t.when!==void 0&&typeof t.when!="function"&&e.addIssue({code:"custom",path:["when"],message:"when, when present, must be a function"})}),ty=gn({kind:"hook",schema:Kl,factoryName:"defineHook"})});var ny=O(()=>{ry();Hl()});var Vi,Wl=O(()=>{Vi=["after_canonicalize_inbound","after_sync_success_outbound"]});var oy,$E,sy,Gl,iy,ay=O(()=>{On();rs();Wl();oy=E.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),$E=E.object({recordType:E.string().min(1,"reads[].recordType must be non-empty"),source:E.string().min(1).optional(),columns:E.array(oy).min(1,"reads[].columns must name at least one column"),by:E.array(oy).optional(),maxRows:E.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),sy=E.object({source:E.string().min(1,"to.source must be non-empty"),recordType:E.string().min(1,"to.recordType must be non-empty")}),Gl=E.object({id:E.string().min(1,"conduit id must be non-empty"),on:E.enum(Vi),from:E.object({source:E.string().min(1,"from.source must be non-empty"),recordType:E.string().min(1,"from.recordType must be non-empty"),when:E.unknown().optional()}),to:sy.optional(),mode:E.enum(["dual-bind","one-shot"]).optional(),transform:E.unknown().optional(),sequence:E.array(E.object({to:sy,transform:E.unknown(),awaitSource:E.boolean().optional()})).optional(),reads:E.array($E).optional(),maxQueriesPerRun:E.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:E.unknown().optional(),cycleBudget:E.number().int().positive().optional(),conflictStrategy:E.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:E.number().int().positive().optional(),description:E.string().optional(),systemReserved:E.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((l,u)=>{typeof l.transform!="function"&&e.addIssue({code:"custom",path:["sequence",u,"transform"],message:"transform must be a function"}),r.from?.source&&l.to?.source&&r.from.source===l.to.source&&e.addIssue({code:"custom",path:["sequence",u,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,c=r.to;a?.source&&c?.source&&a.source===c.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),iy=gn({kind:"conduit",schema:Gl,factoryName:"defineConduit"})});var cy=O(()=>{ay();Wl()});function uy(t,e,r){let n=e;(typeof n.recordType!="string"||n.recordType.length===0)&&t.addIssue({code:"custom",path:[...r,"recordType"],message:"step.recordType must be non-empty"}),typeof n.build!="function"&&t.addIssue({code:"custom",path:[...r,"build"],message:"build must be a function"}),n.when!==void 0&&typeof n.when!="function"&&t.addIssue({code:"custom",path:[...r,"when"],message:"when must be a function returning whether this step runs"});let o=n.update;if(o){for(let s of["pgRowId","externalId","expectedSyncVersion"]){let i=o[s];i!==void 0&&typeof i!="function"&&t.addIssue({code:"custom",path:[...r,"update",s],message:`update.${s} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}o.step===void 0&&o.pgRowId===void 0&&o.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"update"],message:"update must address a record: one of `step`, `pgRowId` or `externalId`"})}}function OE(t,e,r){e.forEach===void 0&&t.addIssue({code:"custom",path:["steps",r,"forEach"],message:"a step-list entry carrying nested steps must declare forEach.input, naming the input property to repeat over"});let n=e.steps;if(!Array.isArray(n)||n.length===0){t.addIssue({code:"custom",path:["steps",r,"steps"],message:"a repeated group needs at least one step in it, or it writes nothing at all"});return}let o=new Map;n.forEach((s,i)=>{uy(t,s,["steps",r,"steps",i]);let a=s.id;if(typeof a!="string")return;let c=o.get(a);c!==void 0?t.addIssue({code:"custom",path:["steps",r,"steps"],message:`duplicate step id '${a}' (steps ${c} and ${i}) \u2014 step ids must be unique within a repeated group`}):o.set(a,i)})}var ly,CE,IE,Jl,dy,py=O(()=>{On();rs();ly={id:E.string().min(1,"step id must be non-empty"),recordType:E.string().min(1,"step.recordType must be non-empty").optional(),awaitSource:E.boolean().optional(),update:E.object({step:E.string().min(1,"update.step must name an earlier step").optional(),pgRowId:E.unknown().optional(),externalId:E.unknown().optional(),expectedSyncVersion:E.unknown().optional()}).optional(),when:E.unknown().optional(),rollback:E.enum(["undo","keep"]).optional(),build:E.unknown(),description:E.string().optional()},CE=E.object(ly),IE=E.object({...ly,forEach:E.object({input:E.string().min(1,"forEach.input must name a property of the process input holding the array to repeat over")}).optional(),steps:E.array(CE).optional()}),Jl=E.object({id:E.string().min(1,"process id must be non-empty"),input:E.object({type:E.literal("object"),properties:E.record(E.unknown()).optional(),required:E.array(E.string()).optional()}).passthrough(),steps:E.array(IE).min(1,"a process needs at least one step"),eachRow:E.object({outstanding:E.unknown(),key:E.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:E.enum(["stop","rollback"]).optional(),description:E.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(a.forEach!==void 0||a.steps!==void 0?OE(e,a,i):uy(e,s,["steps",i]),typeof a.id=="string"){let c=o.get(a.id);c!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${c} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})});dy=gn({kind:"process",schema:Jl,factoryName:"defineProcess"})});var hy=O(()=>{});var my=O(()=>{py();hy()});async function DE(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function Wi(t,e={}){return(e.transform??DE)(t)}var Yl=O(()=>{});function Xl(t){switch(t.toLowerCase().trim()){case"boolean":return"boolean";case"smallint":case"integer":case"bigint":case"numeric":case"decimal":case"real":case"double precision":return"number";case"text":case"character varying":case"character":case"varchar":case"char":case"uuid":case"name":case"citext":return"string";case"timestamp with time zone":case"timestamp without time zone":case"timestamp":case"date":case"time":case"time with time zone":case"time without time zone":return"string";case"json":case"jsonb":return"unknown";case"array":return"unknown[]";default:return"unknown"}}function fy(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Ql(t){return`${fy(t.source)}${fy(t.recordType)}`}function ME(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function UE(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function eu(t){let e=Ql(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
|
|
24
|
+
`)}),this}};function Eg(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function Pg(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",o="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?o=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],o=s[4]),r&&o!=="0"?`${r}=${n}:${parseInt(o)+1}`:e})}Ag.Command=Dl});var Lg=B((Yt,Ng)=>{var{Argument:mR}=Ni(),{Command:Ig}=Cg(),{CommanderError:fR,InvalidArgumentError:Og}=ns(),{Help:gR}=Cl(),{Option:yR}=Nl();Yt=Ng.exports=new Ig;Yt.program=Yt;Yt.Command=Ig;Yt.Option=yR;Yt.Argument=mR;Yt.Help=gR;Yt.CommanderError=fR;Yt.InvalidArgumentError=Og;Yt.InvalidOptionArgumentError=Og});function gn(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var os=N(()=>{});var _e,Ml,V,mr,ss=N(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(_e||(_e={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ml||(Ml={}));V=_e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mr=t=>{switch(typeof t){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(t)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(t)?V.array:t===null?V.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?V.promise:typeof Map<"u"&&t instanceof Map?V.map:typeof Set<"u"&&t instanceof Set?V.set:typeof Date<"u"&&t instanceof Date?V.date:V.object;default:return V.unknown}}});var z,bR,kt,ji=N(()=>{ss();z=_e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),bR=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),kt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,_e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};kt.create=t=>new kt(t)});var wR,Rr,Ul=N(()=>{ji();ss();wR=(t,e)=>{let r;switch(t.code){case z.invalid_type:t.received===V.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,_e.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:r=`Unrecognized key(s) in object: ${_e.joinValues(t.keys,", ")}`;break;case z.invalid_union:r="Invalid input";break;case z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${_e.joinValues(t.options)}`;break;case z.invalid_enum_value:r=`Invalid enum value. Expected ${_e.joinValues(t.options)}, received '${t.received}'`;break;case z.invalid_arguments:r="Invalid function arguments";break;case z.invalid_return_type:r="Invalid function return type";break;case z.invalid_date:r="Invalid date";break;case z.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:_e.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case z.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case z.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case z.custom:r="Invalid input";break;case z.invalid_intersection_types:r="Intersection results could not be merged";break;case z.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case z.not_finite:r="Number must be finite";break;default:r=e.defaultError,_e.assertNever(t)}return{message:r}},Rr=wR});function _R(t){Dg=t}function oo(){return Dg}var Dg,zi=N(()=>{Ul();Dg=Rr});function Z(t,e){let r=oo(),n=is({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Rr?void 0:Rr].filter(o=>!!o)});t.common.issues.push(n)}var is,vR,st,oe,yn,ht,Di,Mi,Fr,so,ql=N(()=>{zi();Ul();is=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},vR=[];st=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return oe;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return oe;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},oe=Object.freeze({status:"aborted"}),yn=t=>({status:"dirty",value:t}),ht=t=>({status:"valid",value:t}),Di=t=>t.status==="aborted",Mi=t=>t.status==="dirty",Fr=t=>t.status==="valid",so=t=>typeof Promise<"u"&&t instanceof Promise});var Mg=N(()=>{});var J,Ug=N(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(J||(J={}))});function de(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function Zg(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function DR(t){return new RegExp(`^${Zg(t)}$`)}function Vg(t){let e=`${Bg}T${Zg(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function MR(t,e){return!!((e==="v4"||!e)&&CR.test(t)||(e==="v6"||!e)&&OR.test(t))}function UR(t,e){if(!RR.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function qR(t,e){return!!((e==="v4"||!e)&&IR.test(t)||(e==="v6"||!e)&&NR.test(t))}function FR(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function io(t){if(t instanceof St){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=xt.create(io(n))}return new St({...t._def,shape:()=>e})}else return t instanceof Ar?new Ar({...t._def,type:io(t.element)}):t instanceof xt?xt.create(io(t.unwrap())):t instanceof gr?gr.create(io(t.unwrap())):t instanceof fr?fr.create(t.items.map(e=>io(e))):t}function Bl(t,e){let r=mr(t),n=mr(e);if(t===e)return{valid:!0,data:t};if(r===V.object&&n===V.object){let o=_e.objectKeys(e),s=_e.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Bl(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===V.array&&n===V.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Bl(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===V.date&&n===V.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Hg(t,e){return new En({values:t,typeName:D.ZodEnum,...de(e)})}function Fg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Kg(t,e={},r){return t?Zr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Fg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Fg(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Zr.create()}var Dt,qg,he,kR,xR,SR,$R,TR,RR,ER,PR,AR,Fl,CR,IR,OR,NR,LR,jR,Bg,zR,Br,bn,wn,_n,vn,ao,kn,xn,Zr,Pr,Xt,co,Ar,St,Sn,Er,Ui,$n,fr,qi,lo,uo,Fi,Tn,Rn,En,Pn,Vr,Mt,xt,gr,An,Cn,po,BR,as,cs,In,ZR,D,VR,Wg,Gg,HR,KR,Jg,WR,GR,JR,YR,XR,QR,eE,tE,rE,Zl,nE,oE,sE,iE,aE,cE,lE,uE,dE,pE,hE,mE,fE,gE,yE,bE,wE,_E,vE,kE,xE,SE,$E,TE,Yg=N(()=>{ji();zi();Ug();ql();ss();Dt=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},qg=(t,e)=>{if(Fr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new kt(t.common.issues);return this._error=r,this._error}}};he=class{get description(){return this._def.description}_getType(e){return mr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:mr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new st,ctx:{common:e.parent.common,data:e.data,parsedType:mr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(so(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return qg(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Fr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Fr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(so(o)?o:Promise.resolve(o));return qg(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:z.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Mt({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return xt.create(this,this._def)}nullable(){return gr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ar.create(this)}promise(){return Vr.create(this,this._def)}or(e){return Sn.create([this,e],this._def)}and(e){return $n.create(this,e,this._def)}transform(e){return new Mt({...de(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new An({...de(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new as({typeName:D.ZodBranded,type:this,...de(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Cn({...de(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return cs.create(this,e)}readonly(){return In.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},kR=/^c[^\s-]{8,}$/i,xR=/^[0-9a-z]+$/,SR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$R=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,TR=/^[a-z0-9_-]{21}$/i,RR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ER=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,PR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,AR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",CR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,IR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,OR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,NR=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,LR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Bg="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",zR=new RegExp(`^${Bg}$`);Br=class t extends he{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_type,expected:V.string,received:s.parsedType}),oe}let n=new st,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?Z(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Z(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")PR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"email",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Fl||(Fl=new RegExp(AR,"u")),Fl.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"emoji",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")$R.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"uuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")TR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"nanoid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")kR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")xR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid2",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")SR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ulid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),Z(o,{validation:"url",code:z.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"regex",code:z.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Vg(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?zR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?DR(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:z.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?ER.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"duration",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?MR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ip",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?UR(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"jwt",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?qR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cidr",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?LR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?jR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64url",code:z.invalid_string,message:s.message}),n.dirty()):_e.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:z.invalid_string,...J.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...J.errToObj(e)})}url(e){return this._addCheck({kind:"url",...J.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...J.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...J.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...J.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...J.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...J.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...J.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...J.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...J.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...J.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...J.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...J.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...J.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...J.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...J.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...J.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...J.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...J.errToObj(r)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Br.create=t=>new Br({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...de(t)});bn=class t extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==V.number){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_type,expected:V.number,received:s.parsedType}),oe}let n,o=new st;for(let s of this._def.checks)s.kind==="int"?_e.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:z.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?FR(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:z.not_finite,message:s.message}),o.dirty()):_e.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,J.toString(r))}gt(e,r){return this.setLimit("min",e,!1,J.toString(r))}lte(e,r){return this.setLimit("max",e,!0,J.toString(r))}lt(e,r){return this.setLimit("max",e,!1,J.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:J.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:J.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:J.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&_e.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};bn.create=t=>new bn({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...de(t)});wn=class t extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==V.bigint)return this._getInvalidInput(e);let n,o=new st;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):_e.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Z(r,{code:z.invalid_type,expected:V.bigint,received:r.parsedType}),oe}gte(e,r){return this.setLimit("min",e,!0,J.toString(r))}gt(e,r){return this.setLimit("min",e,!1,J.toString(r))}lte(e,r){return this.setLimit("max",e,!0,J.toString(r))}lt(e,r){return this.setLimit("max",e,!1,J.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:J.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};wn.create=t=>new wn({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...de(t)});_n=class extends he{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:V.boolean,received:n.parsedType}),oe}return ht(e.data)}};_n.create=t=>new _n({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...de(t)});vn=class t extends he{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==V.date){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_type,expected:V.date,received:s.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Z(s,{code:z.invalid_date}),oe}let n=new st,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:z.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):_e.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:J.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:J.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};vn.create=t=>new vn({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...de(t)});ao=class extends he{_parse(e){if(this._getType(e)!==V.symbol){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:V.symbol,received:n.parsedType}),oe}return ht(e.data)}};ao.create=t=>new ao({typeName:D.ZodSymbol,...de(t)});kn=class extends he{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:V.undefined,received:n.parsedType}),oe}return ht(e.data)}};kn.create=t=>new kn({typeName:D.ZodUndefined,...de(t)});xn=class extends he{_parse(e){if(this._getType(e)!==V.null){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:V.null,received:n.parsedType}),oe}return ht(e.data)}};xn.create=t=>new xn({typeName:D.ZodNull,...de(t)});Zr=class extends he{constructor(){super(...arguments),this._any=!0}_parse(e){return ht(e.data)}};Zr.create=t=>new Zr({typeName:D.ZodAny,...de(t)});Pr=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ht(e.data)}};Pr.create=t=>new Pr({typeName:D.ZodUnknown,...de(t)});Xt=class extends he{_parse(e){let r=this._getOrReturnCtx(e);return Z(r,{code:z.invalid_type,expected:V.never,received:r.parsedType}),oe}};Xt.create=t=>new Xt({typeName:D.ZodNever,...de(t)});co=class extends he{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:V.void,received:n.parsedType}),oe}return ht(e.data)}};co.create=t=>new co({typeName:D.ZodVoid,...de(t)});Ar=class t extends he{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==V.array)return Z(r,{code:z.invalid_type,expected:V.array,received:r.parsedType}),oe;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(Z(r,{code:i?z.too_big:z.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(Z(r,{code:z.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(Z(r,{code:z.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Dt(r,i,r.path,a)))).then(i=>st.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Dt(r,i,r.path,a)));return st.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:J.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:J.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:J.toString(r)}})}nonempty(e){return this.min(1,e)}};Ar.create=(t,e)=>new Ar({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...de(e)});St=class t extends he{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=_e.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==V.object){let l=this._getOrReturnCtx(e);return Z(l,{code:z.invalid_type,expected:V.object,received:l.parsedType}),oe}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Xt&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Dt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Xt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(Z(o,{code:z.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Dt(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,b=await u.value;l.push({key:p,value:b,alwaysSet:u.alwaysSet})}return l}).then(l=>st.mergeObjectSync(n,l)):st.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return J.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:J.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of _e.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of _e.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return io(this)}partial(e){let r={};for(let n of _e.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of _e.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof xt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Hg(_e.objectKeys(this.shape))}};St.create=(t,e)=>new St({shape:()=>t,unknownKeys:"strip",catchall:Xt.create(),typeName:D.ZodObject,...de(e)});St.strictCreate=(t,e)=>new St({shape:()=>t,unknownKeys:"strict",catchall:Xt.create(),typeName:D.ZodObject,...de(e)});St.lazycreate=(t,e)=>new St({shape:t,unknownKeys:"strip",catchall:Xt.create(),typeName:D.ZodObject,...de(e)});Sn=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new kt(a.ctx.common.issues));return Z(r,{code:z.invalid_union,unionErrors:i}),oe}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new kt(c));return Z(r,{code:z.invalid_union,unionErrors:a}),oe}}get options(){return this._def.options}};Sn.create=(t,e)=>new Sn({options:t,typeName:D.ZodUnion,...de(e)});Er=t=>t instanceof Tn?Er(t.schema):t instanceof Mt?Er(t.innerType()):t instanceof Rn?[t.value]:t instanceof En?t.options:t instanceof Pn?_e.objectValues(t.enum):t instanceof An?Er(t._def.innerType):t instanceof kn?[void 0]:t instanceof xn?[null]:t instanceof xt?[void 0,...Er(t.unwrap())]:t instanceof gr?[null,...Er(t.unwrap())]:t instanceof as||t instanceof In?Er(t.unwrap()):t instanceof Cn?Er(t._def.innerType):[],Ui=class t extends he{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.object)return Z(r,{code:z.invalid_type,expected:V.object,received:r.parsedType}),oe;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(Z(r,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),oe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Er(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...de(n)})}};$n=class extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Di(s)||Di(i))return oe;let a=Bl(s.value,i.value);return a.valid?((Mi(s)||Mi(i))&&r.dirty(),{status:r.value,value:a.data}):(Z(n,{code:z.invalid_intersection_types}),oe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};$n.create=(t,e,r)=>new $n({left:t,right:e,typeName:D.ZodIntersection,...de(r)});fr=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.array)return Z(n,{code:z.invalid_type,expected:V.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return Z(n,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oe;!this._def.rest&&n.data.length>this._def.items.length&&(Z(n,{code:z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Dt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>st.mergeArray(r,i)):st.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};fr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fr({items:t,typeName:D.ZodTuple,rest:null,...de(e)})};qi=class t extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.object)return Z(n,{code:z.invalid_type,expected:V.object,received:n.parsedType}),oe;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Dt(n,a,n.path,a)),value:i._parse(new Dt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?st.mergeObjectAsync(r,o):st.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof he?new t({keyType:e,valueType:r,typeName:D.ZodRecord,...de(n)}):new t({keyType:Br.create(),valueType:e,typeName:D.ZodRecord,...de(r)})}},lo=class extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.map)return Z(n,{code:z.invalid_type,expected:V.map,received:n.parsedType}),oe;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new Dt(n,a,n.path,[l,"key"])),value:s._parse(new Dt(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return oe;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return oe;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};lo.create=(t,e,r)=>new lo({valueType:e,keyType:t,typeName:D.ZodMap,...de(r)});uo=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.set)return Z(n,{code:z.invalid_type,expected:V.set,received:n.parsedType}),oe;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(Z(n,{code:z.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(Z(n,{code:z.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return oe;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new Dt(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:J.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:J.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};uo.create=(t,e)=>new uo({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...de(e)});Fi=class t extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.function)return Z(r,{code:z.invalid_type,expected:V.function,received:r.parsedType}),oe;function n(a,c){return is({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,oo(),Rr].filter(l=>!!l),issueData:{code:z.invalid_arguments,argumentsError:c}})}function o(a,c){return is({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,oo(),Rr].filter(l=>!!l),issueData:{code:z.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Vr){let a=this;return ht(async function(...c){let l=new kt([]),u=await a._def.args.parseAsync(c,s).catch(f=>{throw l.addIssue(n(c,f)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(f=>{throw l.addIssue(o(p,f)),l})})}else{let a=this;return ht(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new kt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new kt([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:fr.create(e).rest(Pr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||fr.create([]).rest(Pr.create()),returns:r||Pr.create(),typeName:D.ZodFunction,...de(n)})}},Tn=class extends he{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Tn.create=(t,e)=>new Tn({getter:t,typeName:D.ZodLazy,...de(e)});Rn=class extends he{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Z(r,{received:r.data,code:z.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Rn.create=(t,e)=>new Rn({value:t,typeName:D.ZodLiteral,...de(e)});En=class t extends he{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{expected:_e.joinValues(n),received:r.parsedType,code:z.invalid_type}),oe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{received:r.data,code:z.invalid_enum_value,options:n}),oe}return ht(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};En.create=Hg;Pn=class extends he{_parse(e){let r=_e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==V.string&&n.parsedType!==V.number){let o=_e.objectValues(r);return Z(n,{expected:_e.joinValues(o),received:n.parsedType,code:z.invalid_type}),oe}if(this._cache||(this._cache=new Set(_e.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=_e.objectValues(r);return Z(n,{received:n.data,code:z.invalid_enum_value,options:o}),oe}return ht(e.data)}get enum(){return this._def.values}};Pn.create=(t,e)=>new Pn({values:t,typeName:D.ZodNativeEnum,...de(e)});Vr=class extends he{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.promise&&r.common.async===!1)return Z(r,{code:z.invalid_type,expected:V.promise,received:r.parsedType}),oe;let n=r.parsedType===V.promise?r.data:Promise.resolve(r.data);return ht(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Vr.create=(t,e)=>new Vr({type:t,typeName:D.ZodPromise,...de(e)});Mt=class extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{Z(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return oe;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?oe:c.status==="dirty"?yn(c.value):r.value==="dirty"?yn(c.value):c});{if(r.value==="aborted")return oe;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?oe:a.status==="dirty"?yn(a.value):r.value==="dirty"?yn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?oe:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?oe:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Fr(i))return oe;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Fr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):oe);_e.assertNever(o)}};Mt.create=(t,e,r)=>new Mt({schema:t,typeName:D.ZodEffects,effect:e,...de(r)});Mt.createWithPreprocess=(t,e,r)=>new Mt({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...de(r)});xt=class extends he{_parse(e){return this._getType(e)===V.undefined?ht(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xt.create=(t,e)=>new xt({innerType:t,typeName:D.ZodOptional,...de(e)});gr=class extends he{_parse(e){return this._getType(e)===V.null?ht(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gr.create=(t,e)=>new gr({innerType:t,typeName:D.ZodNullable,...de(e)});An=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===V.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};An.create=(t,e)=>new An({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...de(e)});Cn=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return so(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new kt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new kt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Cn.create=(t,e)=>new Cn({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...de(e)});po=class extends he{_parse(e){if(this._getType(e)!==V.nan){let n=this._getOrReturnCtx(e);return Z(n,{code:z.invalid_type,expected:V.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}};po.create=t=>new po({typeName:D.ZodNaN,...de(t)});BR=Symbol("zod_brand"),as=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},cs=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?oe:s.status==="dirty"?(r.dirty(),yn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?oe:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:D.ZodPipeline})}},In=class extends he{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Fr(o)&&(o.value=Object.freeze(o.value)),o);return so(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};In.create=(t,e)=>new In({innerType:t,typeName:D.ZodReadonly,...de(e)});ZR={object:St.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={}));VR=(t,e={message:`Input not instance of ${t.name}`})=>Kg(r=>r instanceof t,e),Wg=Br.create,Gg=bn.create,HR=po.create,KR=wn.create,Jg=_n.create,WR=vn.create,GR=ao.create,JR=kn.create,YR=xn.create,XR=Zr.create,QR=Pr.create,eE=Xt.create,tE=co.create,rE=Ar.create,Zl=St.create,nE=St.strictCreate,oE=Sn.create,sE=Ui.create,iE=$n.create,aE=fr.create,cE=qi.create,lE=lo.create,uE=uo.create,dE=Fi.create,pE=Tn.create,hE=Rn.create,mE=En.create,fE=Pn.create,gE=Vr.create,yE=Mt.create,bE=xt.create,wE=gr.create,_E=Mt.createWithPreprocess,vE=cs.create,kE=()=>Wg().optional(),xE=()=>Gg().optional(),SE=()=>Jg().optional(),$E={string:(t=>Br.create({...t,coerce:!0})),number:(t=>bn.create({...t,coerce:!0})),boolean:(t=>_n.create({...t,coerce:!0})),bigint:(t=>wn.create({...t,coerce:!0})),date:(t=>vn.create({...t,coerce:!0}))},TE=oe});var P={};rs(P,{BRAND:()=>BR,DIRTY:()=>yn,EMPTY_PATH:()=>vR,INVALID:()=>oe,NEVER:()=>TE,OK:()=>ht,ParseStatus:()=>st,Schema:()=>he,ZodAny:()=>Zr,ZodArray:()=>Ar,ZodBigInt:()=>wn,ZodBoolean:()=>_n,ZodBranded:()=>as,ZodCatch:()=>Cn,ZodDate:()=>vn,ZodDefault:()=>An,ZodDiscriminatedUnion:()=>Ui,ZodEffects:()=>Mt,ZodEnum:()=>En,ZodError:()=>kt,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Fi,ZodIntersection:()=>$n,ZodIssueCode:()=>z,ZodLazy:()=>Tn,ZodLiteral:()=>Rn,ZodMap:()=>lo,ZodNaN:()=>po,ZodNativeEnum:()=>Pn,ZodNever:()=>Xt,ZodNull:()=>xn,ZodNullable:()=>gr,ZodNumber:()=>bn,ZodObject:()=>St,ZodOptional:()=>xt,ZodParsedType:()=>V,ZodPipeline:()=>cs,ZodPromise:()=>Vr,ZodReadonly:()=>In,ZodRecord:()=>qi,ZodSchema:()=>he,ZodSet:()=>uo,ZodString:()=>Br,ZodSymbol:()=>ao,ZodTransformer:()=>Mt,ZodTuple:()=>fr,ZodType:()=>he,ZodUndefined:()=>kn,ZodUnion:()=>Sn,ZodUnknown:()=>Pr,ZodVoid:()=>co,addIssueToContext:()=>Z,any:()=>XR,array:()=>rE,bigint:()=>KR,boolean:()=>Jg,coerce:()=>$E,custom:()=>Kg,date:()=>WR,datetimeRegex:()=>Vg,defaultErrorMap:()=>Rr,discriminatedUnion:()=>sE,effect:()=>yE,enum:()=>mE,function:()=>dE,getErrorMap:()=>oo,getParsedType:()=>mr,instanceof:()=>VR,intersection:()=>iE,isAborted:()=>Di,isAsync:()=>so,isDirty:()=>Mi,isValid:()=>Fr,late:()=>ZR,lazy:()=>pE,literal:()=>hE,makeIssue:()=>is,map:()=>lE,nan:()=>HR,nativeEnum:()=>fE,never:()=>eE,null:()=>YR,nullable:()=>wE,number:()=>Gg,object:()=>Zl,objectUtil:()=>Ml,oboolean:()=>SE,onumber:()=>xE,optional:()=>bE,ostring:()=>kE,pipeline:()=>vE,preprocess:()=>_E,promise:()=>gE,quotelessJson:()=>bR,record:()=>cE,set:()=>uE,setErrorMap:()=>_R,strictObject:()=>nE,string:()=>Wg,symbol:()=>GR,transformer:()=>yE,tuple:()=>aE,undefined:()=>JR,union:()=>oE,unknown:()=>QR,util:()=>_e,void:()=>tE});var Bi=N(()=>{zi();ql();Mg();ss();Yg();ji()});var On=N(()=>{Bi();Bi()});function Zi(t){let e=Vl.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Hl(t,e){let r=Vl.safeParse(t);if(!r.success)throw new Hr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Xg.test(e))throw new Hr('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let n=JSON.stringify(r.data);if(Xg.test(n))throw new Hr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Qg,ey,Vl,Hr,Xg,ty=N(()=>{On();Qg=P.object({type:P.literal("connection"),source_system:P.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:P.string().min(1).max(200).optional()}),ey=P.discriminatedUnion("type",[Qg]),Vl=P.object({inputs:P.array(ey).optional()}).passthrough(),Hr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Xg=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Vi,Kl=N(()=>{Vi=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var Wl,ry,ny=N(()=>{On();os();Kl();Wl=P.object({id:P.string().min(1,"hook id must be non-empty"),recordType:P.union([P.string().min(1),P.array(P.string().min(1)).min(1),P.literal("*")]),event:P.enum(Vi),source:P.string().min(1).optional(),when:P.unknown().optional(),run:P.unknown(),failClosed:P.boolean().optional(),timeoutMs:P.number().int().positive().optional(),description:P.string().optional(),systemReserved:P.boolean().optional()}).superRefine((t,e)=>{typeof t.run!="function"&&e.addIssue({code:"custom",path:["run"],message:"run must be a function"}),"when"in t&&t.when!==void 0&&typeof t.when!="function"&&e.addIssue({code:"custom",path:["when"],message:"when, when present, must be a function"})}),ry=gn({kind:"hook",schema:Wl,factoryName:"defineHook"})});var oy=N(()=>{ny();Kl()});var Hi,Gl=N(()=>{Hi=["after_canonicalize_inbound","after_sync_success_outbound"]});var sy,PE,iy,Jl,ay,cy=N(()=>{On();os();Gl();sy=P.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),PE=P.object({recordType:P.string().min(1,"reads[].recordType must be non-empty"),source:P.string().min(1).optional(),columns:P.array(sy).min(1,"reads[].columns must name at least one column"),by:P.array(sy).optional(),maxRows:P.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),iy=P.object({source:P.string().min(1,"to.source must be non-empty"),recordType:P.string().min(1,"to.recordType must be non-empty")}),Jl=P.object({id:P.string().min(1,"conduit id must be non-empty"),on:P.enum(Hi),from:P.object({source:P.string().min(1,"from.source must be non-empty"),recordType:P.string().min(1,"from.recordType must be non-empty"),when:P.unknown().optional()}),to:iy.optional(),mode:P.enum(["dual-bind","one-shot"]).optional(),transform:P.unknown().optional(),sequence:P.array(P.object({to:iy,transform:P.unknown(),awaitSource:P.boolean().optional()})).optional(),reads:P.array(PE).optional(),maxQueriesPerRun:P.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:P.unknown().optional(),cycleBudget:P.number().int().positive().optional(),conflictStrategy:P.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:P.number().int().positive().optional(),description:P.string().optional(),systemReserved:P.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((l,u)=>{typeof l.transform!="function"&&e.addIssue({code:"custom",path:["sequence",u,"transform"],message:"transform must be a function"}),r.from?.source&&l.to?.source&&r.from.source===l.to.source&&e.addIssue({code:"custom",path:["sequence",u,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,c=r.to;a?.source&&c?.source&&a.source===c.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),ay=gn({kind:"conduit",schema:Jl,factoryName:"defineConduit"})});var ly=N(()=>{cy();Gl()});function dy(t,e,r){let n=e;(typeof n.recordType!="string"||n.recordType.length===0)&&t.addIssue({code:"custom",path:[...r,"recordType"],message:"step.recordType must be non-empty"}),typeof n.build!="function"&&t.addIssue({code:"custom",path:[...r,"build"],message:"build must be a function"}),n.when!==void 0&&typeof n.when!="function"&&t.addIssue({code:"custom",path:[...r,"when"],message:"when must be a function returning whether this step runs"});let o=n.update;if(o){for(let s of["pgRowId","externalId","expectedSyncVersion"]){let i=o[s];i!==void 0&&typeof i!="function"&&t.addIssue({code:"custom",path:[...r,"update",s],message:`update.${s} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}o.step===void 0&&o.pgRowId===void 0&&o.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"update"],message:"update must address a record: one of `step`, `pgRowId` or `externalId`"})}}function zE(t,e,r){e.forEach===void 0&&t.addIssue({code:"custom",path:["steps",r,"forEach"],message:"a step-list entry carrying nested steps must declare forEach.input, naming the input property to repeat over"});let n=e.steps;if(!Array.isArray(n)||n.length===0){t.addIssue({code:"custom",path:["steps",r,"steps"],message:"a repeated group needs at least one step in it, or it writes nothing at all"});return}let o=new Map;n.forEach((s,i)=>{dy(t,s,["steps",r,"steps",i]);let a=s.id;if(typeof a!="string")return;let c=o.get(a);c!==void 0?t.addIssue({code:"custom",path:["steps",r,"steps"],message:`duplicate step id '${a}' (steps ${c} and ${i}) \u2014 step ids must be unique within a repeated group`}):o.set(a,i)})}var uy,LE,jE,Yl,py,hy=N(()=>{On();os();uy={id:P.string().min(1,"step id must be non-empty"),recordType:P.string().min(1,"step.recordType must be non-empty").optional(),awaitSource:P.boolean().optional(),update:P.object({step:P.string().min(1,"update.step must name an earlier step").optional(),pgRowId:P.unknown().optional(),externalId:P.unknown().optional(),expectedSyncVersion:P.unknown().optional()}).optional(),when:P.unknown().optional(),rollback:P.enum(["undo","keep"]).optional(),build:P.unknown(),description:P.string().optional()},LE=P.object(uy),jE=P.object({...uy,forEach:P.object({input:P.string().min(1,"forEach.input must name a property of the process input holding the array to repeat over")}).optional(),steps:P.array(LE).optional()}),Yl=P.object({id:P.string().min(1,"process id must be non-empty"),input:P.object({type:P.literal("object"),properties:P.record(P.unknown()).optional(),required:P.array(P.string()).optional()}).passthrough(),steps:P.array(jE).min(1,"a process needs at least one step"),eachRow:P.object({outstanding:P.unknown(),key:P.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:P.enum(["stop","rollback"]).optional(),description:P.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(a.forEach!==void 0||a.steps!==void 0?zE(e,a,i):dy(e,s,["steps",i]),typeof a.id=="string"){let c=o.get(a.id);c!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${c} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})});py=gn({kind:"process",schema:Yl,factoryName:"defineProcess"})});var my=N(()=>{});var fy=N(()=>{hy();my()});async function FE(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function Gi(t,e={}){return(e.transform??FE)(t)}var Xl=N(()=>{});function Ql(t){switch(t.toLowerCase().trim()){case"boolean":return"boolean";case"smallint":case"integer":case"bigint":case"numeric":case"decimal":case"real":case"double precision":return"number";case"text":case"character varying":case"character":case"varchar":case"char":case"uuid":case"name":case"citext":return"string";case"timestamp with time zone":case"timestamp without time zone":case"timestamp":case"date":case"time":case"time with time zone":case"time without time zone":return"string";case"json":case"jsonb":return"unknown";case"array":return"unknown[]";default:return"unknown"}}function gy(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function eu(t){return`${gy(t.source)}${gy(t.recordType)}`}function BE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function ZE(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function tu(t){let e=eu(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
|
|
25
25
|
* ${r.join(`
|
|
26
26
|
* `)}
|
|
27
27
|
*/`;if(t.columns.length===0)return`${n}
|
|
28
28
|
export interface ${e} {
|
|
29
29
|
// no columns introspected
|
|
30
30
|
[key: string]: unknown;
|
|
31
|
-
}`;let o=t.columns.map(s=>{let i=
|
|
32
|
-
${
|
|
31
|
+
}`;let o=t.columns.map(s=>{let i=Ql(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${ZE(s)} */
|
|
32
|
+
${BE(s.name)}${a}: ${i}${c};`});return`${n}
|
|
33
33
|
export interface ${e} {
|
|
34
34
|
${o.join(`
|
|
35
35
|
`)}
|
|
36
|
-
}`}function
|
|
36
|
+
}`}function Ji(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(tu).join(`
|
|
37
37
|
|
|
38
|
-
`)}function
|
|
39
|
-
`)}var
|
|
38
|
+
`)}function yy(t){let e=new Map,r=(o,s)=>{let i=e.get(o);i||e.set(o,i=new Map);for(let a of s)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let o of t.records){o.table&&r(o.table,o.columns);for(let s of o.lines??[])r(s.table,s.columns)}let n={};for(let[o,s]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>s.get(a)===!1);if(s.get("parent_pg_row_id")===!1&&i){n[o]=["parent_pg_row_id",i];continue}if(s.get("pg_row_id")===!1){n[o]="pg_row_id";continue}if(s.get("external_id")===!1){n[o]="external_id";continue}}return n}function VE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function ru(t){let e=yy(t);return["/**"," * The seek key each table can be keyset-paged on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>{let s=Array.isArray(o)?`[${o.map(i=>`'${i}'`).join(", ")}]`:`'${o}'`;return` ${VE(n)}: ${s},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
|
|
39
|
+
`)}var nu=N(()=>{});function HE(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function by(t,e,r){let n=await r(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`types-gen: GET ${t} failed (${n.status} ${n.statusText})`);return n.json()}async function Nn(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=HE(t.baseUrl),n=await by(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=Ji(n),s=[KE,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",ru(n)];if(!t.recordsOnly){let i=await by(r.openapi,t.token,e),a=await Gi(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
|
|
40
40
|
|
|
41
41
|
`)+`
|
|
42
|
-
`}var
|
|
43
|
-
`)});var
|
|
44
|
-
`,{mode:384})}async function
|
|
45
|
-
`)}function
|
|
46
|
-
`)}function Xi(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(l=>new Promise(u=>setTimeout(u,l))),s=e.now??(()=>Date.now()),i=e.onWait??YE,a=e.onGiveUp??XE;return async(l,u)=>{let p=s(),b=0;for(;;){let f=await t(l,u);if(f.status!==503||u&&!JE(u.body))return f;let h=r-(s()-p),{maintenance:w,delayMs:S,error:R}=await GE(f,s());if(!w)return f;if(h<=0)return b>0&&a({waitedMs:s()-p,attempts:b,host:ky(l),error:R}),f;let A=S??n;A=Math.min(Math.max(A,1e3),12e4),A=Math.min(A,h),b+=1,i({attempt:b,delayMs:A,remainingMs:h,host:ky(l),error:R}),await o(A)}}}var lu=O(()=>{});function xy(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t;if(typeof e.message=="string"&&e.message.trim())return e.message.trim();let r=typeof e.error=="string"?e.error.trim():"",n=typeof e.reason=="string"?e.reason.trim():"";return n?r?`${r}: ${n}`:n:r}function QE(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function Sy(t){let e=xy(t);return typeof t=="string"&&QE(e)?e0:e.slice(0,200)}function $y(t,e){return cu(t,e)}function Ty(t){return t instanceof le&&$y(t.status,t.body)}function r0(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Ry(t){return t.replace(/\/+$/,"")}function uu(t=process.env){let e=(t[po]??"").trim(),r=(t[Qi]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function du(t){let e;try{e=new URL(t)}catch{return`${po} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&r?null:`${po} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var le,e0,t0,K,po,Qi,ls,er=O(()=>{lu();le=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};e0="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";t0="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";K=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Ry(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=e.retry===!1?r:Xi(r,e.retry??{})}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){if(r0()){let l=xy(a);throw new le(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}if($y(s.status,a))throw new le(t0,s.status,a);let c=Sy(a);throw new le(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}async proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async processes(){return(await this.request("GET","/v1/processes")).processes??[]}async processRuns(e){return(await this.request("GET",`/v1/processes/${encodeURIComponent(e)}/runs`)).runs??[]}async processRun(e){return this.request("GET",`/v1/processes/runs/${encodeURIComponent(e)}`)}async cancelProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/cancel`)}async platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},po="TURBOBASE_REGISTRY_URL",Qi="TURBOBASE_REGISTRY_TOKEN";ls=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Ry(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=Sy(a);throw new le(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});import{existsSync as n0,statSync as o0}from"node:fs";import{resolve as ea,sep as Ey}from"node:path";function Py(t){if(i0.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function c0(t,e,r){let n=ea(e,r),o=ea(t);if(n!==o&&!n.startsWith(o+Ey))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+Ey)&&n0(i)&&o0(i).isFile())return i;return null}function Ay(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Py(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=c0(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||u0(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:a0,loader:"js"}))}}}function u0(t){let e=t.startsWith("node:")?t.slice(5):t;return l0.has(e.split("/")[0])}function Cy(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function Iy(){try{return(await import("esbuild")).build}catch(t){throw Cy("esbuild",t)}}async function d0(){try{return(await import("isolated-vm")).default}catch(t){throw Cy("isolated-vm",t)}}async function na(t,e={}){let r=await Iy(),n=e.resolveDir?ea(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[Ay(n)]})}catch(s){let a=s.errors?.map(c=>c.text).filter(Boolean).join("; ");throw new ta(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function pu(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Iy(),n=ea(e),o=Ay(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},c=>c.kind==="entry-point"?null:Py(c.path)?{path:c.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let l=a.errors?.map(u=>u.text).filter(Boolean).join("; ");throw new ta(l||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function us(t,e,r={}){let n=r.timeoutMs??ra,o=r.memoryLimitMb??s0,s=r.member??"run",i={patches:[],logs:[]},a=await d0(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(F=>{let W=JSON.parse(String(F));i.rejection||(i.rejection=W)}),b=new a.Callback(F=>{i.patches.push(JSON.parse(String(F)))}),f=new a.Callback(F=>{let W=JSON.parse(String(F));i.logs.push(W)}),h=new a.Callback(F=>{i.result=JSON.parse(String(F))}),w=r.query,S=new a.Reference(async F=>{if(!w)throw new Error("ctx.query is not available in this context");return JSON.stringify(await w(String(F)))});await u.set("__tb_reject",p),await u.set("__tb_patch",b),await u.set("__tb_log",f),await u.set("__tb_result",h),await u.set("__tb_query",S),await u.set("__tb_ctx_json",JSON.stringify(p0(e)));let R=m0(t,s,r.stepIndex??0,r.stepPath??[r.stepIndex??0],!!r.query),L=await(await c.compileScript(R)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!L}:{effects:i}}finally{c.isDisposed||c.dispose()}}function p0(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null,materialized:t.materialized??null,process:t.process??null}}function h0(t){return`
|
|
42
|
+
`}var KE,wy=N(()=>{Xl();nu();nu();Xl();KE=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
|
|
43
|
+
`)});var ou=N(()=>{os();ty();oy();ly();fy();wy()});import{homedir as WE}from"node:os";import{join as _y}from"node:path";import{promises as su}from"node:fs";function Ut(t){return t.trim().replace(/\/+$/,"")}function Yi(){let t=process.env.TURBOBASE_HOME??_y(WE(),".turbobase");return{dir:t,file:_y(t,"credentials")}}function vy(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function ls(){let{file:t}=Yi(),e;try{let s=await su.readFile(t,"utf8");e=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,c]of Object.entries(r.tenants))vy(c)&&(s[a]={token:c.token,updatedAt:c.updatedAt});return{active:typeof r.active=="string"&&s[r.active]?r.active:void 0,tenants:s}}let n={};for(let[s,i]of Object.entries(r))vy(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:GE(n),tenants:n}}function GE(t){let e,r="";for(let[n,o]of Object.entries(t))(!e||String(o.updatedAt)>r)&&(e=n,r=String(o.updatedAt));return e}async function iu(t){let{dir:e,file:r}=Yi();await su.mkdir(e,{recursive:!0,mode:448}),await su.writeFile(r,JSON.stringify(t,null,2)+`
|
|
44
|
+
`,{mode:384})}async function ky(t){let e=Ut(t.baseUrl),r=await ls(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await iu(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Qt(t){let e=await ls();if(t){let s=Ut(t),i=e.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let o=e.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function Xi(t){let e=Ut(t),r=await ls(),n=r.tenants[e];return n?(r.active=e,await iu(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function au(t){let e=await ls(),r=t?Ut(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!r||!e.tenants[r])return null;if(delete e.tenants[r],e.active===r){let n=Object.keys(e.tenants);e.active=n.length===1?n[0]:void 0}return await iu(e),r}async function Cr(){let t=await ls();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var us=N(()=>{});function lu(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function JE(t){if(t)try{return JSON.parse(t)}catch{return t}}function YE(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function XE(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function QE(t,e){let r=YE(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=JE(n),s=lu(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??XE(n),error:i}}function e0(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function xy(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function cu(t){return`${Math.round(t/1e3)}s`}function t0(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${cu(t.delayMs)} before retrying (${cu(t.remainingMs)} of the retry budget left).
|
|
45
|
+
`)}function r0(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${cu(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
|
|
46
|
+
`)}function Qi(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(l=>new Promise(u=>setTimeout(u,l))),s=e.now??(()=>Date.now()),i=e.onWait??t0,a=e.onGiveUp??r0;return async(l,u)=>{let p=s(),b=0;for(;;){let f=await t(l,u);if(f.status!==503||u&&!e0(u.body))return f;let m=r-(s()-p),{maintenance:w,delayMs:$,error:R}=await QE(f,s());if(!w)return f;if(m<=0)return b>0&&a({waitedMs:s()-p,attempts:b,host:xy(l),error:R}),f;let A=$??n;A=Math.min(Math.max(A,1e3),12e4),A=Math.min(A,m),b+=1,i({attempt:b,delayMs:A,remainingMs:m,host:xy(l),error:R}),await o(A)}}}var uu=N(()=>{});function Sy(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t;if(typeof e.message=="string"&&e.message.trim())return e.message.trim();let r=typeof e.error=="string"?e.error.trim():"",n=typeof e.reason=="string"?e.reason.trim():"";return n?r?`${r}: ${n}`:n:r}function n0(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function $y(t){let e=Sy(t);return typeof t=="string"&&n0(e)?o0:e.slice(0,200)}function Ty(t,e){return lu(t,e)}function Ry(t){return t instanceof se&&Ty(t.status,t.body)}function i0(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Ey(t){return t.replace(/\/+$/,"")}function du(t=process.env){let e=(t[ho]??"").trim(),r=(t[ea]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function pu(t){let e;try{e=new URL(t)}catch{return`${ho} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&r?null:`${ho} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var se,o0,s0,K,ho,ea,ds,er=N(()=>{uu();se=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};o0="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";s0="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";K=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Ey(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=e.retry===!1?r:Qi(r,e.retry??{})}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){if(i0()){let l=Sy(a);throw new se(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}if(Ty(s.status,a))throw new se(s0,s.status,a);let c=$y(a);throw new se(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}async proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async processes(){return(await this.request("GET","/v1/processes")).processes??[]}async processRuns(e){return(await this.request("GET",`/v1/processes/${encodeURIComponent(e)}/runs`)).runs??[]}async processRun(e){return this.request("GET",`/v1/processes/runs/${encodeURIComponent(e)}`)}async invokeProcess(e,r,n="async"){let o=n==="sync"?"?mode=sync":"";return this.request("POST",`/v1/processes/${encodeURIComponent(e)}${o}`,r)}async settleRow(e,r){return this.request("POST",`/v1/data/${encodeURIComponent(e)}/settle`,{pgRowId:r})}async cancelProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/cancel`)}async rollbackProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/rollback`)}async platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},ho="TURBOBASE_REGISTRY_URL",ea="TURBOBASE_REGISTRY_TOKEN";ds=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Ey(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let c=$y(a);throw new se(`${e} ${r} \u2192 ${s.status}${c?`: ${c}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});import{existsSync as a0,statSync as c0}from"node:fs";import{resolve as ta,sep as Py}from"node:path";function Ay(t){if(u0.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function p0(t,e,r){let n=ta(e,r),o=ta(t);if(n!==o&&!n.startsWith(o+Py))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+Py)&&a0(i)&&c0(i).isFile())return i;return null}function Cy(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Ay(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=p0(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||m0(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:d0,loader:"js"}))}}}function m0(t){let e=t.startsWith("node:")?t.slice(5):t;return h0.has(e.split("/")[0])}function Iy(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function Oy(){try{return(await import("esbuild")).build}catch(t){throw Iy("esbuild",t)}}async function f0(){try{return(await import("isolated-vm")).default}catch(t){throw Iy("isolated-vm",t)}}async function oa(t,e={}){let r=await Oy(),n=e.resolveDir?ta(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[Cy(n)]})}catch(s){let a=s.errors?.map(c=>c.text).filter(Boolean).join("; ");throw new ra(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function hu(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Oy(),n=ta(e),o=Cy(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},c=>c.kind==="entry-point"?null:Ay(c.path)?{path:c.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let l=a.errors?.map(u=>u.text).filter(Boolean).join("; ");throw new ra(l||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function ps(t,e,r={}){let n=r.timeoutMs??na,o=r.memoryLimitMb??l0,s=r.member??"run",i={patches:[],logs:[]},a=await f0(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(F=>{let W=JSON.parse(String(F));i.rejection||(i.rejection=W)}),b=new a.Callback(F=>{i.patches.push(JSON.parse(String(F)))}),f=new a.Callback(F=>{let W=JSON.parse(String(F));i.logs.push(W)}),m=new a.Callback(F=>{i.result=JSON.parse(String(F))}),w=r.query,$=new a.Reference(async F=>{if(!w)throw new Error("ctx.query is not available in this context");return JSON.stringify(await w(String(F)))});await u.set("__tb_reject",p),await u.set("__tb_patch",b),await u.set("__tb_log",f),await u.set("__tb_result",m),await u.set("__tb_query",$),await u.set("__tb_ctx_json",JSON.stringify(g0(e)));let R=b0(t,s,r.stepIndex??0,r.stepPath??[r.stepIndex??0],!!r.query),L=await(await c.compileScript(R)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!L}:{effects:i}}finally{c.isDisposed||c.dispose()}}function g0(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null,materialized:t.materialized??null,process:t.process??null}}function y0(t){return`
|
|
47
47
|
"use strict";
|
|
48
48
|
(async () => {
|
|
49
49
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -66,7 +66,7 @@ ${o.join(`
|
|
|
66
66
|
__tb_result(JSON.stringify(out == null ? null : String(out)));
|
|
67
67
|
return undefined;
|
|
68
68
|
})()
|
|
69
|
-
`}function
|
|
69
|
+
`}function b0(t,e,r,n,o=!1){return e==="build"?_0(t,n):e==="prompt"?w0(t,n):e==="outstanding"?y0(t):`
|
|
70
70
|
"use strict";
|
|
71
71
|
(async () => {
|
|
72
72
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -147,7 +147,7 @@ ${o.join(`
|
|
|
147
147
|
${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":e==="idempotencyKey"?"__tb_result(JSON.stringify(out == null ? null : String(out)));":""}
|
|
148
148
|
return ${e==="when"?"out":"undefined"};
|
|
149
149
|
})()
|
|
150
|
-
`}function
|
|
150
|
+
`}function w0(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
|
|
151
151
|
"use strict";
|
|
152
152
|
(async () => {
|
|
153
153
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -192,7 +192,7 @@ ${o.join(`
|
|
|
192
192
|
__tb_result(String(out == null ? '' : out));
|
|
193
193
|
return undefined;
|
|
194
194
|
})()
|
|
195
|
-
`}function
|
|
195
|
+
`}function _0(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
|
|
196
196
|
"use strict";
|
|
197
197
|
(async () => {
|
|
198
198
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -263,12 +263,12 @@ ${o.join(`
|
|
|
263
263
|
__tb_result(JSON.stringify({ declined: out == null, address: address, write: out == null ? null : out }));
|
|
264
264
|
return undefined;
|
|
265
265
|
})()
|
|
266
|
-
`}var
|
|
266
|
+
`}var na,l0,u0,d0,ra,h0,sa=N(()=>{na=200,l0=16,u0=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@/sync/processes","@/sync/processes/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit","@turbobase/extensions/process"]);d0=`
|
|
267
267
|
export const defineHook = (def) => def;
|
|
268
268
|
export const defineConduit = (def) => def;
|
|
269
269
|
export const defineProcess = (def) => def;
|
|
270
270
|
export default defineHook;
|
|
271
|
-
`;
|
|
271
|
+
`;ra=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};h0=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","http2","https","net","os","path","process","querystring","readline","stream","string_decoder","timers","tls","tty","url","util","v8","vm","worker_threads","zlib"])});import{promises as mu}from"node:fs";import{join as v0}from"node:path";function k0(t){return{recordType:t.recordType??"unknown",event:t.event??"before_save",direction:t.direction??"standalone",origin:t.origin??"user",source:t.source??null,payload:t.payload??{},prior:t.prior,user:t.user,tenantConfig:t.tenantConfig??{},metadata:t.metadata}}async function x0(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await ps(t,k0(e.context)),i=s.rejection?"reject":"pass";return{name:n,expected:o,observed:i,pass:i===o,rejection:s.rejection,patchCount:s.patches.length}}catch(s){return{name:n,expected:o,observed:"pass",pass:!1,patchCount:0,error:s instanceof Error?s.message:String(s)}}}async function ia(t,e,r={}){let n=await oa(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await x0(n,e[s],`sample[${s}]`));return o}async function hs(t){let e;try{e=await mu.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let o=await mu.readFile(v0(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let c=i[a];r.push({file:n,fixture:{...c,name:c.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function ms(t){return mu.readFile(t,"utf8")}var fu=N(()=>{sa()});function Tt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function yP(t){let e=t.recordType;if(!e)throw new Rt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
|
|
272
272
|
source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
|
|
273
273
|
run: (ctx) => {
|
|
274
274
|
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
@@ -306,7 +306,7 @@ export default defineHook<Record<string, unknown>>({
|
|
|
306
306
|
recordType: ${JSON.stringify(e)},
|
|
307
307
|
event: ${JSON.stringify(r)},${s}${i}
|
|
308
308
|
});
|
|
309
|
-
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function
|
|
309
|
+
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function bP(t){let e=t.recordType;if(!e)throw new Rt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Rt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Rt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Rt(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=t.toRecordType??e,s=t.event??"after_canonicalize_inbound",i=t.id??`${Tt(r)}2${Tt(n)}:${Tt(e)}`,c=`/**
|
|
310
310
|
* ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
|
|
311
311
|
*
|
|
312
312
|
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
@@ -349,7 +349,7 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
349
349
|
},
|
|
350
350
|
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
351
351
|
});
|
|
352
|
-
`;return{relativePath:`conduits/${Tt(r)}-${Tt(e)}-to-${Tt(n)}-${Tt(o)}.ts`,content:c}}function
|
|
352
|
+
`;return{relativePath:`conduits/${Tt(r)}-${Tt(e)}-to-${Tt(n)}-${Tt(o)}.ts`,content:c}}function wP(t){let e=t.recordType;if(!e)throw new Rt("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Rt(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${Tt(e)}-then-${Tt(r)}`:Tt(e),s=t.id??`custom:process:${o}`,i=t.description??(r?`Raise a ${e}, wait for the source, then raise a ${r}.`:`Raise a ${e}.`),a=r?`
|
|
353
353
|
{
|
|
354
354
|
id: ${JSON.stringify(Tt(r))},
|
|
355
355
|
recordType: ${JSON.stringify(r)},
|
|
@@ -398,7 +398,7 @@ export default defineProcess({
|
|
|
398
398
|
],
|
|
399
399
|
onFailure: ${JSON.stringify(n)},
|
|
400
400
|
});
|
|
401
|
-
`;return{relativePath:`processes/${o}.ts`,content:c}}function yr(t,e){let r=
|
|
401
|
+
`;return{relativePath:`processes/${o}.ts`,content:c}}function yr(t,e){let r=_P[t];if(!r)throw new Rt(`unknown extension kind '${t}'. Scaffoldable kinds: ${fb.join(", ")}.`);return r(e)}var fb,Rt,_P,pa=N(()=>{fb=["hook","conduit","process"];Rt=class extends Error{};_P={hook:yP,conduit:bP,process:wP}});var Du,Mu=N(()=>{Du=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function UC(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e>>>0}function qC(t){return Hw[UC(t)%Hw.length]}function FC(t){let e=t.trim().split(/[\s\-_.]+/).filter(r=>/[a-z0-9]/i.test(r));return e.length===0?t.trim().slice(0,1).toUpperCase()||"\u2022":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase()}function Kw(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Ww(t,e){let[r,n]=qC(t),o=Kw(FC(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Kw(e)}">
|
|
402
402
|
<defs>
|
|
403
403
|
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
404
404
|
<stop offset="0" stop-color="${r}"/>
|
|
@@ -408,9 +408,9 @@ export default defineProcess({
|
|
|
408
408
|
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
409
409
|
<text x="32" y="34" text-anchor="middle" dominant-baseline="central" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="26" font-weight="600" fill="#ffffff">${o}</text>
|
|
410
410
|
</svg>
|
|
411
|
-
`}var
|
|
412
|
-
`}function
|
|
413
|
-
`}function
|
|
411
|
+
`}var Hw,Gw=N(()=>{Hw=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var d_={};rs(d_,{CN_UTIL:()=>t_,COMPONENTS_JSON:()=>e_,MAIN_TSX:()=>n_,STYLES_CSS:()=>o_,TSCONFIG:()=>Qw,TURBOBASE_CLIENT:()=>Jw,UI_BADGE:()=>a_,UI_BUTTON:()=>s_,UI_CARD:()=>i_,UI_INPUT:()=>l_,UI_LABEL:()=>u_,UI_TABLE:()=>c_,indexHtml:()=>r_,instanceOriginFromEnv:()=>YC,packageJson:()=>Yw,scaffoldAppFiles:()=>QC,starterApp:()=>eI,viteConfig:()=>Xw});function VC(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function HC(t){let e={name:VC(t.title,ZC)},r=(t.description??"").trim().slice(0,BC);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Du},JSON.stringify(e,null,2)+`
|
|
412
|
+
`}function Yw(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:KC},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^19.2.0","@types/react-dom":"^19.2.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
|
|
413
|
+
`}function JC(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}function YC(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Xw(t,e={}){let r=JC(e.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
414
414
|
import { fileURLToPath, URL } from 'node:url';
|
|
415
415
|
import react from '@vitejs/plugin-react';
|
|
416
416
|
// Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
|
|
@@ -429,8 +429,8 @@ import tailwindcss from '@tailwindcss/vite';
|
|
|
429
429
|
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
430
430
|
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
431
431
|
// them at boot; restart the dev server after changing one).
|
|
432
|
-
const TENANT = process.env.SUPABASE_URL || '${r??
|
|
433
|
-
const API = process.env.TURBOBASE_API_URL || '${r??
|
|
432
|
+
const TENANT = process.env.SUPABASE_URL || '${r??WC}'; // /rest + the Realtime WS
|
|
433
|
+
const API = process.env.TURBOBASE_API_URL || '${r??GC}'; // /v1, /auth, /login, /_app
|
|
434
434
|
|
|
435
435
|
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
436
436
|
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
@@ -468,7 +468,7 @@ export default defineConfig({
|
|
|
468
468
|
},
|
|
469
469
|
build: { outDir: 'dist' },
|
|
470
470
|
});
|
|
471
|
-
`}function
|
|
471
|
+
`}function r_(t){return`<!doctype html>
|
|
472
472
|
<html lang="en">
|
|
473
473
|
<head>
|
|
474
474
|
<meta charset="UTF-8" />
|
|
@@ -481,7 +481,7 @@ export default defineConfig({
|
|
|
481
481
|
<script type="module" src="/src/main.tsx"></script>
|
|
482
482
|
</body>
|
|
483
483
|
</html>
|
|
484
|
-
`}function
|
|
484
|
+
`}function QC(t){return{"package.json":Yw(t.slug),"vite.config.ts":Xw(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":XC,"tsconfig.json":Qw,"index.html":r_(t.title),"public/turbobase.json":HC(t),"public/favicon.svg":Ww(t.slug,t.title),"src/main.tsx":n_,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Jw,"src/styles.css":o_,"components.json":e_,"src/lib/utils.ts":t_,"src/components/ui/button.tsx":s_,"src/components/ui/card.tsx":i_,"src/components/ui/badge.tsx":a_,"src/components/ui/table.tsx":c_,"src/components/ui/input.tsx":l_,"src/components/ui/label.tsx":u_,"README.md":`# ${t.title}
|
|
485
485
|
|
|
486
486
|
\`\`\`sh
|
|
487
487
|
npm install
|
|
@@ -502,7 +502,7 @@ every read comes back "permission denied", which looks like an RLS problem.
|
|
|
502
502
|
|
|
503
503
|
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
504
504
|
live access token and is gitignored \u2014 keep it that way.
|
|
505
|
-
`}}function
|
|
505
|
+
`}}function eI(t){return`import React from 'react';
|
|
506
506
|
import { Loader2, Trash2 } from 'lucide-react';
|
|
507
507
|
|
|
508
508
|
import { select, write, del } from '@/lib/turbobase';
|
|
@@ -727,7 +727,7 @@ export default function App() {
|
|
|
727
727
|
</main>
|
|
728
728
|
);
|
|
729
729
|
}
|
|
730
|
-
`}var
|
|
730
|
+
`}var BC,ZC,Jw,$s,KC,WC,GC,XC,Qw,e_,t_,n_,o_,s_,i_,a_,c_,l_,u_,p_=N(()=>{Gw();Mu();BC=200,ZC=60;Jw=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
|
|
731
731
|
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
732
732
|
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
733
733
|
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
@@ -1980,7 +1980,7 @@ export async function cancelProcessRun(runId: string): Promise<{ cancelled: bool
|
|
|
1980
1980
|
if (!res.ok) throw await writeError(res, 'process run');
|
|
1981
1981
|
return (await res.json()) as { cancelled: boolean };
|
|
1982
1982
|
}
|
|
1983
|
-
|
|
1983
|
+
`,$s="src/types.ts",KC=`turbobase project types -o ${$s} || node -e "if(require('node:fs').existsSync('${$s}')){console.error('turbobase: could not refresh ${$s} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${$s} is missing. It is generated from the instance catalog and gitignored, so a fresh checkout has no copy. Run: turbobase auth login --base-url <your-instance> --token tb_pat_... , then turbobase project types -o ${$s}');process.exit(1)}"`;WC="http://localhost:54331",GC="http://localhost:4100";XC=`node_modules/
|
|
1984
1984
|
dist/
|
|
1985
1985
|
build/
|
|
1986
1986
|
|
|
@@ -1992,9 +1992,9 @@ build/
|
|
|
1992
1992
|
!.env.example
|
|
1993
1993
|
|
|
1994
1994
|
.DS_Store
|
|
1995
|
-
`,
|
|
1996
|
-
`,
|
|
1997
|
-
`,
|
|
1995
|
+
`,Qw=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
|
|
1996
|
+
`,e_=`${JSON.stringify({$schema:"https://ui.shadcn.com/schema.json",style:"new-york",rsc:!1,tsx:!0,tailwind:{config:"",css:"src/styles.css",baseColor:"neutral",cssVariables:!0,prefix:""},aliases:{components:"@/components",utils:"@/lib/utils",ui:"@/components/ui",lib:"@/lib",hooks:"@/hooks"},iconLibrary:"lucide"},null,2)}
|
|
1997
|
+
`,t_=`import { clsx, type ClassValue } from 'clsx';
|
|
1998
1998
|
import { twMerge } from 'tailwind-merge';
|
|
1999
1999
|
|
|
2000
2000
|
/**
|
|
@@ -2008,7 +2008,7 @@ import { twMerge } from 'tailwind-merge';
|
|
|
2008
2008
|
export function cn(...inputs: ClassValue[]) {
|
|
2009
2009
|
return twMerge(clsx(inputs));
|
|
2010
2010
|
}
|
|
2011
|
-
`;
|
|
2011
|
+
`;n_=`import React from 'react';
|
|
2012
2012
|
import { createRoot } from 'react-dom/client';
|
|
2013
2013
|
import App from './App';
|
|
2014
2014
|
import './styles.css';
|
|
@@ -2018,7 +2018,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
2018
2018
|
<App />
|
|
2019
2019
|
</React.StrictMode>,
|
|
2020
2020
|
);
|
|
2021
|
-
`,
|
|
2021
|
+
`,o_=`@import 'tailwindcss';
|
|
2022
2022
|
@import 'tw-animate-css';
|
|
2023
2023
|
|
|
2024
2024
|
/* Inter, self-hosted \u2014 the design system's font.
|
|
@@ -2106,7 +2106,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
2106
2106
|
transition-duration: 0.01ms !important;
|
|
2107
2107
|
}
|
|
2108
2108
|
}
|
|
2109
|
-
`,
|
|
2109
|
+
`,s_=`import * as React from 'react';
|
|
2110
2110
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
2111
2111
|
|
|
2112
2112
|
import { cn } from '@/lib/utils';
|
|
@@ -2146,7 +2146,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|
|
2146
2146
|
Button.displayName = 'Button';
|
|
2147
2147
|
|
|
2148
2148
|
export { Button, buttonVariants };
|
|
2149
|
-
`,
|
|
2149
|
+
`,i_=`import * as React from 'react';
|
|
2150
2150
|
|
|
2151
2151
|
import { cn } from '@/lib/utils';
|
|
2152
2152
|
|
|
@@ -2184,7 +2184,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
|
|
|
2184
2184
|
CardContent.displayName = 'CardContent';
|
|
2185
2185
|
|
|
2186
2186
|
export { Card, CardHeader, CardTitle, CardDescription, CardContent };
|
|
2187
|
-
`,
|
|
2187
|
+
`,a_=`import * as React from 'react';
|
|
2188
2188
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
2189
2189
|
|
|
2190
2190
|
import { cn } from '@/lib/utils';
|
|
@@ -2219,7 +2219,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
|
|
|
2219
2219
|
}
|
|
2220
2220
|
|
|
2221
2221
|
export { Badge, badgeVariants };
|
|
2222
|
-
`,
|
|
2222
|
+
`,c_=`import * as React from 'react';
|
|
2223
2223
|
|
|
2224
2224
|
import { cn } from '@/lib/utils';
|
|
2225
2225
|
|
|
@@ -2278,7 +2278,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
|
|
|
2278
2278
|
TableCell.displayName = 'TableCell';
|
|
2279
2279
|
|
|
2280
2280
|
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
|
|
2281
|
-
`,
|
|
2281
|
+
`,l_=`import * as React from 'react';
|
|
2282
2282
|
|
|
2283
2283
|
import { cn } from '@/lib/utils';
|
|
2284
2284
|
|
|
@@ -2298,7 +2298,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
|
|
|
2298
2298
|
Input.displayName = 'Input';
|
|
2299
2299
|
|
|
2300
2300
|
export { Input };
|
|
2301
|
-
`,
|
|
2301
|
+
`,u_=`import * as React from 'react';
|
|
2302
2302
|
|
|
2303
2303
|
import { cn } from '@/lib/utils';
|
|
2304
2304
|
|
|
@@ -2315,9 +2315,9 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
|
|
|
2315
2315
|
Label.displayName = 'Label';
|
|
2316
2316
|
|
|
2317
2317
|
export { Label };
|
|
2318
|
-
`});var Ss=O(()=>{Fi()});function I(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Nt(t){return t&&Object.assign($a,t),$a}var GC,Lr,$a,xo=O(()=>{GC=Object.freeze({status:"aborted"});Lr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$a={}});var ve={};es(ve,{BIGINT_FORMAT_RANGES:()=>u_,Class:()=>Yu,NUMBER_FORMAT_RANGES:()=>od,aborted:()=>Dn,allowsEval:()=>td,assert:()=>eI,assertEqual:()=>JC,assertIs:()=>XC,assertNever:()=>QC,assertNotEqual:()=>YC,assignProp:()=>ed,cached:()=>Rs,captureStackTrace:()=>Ra,cleanEnum:()=>hI,cleanRegex:()=>Ps,clone:()=>Lt,createTransparentProxy:()=>iI,defineLazy:()=>ze,esc:()=>jn,escapeRegex:()=>Yr,extend:()=>lI,finalizeIssue:()=>nr,floatSafeRemainder:()=>Qu,getElementAtPath:()=>tI,getEnumValues:()=>Ts,getLengthableOrigin:()=>As,getParsedType:()=>sI,getSizableOrigin:()=>d_,isObject:()=>So,isPlainObject:()=>$o,issue:()=>sd,joinValues:()=>Ta,jsonStringifyReplacer:()=>Xu,merge:()=>uI,normalizeParams:()=>ie,nullish:()=>Es,numKeys:()=>oI,omit:()=>cI,optionalKeys:()=>nd,partial:()=>dI,pick:()=>aI,prefixIssues:()=>br,primitiveTypes:()=>l_,promiseAllObject:()=>rI,propertyKeyTypes:()=>rd,randomString:()=>nI,required:()=>pI,stringifyPrimitive:()=>Ea,unwrapMessage:()=>$s});function JC(t){return t}function YC(t){return t}function XC(t){}function QC(t){throw new Error}function eI(t){}function Ts(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ta(t,e="|"){return t.map(r=>Ea(r)).join(e)}function Xu(t,e){return typeof e=="bigint"?e.toString():e}function Rs(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Es(t){return t==null}function Ps(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Qu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function ze(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function ed(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function tI(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function rI(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function nI(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function jn(t){return JSON.stringify(t)}function So(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $o(t){if(So(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(So(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function oI(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Yr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Lt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ie(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function iI(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ea(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function nd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function aI(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Lt(t,{...t._zod.def,shape:r,checks:[]})}function cI(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Lt(t,{...t._zod.def,shape:r,checks:[]})}function lI(t,e){if(!$o(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return ed(this,"shape",n),n},checks:[]};return Lt(t,r)}function uI(t,e){return Lt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return ed(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function dI(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Lt(e,{...e._zod.def,shape:o,checks:[]})}function pI(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Lt(e,{...e._zod.def,shape:o,checks:[]})}function Dn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function br(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function $s(t){return typeof t=="string"?t:t?.message}function nr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=$s(t.inst?._zod.def?.error?.(t))??$s(e?.error?.(t))??$s(r.customError?.(t))??$s(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function d_(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function As(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function sd(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function hI(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ra,td,sI,rd,l_,od,u_,Yu,wr=O(()=>{Ra=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};td=Rs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});sI=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},rd=new Set(["string","number","symbol"]),l_=new Set(["string","number","bigint","boolean","symbol","undefined"]);od={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},u_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Yu=class{constructor(...e){}}});function id(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function ad(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(t),n}var p_,Pa,Cs,cd=O(()=>{xo();wr();p_=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Xu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Pa=I("$ZodError",p_),Cs=I("$ZodError",p_,{Parent:Error})});var ld,ud,dd,pd,hd,Mn,md,Un,fd=O(()=>{xo();cd();wr();ld=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Lr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>nr(c,s,Nt())));throw Ra(a,o?.callee),a}return i.value},ud=ld(Cs),dd=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>nr(c,s,Nt())));throw Ra(a,o?.callee),a}return i.value},pd=dd(Cs),hd=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Lr;return s.issues.length?{success:!1,error:new(t??Pa)(s.issues.map(i=>nr(i,o,Nt())))}:{success:!0,data:s.value}},Mn=hd(Cs),md=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>nr(i,o,Nt())))}:{success:!0,data:s.value}},Un=md(Cs)});function k_(){return new RegExp(fI,"u")}function I_(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function O_(t){return new RegExp(`^${I_(t)}$`)}function N_(t){let e=I_({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${A_}T(?:${n})$`)}var h_,m_,f_,g_,y_,b_,w_,__,gd,v_,fI,x_,S_,$_,T_,R_,yd,E_,P_,A_,C_,L_,z_,j_,D_,M_,U_,q_,Ca=O(()=>{h_=/^[cC][^\s-]{8,}$/,m_=/^[0-9a-z]+$/,f_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,g_=/^[0-9a-vA-V]{20}$/,y_=/^[A-Za-z0-9]{27}$/,b_=/^[a-zA-Z0-9_-]{21}$/,w_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,__=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,gd=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,v_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,fI="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";x_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,S_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,$_=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,T_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,R_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yd=/^[A-Za-z0-9_-]*$/,E_=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,P_=/^\+(?:[0-9]){6,14}[0-9]$/,A_="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",C_=new RegExp(`^${A_}$`);L_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},z_=/^\d+$/,j_=/^-?\d+(?:\.\d+)?/i,D_=/true|false/i,M_=/null/i,U_=/^[^A-Z]*$/,q_=/^[^a-z]*$/});var ct,F_,bd,wd,B_,Z_,V_,H_,K_,Is,W_,G_,J_,Y_,X_,Q_,ev,Ia=O(()=>{xo();Ca();wr();ct=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),F_={number:"number",bigint:"bigint",object:"date"},bd=I("$ZodCheckLessThan",(t,e)=>{ct.init(t,e);let r=F_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),wd=I("$ZodCheckGreaterThan",(t,e)=>{ct.init(t,e);let r=F_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),B_=I("$ZodCheckMultipleOf",(t,e)=>{ct.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Qu(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Z_=I("$ZodCheckNumberFormat",(t,e)=>{ct.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=od[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=z_)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),V_=I("$ZodCheckMaxLength",(t,e)=>{var r;ct.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Es(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=As(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),H_=I("$ZodCheckMinLength",(t,e)=>{var r;ct.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Es(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=As(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),K_=I("$ZodCheckLengthEquals",(t,e)=>{var r;ct.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Es(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=As(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Is=I("$ZodCheckStringFormat",(t,e)=>{var r,n;ct.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),W_=I("$ZodCheckRegex",(t,e)=>{Is.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),G_=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=U_),Is.init(t,e)}),J_=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=q_),Is.init(t,e)}),Y_=I("$ZodCheckIncludes",(t,e)=>{ct.init(t,e);let r=Yr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),X_=I("$ZodCheckStartsWith",(t,e)=>{ct.init(t,e);let r=new RegExp(`^${Yr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Q_=I("$ZodCheckEndsWith",(t,e)=>{ct.init(t,e);let r=new RegExp(`.*${Yr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),ev=I("$ZodCheckOverwrite",(t,e)=>{ct.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Oa,_d=O(()=>{Oa=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
2318
|
+
`});var Ts=N(()=>{Bi()});function I(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Nt(t){return t&&Object.assign(Ta,t),Ta}var rI,Lr,Ta,$o=N(()=>{rI=Object.freeze({status:"aborted"});Lr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ta={}});var ve={};rs(ve,{BIGINT_FORMAT_RANGES:()=>m_,Class:()=>Xu,NUMBER_FORMAT_RANGES:()=>sd,aborted:()=>Dn,allowsEval:()=>rd,assert:()=>aI,assertEqual:()=>nI,assertIs:()=>sI,assertNever:()=>iI,assertNotEqual:()=>oI,assignProp:()=>td,cached:()=>Ps,captureStackTrace:()=>Ea,cleanEnum:()=>_I,cleanRegex:()=>Cs,clone:()=>Lt,createTransparentProxy:()=>hI,defineLazy:()=>je,esc:()=>zn,escapeRegex:()=>Yr,extend:()=>gI,finalizeIssue:()=>nr,floatSafeRemainder:()=>ed,getElementAtPath:()=>cI,getEnumValues:()=>Es,getLengthableOrigin:()=>Is,getParsedType:()=>pI,getSizableOrigin:()=>f_,isObject:()=>To,isPlainObject:()=>Ro,issue:()=>id,joinValues:()=>Ra,jsonStringifyReplacer:()=>Qu,merge:()=>yI,normalizeParams:()=>ae,nullish:()=>As,numKeys:()=>dI,omit:()=>fI,optionalKeys:()=>od,partial:()=>bI,pick:()=>mI,prefixIssues:()=>br,primitiveTypes:()=>h_,promiseAllObject:()=>lI,propertyKeyTypes:()=>nd,randomString:()=>uI,required:()=>wI,stringifyPrimitive:()=>Pa,unwrapMessage:()=>Rs});function nI(t){return t}function oI(t){return t}function sI(t){}function iI(t){throw new Error}function aI(t){}function Es(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ra(t,e="|"){return t.map(r=>Pa(r)).join(e)}function Qu(t,e){return typeof e=="bigint"?e.toString():e}function Ps(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function As(t){return t==null}function Cs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ed(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function je(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function td(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function cI(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function lI(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function uI(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function zn(t){return JSON.stringify(t)}function To(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ro(t){if(To(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(To(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function dI(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Yr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Lt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ae(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function hI(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Pa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function od(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function mI(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Lt(t,{...t._zod.def,shape:r,checks:[]})}function fI(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Lt(t,{...t._zod.def,shape:r,checks:[]})}function gI(t,e){if(!Ro(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return td(this,"shape",n),n},checks:[]};return Lt(t,r)}function yI(t,e){return Lt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return td(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function bI(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Lt(e,{...e._zod.def,shape:o,checks:[]})}function wI(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Lt(e,{...e._zod.def,shape:o,checks:[]})}function Dn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function br(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Rs(t){return typeof t=="string"?t:t?.message}function nr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Rs(t.inst?._zod.def?.error?.(t))??Rs(e?.error?.(t))??Rs(r.customError?.(t))??Rs(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function f_(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Is(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function id(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function _I(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ea,rd,pI,nd,h_,sd,m_,Xu,wr=N(()=>{Ea=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};rd=Ps(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});pI=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},nd=new Set(["string","number","symbol"]),h_=new Set(["string","number","bigint","boolean","symbol","undefined"]);sd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},m_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Xu=class{constructor(...e){}}});function ad(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function cd(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(t),n}var g_,Aa,Os,ld=N(()=>{$o();wr();g_=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Qu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Aa=I("$ZodError",g_),Os=I("$ZodError",g_,{Parent:Error})});var ud,dd,pd,hd,md,Mn,fd,Un,gd=N(()=>{$o();ld();wr();ud=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Lr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>nr(c,s,Nt())));throw Ea(a,o?.callee),a}return i.value},dd=ud(Os),pd=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>nr(c,s,Nt())));throw Ea(a,o?.callee),a}return i.value},hd=pd(Os),md=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Lr;return s.issues.length?{success:!1,error:new(t??Aa)(s.issues.map(i=>nr(i,o,Nt())))}:{success:!0,data:s.value}},Mn=md(Os),fd=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>nr(i,o,Nt())))}:{success:!0,data:s.value}},Un=fd(Os)});function T_(){return new RegExp(kI,"u")}function j_(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function z_(t){return new RegExp(`^${j_(t)}$`)}function D_(t){let e=j_({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${N_}T(?:${n})$`)}var y_,b_,w_,__,v_,k_,x_,S_,yd,$_,kI,R_,E_,P_,A_,C_,bd,I_,O_,N_,L_,M_,U_,q_,F_,B_,Z_,V_,Ia=N(()=>{y_=/^[cC][^\s-]{8,}$/,b_=/^[0-9a-z]+$/,w_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,__=/^[0-9a-vA-V]{20}$/,v_=/^[A-Za-z0-9]{27}$/,k_=/^[a-zA-Z0-9_-]{21}$/,x_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,S_=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,yd=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,$_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,kI="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";R_=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,E_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,P_=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,A_=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,C_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,bd=/^[A-Za-z0-9_-]*$/,I_=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,O_=/^\+(?:[0-9]){6,14}[0-9]$/,N_="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",L_=new RegExp(`^${N_}$`);M_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},U_=/^\d+$/,q_=/^-?\d+(?:\.\d+)?/i,F_=/true|false/i,B_=/null/i,Z_=/^[^A-Z]*$/,V_=/^[^a-z]*$/});var ct,H_,wd,_d,K_,W_,G_,J_,Y_,Ns,X_,Q_,ev,tv,rv,nv,ov,Oa=N(()=>{$o();Ia();wr();ct=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),H_={number:"number",bigint:"bigint",object:"date"},wd=I("$ZodCheckLessThan",(t,e)=>{ct.init(t,e);let r=H_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),_d=I("$ZodCheckGreaterThan",(t,e)=>{ct.init(t,e);let r=H_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),K_=I("$ZodCheckMultipleOf",(t,e)=>{ct.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):ed(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),W_=I("$ZodCheckNumberFormat",(t,e)=>{ct.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=sd[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=U_)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),G_=I("$ZodCheckMaxLength",(t,e)=>{var r;ct.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!As(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Is(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),J_=I("$ZodCheckMinLength",(t,e)=>{var r;ct.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!As(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Is(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Y_=I("$ZodCheckLengthEquals",(t,e)=>{var r;ct.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!As(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Is(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Ns=I("$ZodCheckStringFormat",(t,e)=>{var r,n;ct.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),X_=I("$ZodCheckRegex",(t,e)=>{Ns.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Q_=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Z_),Ns.init(t,e)}),ev=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=V_),Ns.init(t,e)}),tv=I("$ZodCheckIncludes",(t,e)=>{ct.init(t,e);let r=Yr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),rv=I("$ZodCheckStartsWith",(t,e)=>{ct.init(t,e);let r=new RegExp(`^${Yr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),nv=I("$ZodCheckEndsWith",(t,e)=>{ct.init(t,e);let r=new RegExp(`.*${Yr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),ov=I("$ZodCheckOverwrite",(t,e)=>{ct.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Na,vd=N(()=>{Na=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
2319
2319
|
`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
|
|
2320
|
-
`))}}});var
|
|
2320
|
+
`))}}});var iv,kd=N(()=>{iv={major:4,minor:0,patch:0}});function _v(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function xI(t){if(!bd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return _v(r)}function SI(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function av(t,e,r){t.issues.length&&e.issues.push(...br(r,t.issues)),e.value[r]=t.value}function La(t,e,r){t.issues.length&&e.issues.push(...br(r,t.issues)),e.value[r]=t.value}function cv(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...br(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function lv(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>nr(s,n,Nt())))}),e}function xd(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Ro(t)&&Ro(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=xd(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=xd(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function uv(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Dn(t))return t;let n=xd(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function dv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function pv(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function hv(t,e,r){return Dn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function mv(t){return t.value=Object.freeze(t.value),t}function fv(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(id(o))}}var Ie,Ls,ze,Sd,$d,Td,Rd,Ed,Pd,Ad,Cd,Id,Od,Nd,gv,yv,bv,wv,Ld,jd,zd,Dd,Md,Ud,qd,Fd,ja,Bd,Zd,Vd,Hd,Kd,Wd,za,Da,Gd,Jd,Yd,Xd,Qd,ep,tp,rp,np,op,sp,ip,ap,cp,lp,vv=N(()=>{Oa();$o();vd();gd();Ia();wr();kd();wr();Ie=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=iv;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Dn(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,b=u._zod.check(s);if(b instanceof Promise&&a?.async===!1)throw new Lr;if(l||b instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await b,s.issues.length!==p&&(c||(c=Dn(s,p)))});else{if(s.issues.length===p)continue;c||(c=Dn(s,p))}}return l?l.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Lr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Mn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Un(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Ls=I("$ZodString",(t,e)=>{Ie.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??M_(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ze=I("$ZodStringFormat",(t,e)=>{Ns.init(t,e),Ls.init(t,e)}),Sd=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=S_),ze.init(t,e)}),$d=I("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=yd(n))}else e.pattern??(e.pattern=yd());ze.init(t,e)}),Td=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=$_),ze.init(t,e)}),Rd=I("$ZodURL",(t,e)=>{ze.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:I_.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Ed=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=T_()),ze.init(t,e)}),Pd=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=k_),ze.init(t,e)}),Ad=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=y_),ze.init(t,e)}),Cd=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=b_),ze.init(t,e)}),Id=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=w_),ze.init(t,e)}),Od=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=__),ze.init(t,e)}),Nd=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=v_),ze.init(t,e)}),gv=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=D_(e)),ze.init(t,e)}),yv=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=L_),ze.init(t,e)}),bv=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=z_(e)),ze.init(t,e)}),wv=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=x_),ze.init(t,e)}),Ld=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=R_),ze.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),jd=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=E_),ze.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),zd=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=P_),ze.init(t,e)}),Dd=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=A_),ze.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Md=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=C_),ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{_v(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Ud=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=bd),ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{xI(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),qd=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=O_),ze.init(t,e)});Fd=I("$ZodJWT",(t,e)=>{ze.init(t,e),t._zod.check=r=>{SI(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),ja=I("$ZodNumber",(t,e)=>{Ie.init(t,e),t._zod.pattern=t._zod.bag.pattern??q_,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Bd=I("$ZodNumber",(t,e)=>{W_.init(t,e),ja.init(t,e)}),Zd=I("$ZodBoolean",(t,e)=>{Ie.init(t,e),t._zod.pattern=F_,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Vd=I("$ZodNull",(t,e)=>{Ie.init(t,e),t._zod.pattern=B_,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Hd=I("$ZodUnknown",(t,e)=>{Ie.init(t,e),t._zod.parse=r=>r}),Kd=I("$ZodNever",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Wd=I("$ZodArray",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>av(l,r,i))):av(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});za=I("$ZodObject",(t,e)=>{Ie.init(t,e);let r=Ps(()=>{let p=Object.keys(e.shape);for(let f of p)if(!(e.shape[f]instanceof Ie))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let b=od(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(b)}});je(t._zod,"propValues",()=>{let p=e.shape,b={};for(let f in p){let m=p[f]._zod;if(m.values){b[f]??(b[f]=new Set);for(let w of m.values)b[f].add(w)}}return b});let n=p=>{let b=new Na(["shape","payload","ctx"]),f=r.value,m=A=>{let L=zn(A);return`shape[${L}]._zod.run({ value: input[${L}], issues: [] }, ctx)`};b.write("const input = payload.value;");let w=Object.create(null),$=0;for(let A of f.keys)w[A]=`key_${$++}`;b.write("const newResult = {}");for(let A of f.keys)if(f.optionalKeys.has(A)){let L=w[A];b.write(`const ${L} = ${m(A)};`);let F=zn(A);b.write(`
|
|
2321
2321
|
if (${L}.issues.length) {
|
|
2322
2322
|
if (input[${F}] === undefined) {
|
|
2323
2323
|
if (${F} in input) {
|
|
@@ -2336,60 +2336,61 @@ export { Label };
|
|
|
2336
2336
|
} else {
|
|
2337
2337
|
newResult[${F}] = ${L}.value;
|
|
2338
2338
|
}
|
|
2339
|
-
`)}else{let L=w[A];b.write(`const ${L} = ${
|
|
2339
|
+
`)}else{let L=w[A];b.write(`const ${L} = ${m(A)};`),b.write(`
|
|
2340
2340
|
if (${L}.issues.length) payload.issues = payload.issues.concat(${L}.issues.map(iss => ({
|
|
2341
2341
|
...iss,
|
|
2342
|
-
path: iss.path ? [${
|
|
2343
|
-
})));`),b.write(`newResult[${jn(A)}] = ${L}.value`)}b.write("payload.value = newResult;"),b.write("return payload;");let R=b.compile();return(A,L)=>R(p,A,L)},o,s=So,i=!$a.jitless,c=i&&td.value,l=e.catchall,u;t._zod.parse=(p,b)=>{u??(u=r.value);let f=p.value;if(!s(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let h=[];if(i&&c&&b?.async===!1&&b.jitless!==!0)o||(o=n(e.shape)),p=o(p,b);else{p.value={};let L=u.shape;for(let F of u.keys){let W=L[F],Ke=W._zod.run({value:f[F],issues:[]},b),Je=W._zod.optin==="optional"&&W._zod.optout==="optional";Ke instanceof Promise?h.push(Ke.then(jt=>Je?ov(jt,p,F,f):Na(jt,p,F))):Je?ov(Ke,p,F,f):Na(Ke,p,F)}}if(!l)return h.length?Promise.all(h).then(()=>p):p;let w=[],S=u.keySet,R=l._zod,A=R.def.type;for(let L of Object.keys(f)){if(S.has(L))continue;if(A==="never"){w.push(L);continue}let F=R.run({value:f[L],issues:[]},b);F instanceof Promise?h.push(F.then(W=>Na(W,p,L))):Na(F,p,L)}return w.length&&p.issues.push({code:"unrecognized_keys",keys:w,input:f,inst:t}),h.length?Promise.all(h).then(()=>p):p}});ja=I("$ZodUnion",(t,e)=>{Ie.init(t,e),ze(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ze(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ze(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ze(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Ps(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>sv(i,r,t,n)):sv(s,r,t,n)}}),Wd=I("$ZodDiscriminatedUnion",(t,e)=>{ja.init(t,e);let r=t._zod.parse;ze(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=Rs(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!So(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Gd=I("$ZodIntersection",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>iv(r,c,l)):iv(r,s,i)}});Jd=I("$ZodRecord",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!$o(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...br(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...br(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>nr(l,n,Nt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...br(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...br(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Yd=I("$ZodEnum",(t,e)=>{Ie.init(t,e);let r=Ts(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>rd.has(typeof n)).map(n=>typeof n=="string"?Yr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Xd=I("$ZodLiteral",(t,e)=>{Ie.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Yr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),Qd=I("$ZodTransform",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Lr;return r.value=o,r}}),ep=I("$ZodOptional",(t,e)=>{Ie.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ze(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ze(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ps(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),tp=I("$ZodNullable",(t,e)=>{Ie.init(t,e),ze(t._zod,"optin",()=>e.innerType._zod.optin),ze(t._zod,"optout",()=>e.innerType._zod.optout),ze(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ps(r.source)}|null)$`):void 0}),ze(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),rp=I("$ZodDefault",(t,e)=>{Ie.init(t,e),t._zod.optin="optional",ze(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>av(s,e)):av(o,e)}});np=I("$ZodPrefault",(t,e)=>{Ie.init(t,e),t._zod.optin="optional",ze(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),op=I("$ZodNonOptional",(t,e)=>{Ie.init(t,e),ze(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>cv(s,t)):cv(o,t)}});sp=I("$ZodCatch",(t,e)=>{Ie.init(t,e),t._zod.optin="optional",ze(t._zod,"optout",()=>e.innerType._zod.optout),ze(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>nr(i,n,Nt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>nr(s,n,Nt()))},input:r.value}),r.issues=[]),r)}}),ip=I("$ZodPipe",(t,e)=>{Ie.init(t,e),ze(t._zod,"values",()=>e.in._zod.values),ze(t._zod,"optin",()=>e.in._zod.optin),ze(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>lv(s,e,n)):lv(o,e,n)}});ap=I("$ZodReadonly",(t,e)=>{Ie.init(t,e),ze(t._zod,"propValues",()=>e.innerType._zod.propValues),ze(t._zod,"values",()=>e.innerType._zod.values),ze(t._zod,"optin",()=>e.innerType._zod.optin),ze(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(uv):uv(o)}});cp=I("$ZodCustom",(t,e)=>{ct.init(t,e),Ie.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>dv(s,r,n,t));dv(o,r,n,t)}})});function bv(){return{localeError:wI()}}var bI,wI,wv=O(()=>{wr();bI=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},wI=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={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"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${bI(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ea(n.values[0])}`:`Invalid option: expected one of ${Ta(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ta(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Da=O(()=>{});function _v(){return new Ns}var Ns,Xr,up=O(()=>{Ns=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Xr=_v()});function dp(t,e){return new t({type:"string",...ie(e)})}function pp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ie(e)})}function Ma(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ie(e)})}function hp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ie(e)})}function mp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ie(e)})}function fp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ie(e)})}function gp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ie(e)})}function yp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ie(e)})}function bp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ie(e)})}function wp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ie(e)})}function _p(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ie(e)})}function vp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ie(e)})}function kp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ie(e)})}function xp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ie(e)})}function Sp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ie(e)})}function $p(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ie(e)})}function Tp(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ie(e)})}function Rp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ie(e)})}function Ep(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ie(e)})}function Pp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ie(e)})}function Ap(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ie(e)})}function Cp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ie(e)})}function Ip(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ie(e)})}function vv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ie(e)})}function kv(t,e){return new t({type:"string",format:"date",check:"string_format",...ie(e)})}function xv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ie(e)})}function Sv(t,e){return new t({type:"string",format:"duration",check:"string_format",...ie(e)})}function Op(t,e){return new t({type:"number",checks:[],...ie(e)})}function Np(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ie(e)})}function Lp(t,e){return new t({type:"boolean",...ie(e)})}function zp(t,e){return new t({type:"null",...ie(e)})}function jp(t){return new t({type:"unknown"})}function Dp(t,e){return new t({type:"never",...ie(e)})}function Ua(t,e){return new bd({check:"less_than",...ie(e),value:t,inclusive:!1})}function Ls(t,e){return new bd({check:"less_than",...ie(e),value:t,inclusive:!0})}function qa(t,e){return new wd({check:"greater_than",...ie(e),value:t,inclusive:!1})}function zs(t,e){return new wd({check:"greater_than",...ie(e),value:t,inclusive:!0})}function Fa(t,e){return new B_({check:"multiple_of",...ie(e),value:t})}function Ba(t,e){return new V_({check:"max_length",...ie(e),maximum:t})}function To(t,e){return new H_({check:"min_length",...ie(e),minimum:t})}function Za(t,e){return new K_({check:"length_equals",...ie(e),length:t})}function Mp(t,e){return new W_({check:"string_format",format:"regex",...ie(e),pattern:t})}function Up(t){return new G_({check:"string_format",format:"lowercase",...ie(t)})}function qp(t){return new J_({check:"string_format",format:"uppercase",...ie(t)})}function Fp(t,e){return new Y_({check:"string_format",format:"includes",...ie(e),includes:t})}function Bp(t,e){return new X_({check:"string_format",format:"starts_with",...ie(e),prefix:t})}function Zp(t,e){return new Q_({check:"string_format",format:"ends_with",...ie(e),suffix:t})}function qn(t){return new ev({check:"overwrite",tx:t})}function Vp(t){return qn(e=>e.normalize(t))}function Hp(){return qn(t=>t.trim())}function Kp(){return qn(t=>t.toLowerCase())}function Wp(){return qn(t=>t.toUpperCase())}function $v(t,e,r){return new t({type:"array",element:e,...ie(r)})}function Gp(t,e,r){let n=ie(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Jp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ie(r)})}var Tv=O(()=>{Ia();wr()});var Rv=O(()=>{});function Yp(t,e){if(t instanceof Ns){let n=new Va(e),o={};for(let a of t._idmap.entries()){let[c,l]=a;n.process(l)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,l]=a;s[c]=n.emit(l,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Va(e);return r.process(t),r.emit(t,e)}function tt(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return tt(o.element,r);case"object":{for(let s in o.shape)if(tt(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(tt(s,r))return!0;return!1}case"intersection":return tt(o.left,r)||tt(o.right,r);case"tuple":{for(let s of o.items)if(tt(s,r))return!0;return!!(o.rest&&tt(o.rest,r))}case"record":return tt(o.keyType,r)||tt(o.valueType,r);case"map":return tt(o.keyType,r)||tt(o.valueType,r);case"set":return tt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return tt(o.innerType,r);case"lazy":return tt(o.getter(),r);case"default":return tt(o.innerType,r);case"prefault":return tt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return tt(o.in,r)||tt(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Va,Ev=O(()=>{up();wr();Va=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Xr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let p={...r,schemaPath:[...r.schemaPath,e],path:r.path},b=e._zod.parent;if(b)a.ref=b,this.process(b,p),this.seen.get(b).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let h=f;h.type="string";let{minimum:w,maximum:S,format:R,patterns:A,contentEncoding:L}=e._zod.bag;if(typeof w=="number"&&(h.minLength=w),typeof S=="number"&&(h.maxLength=S),R&&(h.format=s[R]??R,h.format===""&&delete h.format),L&&(h.contentEncoding=L),A&&A.size>0){let F=[...A];F.length===1?h.pattern=F[0].source:F.length>1&&(a.schema.allOf=[...F.map(W=>({...this.target==="draft-7"?{type:"string"}:{},pattern:W.source}))])}break}case"number":{let h=f,{minimum:w,maximum:S,format:R,multipleOf:A,exclusiveMaximum:L,exclusiveMinimum:F}=e._zod.bag;typeof R=="string"&&R.includes("int")?h.type="integer":h.type="number",typeof F=="number"&&(h.exclusiveMinimum=F),typeof w=="number"&&(h.minimum=w,typeof F=="number"&&(F>=w?delete h.minimum:delete h.exclusiveMinimum)),typeof L=="number"&&(h.exclusiveMaximum=L),typeof S=="number"&&(h.maximum=S,typeof L=="number"&&(L<=S?delete h.maximum:delete h.exclusiveMaximum)),typeof A=="number"&&(h.multipleOf=A);break}case"boolean":{let h=f;h.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let h=f,{minimum:w,maximum:S}=e._zod.bag;typeof w=="number"&&(h.minItems=w),typeof S=="number"&&(h.maxItems=S),h.type="array",h.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let h=f;h.type="object",h.properties={};let w=o.shape;for(let A in w)h.properties[A]=this.process(w[A],{...p,path:[...p.path,"properties",A]});let S=new Set(Object.keys(w)),R=new Set([...S].filter(A=>{let L=o.shape[A]._zod;return this.io==="input"?L.optin===void 0:L.optout===void 0}));R.size>0&&(h.required=Array.from(R)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{let h=f;h.anyOf=o.options.map((w,S)=>this.process(w,{...p,path:[...p.path,"anyOf",S]}));break}case"intersection":{let h=f,w=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),S=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),R=L=>"allOf"in L&&Object.keys(L).length===1,A=[...R(w)?w.allOf:[w],...R(S)?S.allOf:[S]];h.allOf=A;break}case"tuple":{let h=f;h.type="array";let w=o.items.map((A,L)=>this.process(A,{...p,path:[...p.path,"prefixItems",L]}));if(this.target==="draft-2020-12"?h.prefixItems=w:h.items=w,o.rest){let A=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?h.items=A:h.additionalItems=A}o.rest&&(h.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:S,maximum:R}=e._zod.bag;typeof S=="number"&&(h.minItems=S),typeof R=="number"&&(h.maxItems=R);break}case"record":{let h=f;h.type="object",h.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),h.additionalProperties=this.process(o.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let h=f,w=Ts(o.entries);w.every(S=>typeof S=="number")&&(h.type="number"),w.every(S=>typeof S=="string")&&(h.type="string"),h.enum=w;break}case"literal":{let h=f,w=[];for(let S of o.values)if(S===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof S=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(S))}else w.push(S);if(w.length!==0)if(w.length===1){let S=w[0];h.type=S===null?"null":typeof S,h.const=S}else w.every(S=>typeof S=="number")&&(h.type="number"),w.every(S=>typeof S=="string")&&(h.type="string"),w.every(S=>typeof S=="boolean")&&(h.type="string"),w.every(S=>S===null)&&(h.type="null"),h.enum=w;break}case"file":{let h=f,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:S,maximum:R,mime:A}=e._zod.bag;S!==void 0&&(w.minLength=S),R!==void 0&&(w.maxLength=R),A?A.length===1?(w.contentMediaType=A[0],Object.assign(h,w)):h.anyOf=A.map(L=>({...w,contentMediaType:L})):Object.assign(h,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let h=this.process(o.innerType,p);f.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let h=f;h.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let h=f,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=w.source;break}case"pipe":{let h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,p),a.ref=h;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let h=e._zod.innerType;this.process(h,p),a.ref=h;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&tt(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=u=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let w=n.external.registry.get(u[0])?.id,S=n.external.uri??(A=>A);if(w)return{ref:S(w)};let R=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=R,{defId:R,ref:`${S("__shared")}#/${p}/${R}`}}if(u[1]===o)return{ref:"#"};let f=`#/${p}/`,h=u[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:f+h}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:b,defId:f}=s(u);p.def={...p.schema},f&&(p.defId=f);let h=p.schema;for(let w in h)delete h[w];h.$ref=b};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
|
|
2342
|
+
path: iss.path ? [${zn(A)}, ...iss.path] : [${zn(A)}]
|
|
2343
|
+
})));`),b.write(`newResult[${zn(A)}] = ${L}.value`)}b.write("payload.value = newResult;"),b.write("return payload;");let R=b.compile();return(A,L)=>R(p,A,L)},o,s=To,i=!Ta.jitless,c=i&&rd.value,l=e.catchall,u;t._zod.parse=(p,b)=>{u??(u=r.value);let f=p.value;if(!s(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let m=[];if(i&&c&&b?.async===!1&&b.jitless!==!0)o||(o=n(e.shape)),p=o(p,b);else{p.value={};let L=u.shape;for(let F of u.keys){let W=L[F],Ke=W._zod.run({value:f[F],issues:[]},b),Je=W._zod.optin==="optional"&&W._zod.optout==="optional";Ke instanceof Promise?m.push(Ke.then(zt=>Je?cv(zt,p,F,f):La(zt,p,F))):Je?cv(Ke,p,F,f):La(Ke,p,F)}}if(!l)return m.length?Promise.all(m).then(()=>p):p;let w=[],$=u.keySet,R=l._zod,A=R.def.type;for(let L of Object.keys(f)){if($.has(L))continue;if(A==="never"){w.push(L);continue}let F=R.run({value:f[L],issues:[]},b);F instanceof Promise?m.push(F.then(W=>La(W,p,L))):La(F,p,L)}return w.length&&p.issues.push({code:"unrecognized_keys",keys:w,input:f,inst:t}),m.length?Promise.all(m).then(()=>p):p}});Da=I("$ZodUnion",(t,e)=>{Ie.init(t,e),je(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),je(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),je(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),je(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Cs(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>lv(i,r,t,n)):lv(s,r,t,n)}}),Gd=I("$ZodDiscriminatedUnion",(t,e)=>{Da.init(t,e);let r=t._zod.parse;je(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=Ps(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!To(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Jd=I("$ZodIntersection",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>uv(r,c,l)):uv(r,s,i)}});Yd=I("$ZodRecord",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Ro(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...br(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...br(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>nr(l,n,Nt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...br(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...br(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Xd=I("$ZodEnum",(t,e)=>{Ie.init(t,e);let r=Es(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>nd.has(typeof n)).map(n=>typeof n=="string"?Yr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Qd=I("$ZodLiteral",(t,e)=>{Ie.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Yr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),ep=I("$ZodTransform",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Lr;return r.value=o,r}}),tp=I("$ZodOptional",(t,e)=>{Ie.init(t,e),t._zod.optin="optional",t._zod.optout="optional",je(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),je(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Cs(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),rp=I("$ZodNullable",(t,e)=>{Ie.init(t,e),je(t._zod,"optin",()=>e.innerType._zod.optin),je(t._zod,"optout",()=>e.innerType._zod.optout),je(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Cs(r.source)}|null)$`):void 0}),je(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),np=I("$ZodDefault",(t,e)=>{Ie.init(t,e),t._zod.optin="optional",je(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>dv(s,e)):dv(o,e)}});op=I("$ZodPrefault",(t,e)=>{Ie.init(t,e),t._zod.optin="optional",je(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),sp=I("$ZodNonOptional",(t,e)=>{Ie.init(t,e),je(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>pv(s,t)):pv(o,t)}});ip=I("$ZodCatch",(t,e)=>{Ie.init(t,e),t._zod.optin="optional",je(t._zod,"optout",()=>e.innerType._zod.optout),je(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>nr(i,n,Nt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>nr(s,n,Nt()))},input:r.value}),r.issues=[]),r)}}),ap=I("$ZodPipe",(t,e)=>{Ie.init(t,e),je(t._zod,"values",()=>e.in._zod.values),je(t._zod,"optin",()=>e.in._zod.optin),je(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>hv(s,e,n)):hv(o,e,n)}});cp=I("$ZodReadonly",(t,e)=>{Ie.init(t,e),je(t._zod,"propValues",()=>e.innerType._zod.propValues),je(t._zod,"values",()=>e.innerType._zod.values),je(t._zod,"optin",()=>e.innerType._zod.optin),je(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(mv):mv(o)}});lp=I("$ZodCustom",(t,e)=>{ct.init(t,e),Ie.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>fv(s,r,n,t));fv(o,r,n,t)}})});function kv(){return{localeError:TI()}}var $I,TI,xv=N(()=>{wr();$I=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},TI=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={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"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${$I(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Pa(n.values[0])}`:`Invalid option: expected one of ${Ra(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ra(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Ma=N(()=>{});function Sv(){return new js}var js,Xr,dp=N(()=>{js=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Xr=Sv()});function pp(t,e){return new t({type:"string",...ae(e)})}function hp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ae(e)})}function Ua(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ae(e)})}function mp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ae(e)})}function fp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ae(e)})}function gp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ae(e)})}function yp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ae(e)})}function bp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ae(e)})}function wp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ae(e)})}function _p(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ae(e)})}function vp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ae(e)})}function kp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ae(e)})}function xp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ae(e)})}function Sp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ae(e)})}function $p(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ae(e)})}function Tp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ae(e)})}function Rp(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ae(e)})}function Ep(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ae(e)})}function Pp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ae(e)})}function Ap(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ae(e)})}function Cp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ae(e)})}function Ip(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ae(e)})}function Op(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ae(e)})}function $v(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ae(e)})}function Tv(t,e){return new t({type:"string",format:"date",check:"string_format",...ae(e)})}function Rv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ae(e)})}function Ev(t,e){return new t({type:"string",format:"duration",check:"string_format",...ae(e)})}function Np(t,e){return new t({type:"number",checks:[],...ae(e)})}function Lp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ae(e)})}function jp(t,e){return new t({type:"boolean",...ae(e)})}function zp(t,e){return new t({type:"null",...ae(e)})}function Dp(t){return new t({type:"unknown"})}function Mp(t,e){return new t({type:"never",...ae(e)})}function qa(t,e){return new wd({check:"less_than",...ae(e),value:t,inclusive:!1})}function zs(t,e){return new wd({check:"less_than",...ae(e),value:t,inclusive:!0})}function Fa(t,e){return new _d({check:"greater_than",...ae(e),value:t,inclusive:!1})}function Ds(t,e){return new _d({check:"greater_than",...ae(e),value:t,inclusive:!0})}function Ba(t,e){return new K_({check:"multiple_of",...ae(e),value:t})}function Za(t,e){return new G_({check:"max_length",...ae(e),maximum:t})}function Eo(t,e){return new J_({check:"min_length",...ae(e),minimum:t})}function Va(t,e){return new Y_({check:"length_equals",...ae(e),length:t})}function Up(t,e){return new X_({check:"string_format",format:"regex",...ae(e),pattern:t})}function qp(t){return new Q_({check:"string_format",format:"lowercase",...ae(t)})}function Fp(t){return new ev({check:"string_format",format:"uppercase",...ae(t)})}function Bp(t,e){return new tv({check:"string_format",format:"includes",...ae(e),includes:t})}function Zp(t,e){return new rv({check:"string_format",format:"starts_with",...ae(e),prefix:t})}function Vp(t,e){return new nv({check:"string_format",format:"ends_with",...ae(e),suffix:t})}function qn(t){return new ov({check:"overwrite",tx:t})}function Hp(t){return qn(e=>e.normalize(t))}function Kp(){return qn(t=>t.trim())}function Wp(){return qn(t=>t.toLowerCase())}function Gp(){return qn(t=>t.toUpperCase())}function Pv(t,e,r){return new t({type:"array",element:e,...ae(r)})}function Jp(t,e,r){let n=ae(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Yp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ae(r)})}var Av=N(()=>{Oa();wr()});var Cv=N(()=>{});function Xp(t,e){if(t instanceof js){let n=new Ha(e),o={};for(let a of t._idmap.entries()){let[c,l]=a;n.process(l)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,l]=a;s[c]=n.emit(l,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Ha(e);return r.process(t),r.emit(t,e)}function tt(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return tt(o.element,r);case"object":{for(let s in o.shape)if(tt(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(tt(s,r))return!0;return!1}case"intersection":return tt(o.left,r)||tt(o.right,r);case"tuple":{for(let s of o.items)if(tt(s,r))return!0;return!!(o.rest&&tt(o.rest,r))}case"record":return tt(o.keyType,r)||tt(o.valueType,r);case"map":return tt(o.keyType,r)||tt(o.valueType,r);case"set":return tt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return tt(o.innerType,r);case"lazy":return tt(o.getter(),r);case"default":return tt(o.innerType,r);case"prefault":return tt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return tt(o.in,r)||tt(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Ha,Iv=N(()=>{dp();wr();Ha=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Xr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let p={...r,schemaPath:[...r.schemaPath,e],path:r.path},b=e._zod.parent;if(b)a.ref=b,this.process(b,p),this.seen.get(b).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let m=f;m.type="string";let{minimum:w,maximum:$,format:R,patterns:A,contentEncoding:L}=e._zod.bag;if(typeof w=="number"&&(m.minLength=w),typeof $=="number"&&(m.maxLength=$),R&&(m.format=s[R]??R,m.format===""&&delete m.format),L&&(m.contentEncoding=L),A&&A.size>0){let F=[...A];F.length===1?m.pattern=F[0].source:F.length>1&&(a.schema.allOf=[...F.map(W=>({...this.target==="draft-7"?{type:"string"}:{},pattern:W.source}))])}break}case"number":{let m=f,{minimum:w,maximum:$,format:R,multipleOf:A,exclusiveMaximum:L,exclusiveMinimum:F}=e._zod.bag;typeof R=="string"&&R.includes("int")?m.type="integer":m.type="number",typeof F=="number"&&(m.exclusiveMinimum=F),typeof w=="number"&&(m.minimum=w,typeof F=="number"&&(F>=w?delete m.minimum:delete m.exclusiveMinimum)),typeof L=="number"&&(m.exclusiveMaximum=L),typeof $=="number"&&(m.maximum=$,typeof L=="number"&&(L<=$?delete m.maximum:delete m.exclusiveMaximum)),typeof A=="number"&&(m.multipleOf=A);break}case"boolean":{let m=f;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=f,{minimum:w,maximum:$}=e._zod.bag;typeof w=="number"&&(m.minItems=w),typeof $=="number"&&(m.maxItems=$),m.type="array",m.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let w=o.shape;for(let A in w)m.properties[A]=this.process(w[A],{...p,path:[...p.path,"properties",A]});let $=new Set(Object.keys(w)),R=new Set([...$].filter(A=>{let L=o.shape[A]._zod;return this.io==="input"?L.optin===void 0:L.optout===void 0}));R.size>0&&(m.required=Array.from(R)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=o.options.map((w,$)=>this.process(w,{...p,path:[...p.path,"anyOf",$]}));break}case"intersection":{let m=f,w=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),$=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),R=L=>"allOf"in L&&Object.keys(L).length===1,A=[...R(w)?w.allOf:[w],...R($)?$.allOf:[$]];m.allOf=A;break}case"tuple":{let m=f;m.type="array";let w=o.items.map((A,L)=>this.process(A,{...p,path:[...p.path,"prefixItems",L]}));if(this.target==="draft-2020-12"?m.prefixItems=w:m.items=w,o.rest){let A=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=A:m.additionalItems=A}o.rest&&(m.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:$,maximum:R}=e._zod.bag;typeof $=="number"&&(m.minItems=$),typeof R=="number"&&(m.maxItems=R);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=f,w=Es(o.entries);w.every($=>typeof $=="number")&&(m.type="number"),w.every($=>typeof $=="string")&&(m.type="string"),m.enum=w;break}case"literal":{let m=f,w=[];for(let $ of o.values)if($===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof $=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number($))}else w.push($);if(w.length!==0)if(w.length===1){let $=w[0];m.type=$===null?"null":typeof $,m.const=$}else w.every($=>typeof $=="number")&&(m.type="number"),w.every($=>typeof $=="string")&&(m.type="string"),w.every($=>typeof $=="boolean")&&(m.type="string"),w.every($=>$===null)&&(m.type="null"),m.enum=w;break}case"file":{let m=f,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:$,maximum:R,mime:A}=e._zod.bag;$!==void 0&&(w.minLength=$),R!==void 0&&(w.maxLength=R),A?A.length===1?(w.contentMediaType=A[0],Object.assign(m,w)):m.anyOf=A.map(L=>({...w,contentMediaType:L})):Object.assign(m,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,p);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=f,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=w.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,p),a.ref=m;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,p),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&tt(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=u=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let w=n.external.registry.get(u[0])?.id,$=n.external.uri??(A=>A);if(w)return{ref:$(w)};let R=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=R,{defId:R,ref:`${$("__shared")}#/${p}/${R}`}}if(u[1]===o)return{ref:"#"};let f=`#/${p}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:b,defId:f}=s(u);p.def={...p.schema},f&&(p.defId=f);let m=p.schema;for(let w in m)delete m[w];m.$ref=b};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
|
|
2344
2344
|
|
|
2345
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){i(u);continue}if(n.external){let f=n.external.registry.get(u[0])?.id;if(e!==u[0]&&f){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let b=this.seen.get(u),f=b.def??b.schema,
|
|
2346
|
-
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function jv(t){return t.description}function Dv(t){if(_r(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Eo(t){if(_r(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var js=O(()=>{Ss();eh()});var th=O(()=>{yt()});var Ds={};es(Ds,{ZodISODate:()=>Uv,ZodISODateTime:()=>Mv,ZodISODuration:()=>Fv,ZodISOTime:()=>qv,date:()=>nh,datetime:()=>rh,duration:()=>sh,time:()=>oh});function rh(t){return vv(Mv,t)}function nh(t){return kv(Uv,t)}function oh(t){return xv(qv,t)}function sh(t){return Sv(Fv,t)}var Mv,Uv,qv,Fv,ih=O(()=>{yt();ah();Mv=I("ZodISODateTime",(t,e)=>{pv.init(t,e),Be.init(t,e)});Uv=I("ZodISODate",(t,e)=>{hv.init(t,e),Be.init(t,e)});qv=I("ZodISOTime",(t,e)=>{mv.init(t,e),Be.init(t,e)});Fv=I("ZodISODuration",(t,e)=>{fv.init(t,e),Be.init(t,e)})});var Bv,dV,Ms,ch=O(()=>{yt();yt();Bv=(t,e)=>{Pa.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>ad(t,r)},flatten:{value:r=>id(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},dV=I("ZodError",Bv),Ms=I("ZodError",Bv,{Parent:Error})});var Zv,Vv,Hv,Kv,lh=O(()=>{yt();ch();Zv=ld(Ms),Vv=dd(Ms),Hv=hd(Ms),Kv=md(Ms)});function C(t){return dp(pO,t)}function Ae(t){return Op(Xv,t)}function Gv(t){return Np(AO,t)}function ot(t){return Lp(CO,t)}function Qv(t){return zp(IO,t)}function Ze(){return jp(OO)}function LO(t){return Dp(NO,t)}function ke(t,e){return $v(zO,t,e)}function H(t,e){let r={type:"object",get shape(){return ve.assignProp(this,"shape",{...t}),this.shape},...ve.normalizeParams(e)};return new ek(r)}function bt(t,e){return new ek({type:"object",get shape(){return ve.assignProp(this,"shape",{...t}),this.shape},catchall:Ze(),...ve.normalizeParams(e)})}function Me(t,e){return new tk({type:"union",options:t,...ve.normalizeParams(e)})}function ph(t,e,r){return new jO({type:"union",options:e,discriminator:t,...ve.normalizeParams(r)})}function Ga(t,e){return new DO({type:"intersection",left:t,right:e})}function De(t,e,r){return new MO({type:"record",keyType:t,valueType:e,...ve.normalizeParams(r)})}function Et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new uh({type:"enum",entries:r,...ve.normalizeParams(e)})}function X(t,e){return new UO({type:"literal",values:Array.isArray(t)?t:[t],...ve.normalizeParams(e)})}function rk(t){return new qO({type:"transform",transform:t})}function Ve(t){return new nk({type:"optional",innerType:t})}function Jv(t){return new FO({type:"nullable",innerType:t})}function ZO(t,e){return new BO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function HO(t,e){return new VO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function KO(t,e){return new ok({type:"nonoptional",innerType:t,...ve.normalizeParams(e)})}function GO(t,e){return new WO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function dh(t,e){return new JO({type:"pipe",in:t,out:e})}function XO(t){return new YO({type:"readonly",innerType:t})}function QO(t){let e=new ct({check:"custom"});return e._zod.check=t,e}function ik(t,e){return Gp(sk,t??(()=>!0),e)}function eN(t,e={}){return Jp(sk,t,e)}function tN(t){let e=QO(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ve.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ve.issue(o))}},t(r.value,r)));return e}function hh(t,e){return dh(rk(t),e)}var We,Yv,pO,Be,hO,Wv,Wa,mO,fO,gO,yO,bO,wO,_O,vO,kO,xO,SO,$O,TO,RO,EO,PO,Xv,AO,CO,IO,OO,NO,zO,ek,tk,jO,DO,MO,uh,UO,qO,nk,FO,BO,VO,ok,WO,JO,YO,sk,ah=O(()=>{yt();yt();th();ih();lh();We=I("ZodType",(t,e)=>(Ie.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Lt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Zv(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Hv(t,r,n),t.parseAsync=async(r,n)=>Vv(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Kv(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(eN(r,n)),t.superRefine=r=>t.check(tN(r)),t.overwrite=r=>t.check(qn(r)),t.optional=()=>Ve(t),t.nullable=()=>Jv(t),t.nullish=()=>Ve(Jv(t)),t.nonoptional=r=>KO(t,r),t.array=()=>ke(t),t.or=r=>Me([t,r]),t.and=r=>Ga(t,r),t.transform=r=>dh(t,rk(r)),t.default=r=>ZO(t,r),t.prefault=r=>HO(t,r),t.catch=r=>GO(t,r),t.pipe=r=>dh(t,r),t.readonly=()=>XO(t),t.describe=r=>{let n=t.clone();return Xr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Xr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Xr.get(t);let n=t.clone();return Xr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Yv=I("_ZodString",(t,e)=>{Os.init(t,e),We.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Mp(...n)),t.includes=(...n)=>t.check(Fp(...n)),t.startsWith=(...n)=>t.check(Bp(...n)),t.endsWith=(...n)=>t.check(Zp(...n)),t.min=(...n)=>t.check(To(...n)),t.max=(...n)=>t.check(Ba(...n)),t.length=(...n)=>t.check(Za(...n)),t.nonempty=(...n)=>t.check(To(1,...n)),t.lowercase=n=>t.check(Up(n)),t.uppercase=n=>t.check(qp(n)),t.trim=()=>t.check(Hp()),t.normalize=(...n)=>t.check(Vp(...n)),t.toLowerCase=()=>t.check(Kp()),t.toUpperCase=()=>t.check(Wp())}),pO=I("ZodString",(t,e)=>{Os.init(t,e),Yv.init(t,e),t.email=r=>t.check(pp(hO,r)),t.url=r=>t.check(yp(mO,r)),t.jwt=r=>t.check(Ip(PO,r)),t.emoji=r=>t.check(bp(fO,r)),t.guid=r=>t.check(Ma(Wv,r)),t.uuid=r=>t.check(hp(Wa,r)),t.uuidv4=r=>t.check(mp(Wa,r)),t.uuidv6=r=>t.check(fp(Wa,r)),t.uuidv7=r=>t.check(gp(Wa,r)),t.nanoid=r=>t.check(wp(gO,r)),t.guid=r=>t.check(Ma(Wv,r)),t.cuid=r=>t.check(_p(yO,r)),t.cuid2=r=>t.check(vp(bO,r)),t.ulid=r=>t.check(kp(wO,r)),t.base64=r=>t.check(Pp(TO,r)),t.base64url=r=>t.check(Ap(RO,r)),t.xid=r=>t.check(xp(_O,r)),t.ksuid=r=>t.check(Sp(vO,r)),t.ipv4=r=>t.check($p(kO,r)),t.ipv6=r=>t.check(Tp(xO,r)),t.cidrv4=r=>t.check(Rp(SO,r)),t.cidrv6=r=>t.check(Ep($O,r)),t.e164=r=>t.check(Cp(EO,r)),t.datetime=r=>t.check(rh(r)),t.date=r=>t.check(nh(r)),t.time=r=>t.check(oh(r)),t.duration=r=>t.check(sh(r))});Be=I("ZodStringFormat",(t,e)=>{je.init(t,e),Yv.init(t,e)}),hO=I("ZodEmail",(t,e)=>{$d.init(t,e),Be.init(t,e)}),Wv=I("ZodGUID",(t,e)=>{xd.init(t,e),Be.init(t,e)}),Wa=I("ZodUUID",(t,e)=>{Sd.init(t,e),Be.init(t,e)}),mO=I("ZodURL",(t,e)=>{Td.init(t,e),Be.init(t,e)}),fO=I("ZodEmoji",(t,e)=>{Rd.init(t,e),Be.init(t,e)}),gO=I("ZodNanoID",(t,e)=>{Ed.init(t,e),Be.init(t,e)}),yO=I("ZodCUID",(t,e)=>{Pd.init(t,e),Be.init(t,e)}),bO=I("ZodCUID2",(t,e)=>{Ad.init(t,e),Be.init(t,e)}),wO=I("ZodULID",(t,e)=>{Cd.init(t,e),Be.init(t,e)}),_O=I("ZodXID",(t,e)=>{Id.init(t,e),Be.init(t,e)}),vO=I("ZodKSUID",(t,e)=>{Od.init(t,e),Be.init(t,e)}),kO=I("ZodIPv4",(t,e)=>{Nd.init(t,e),Be.init(t,e)}),xO=I("ZodIPv6",(t,e)=>{Ld.init(t,e),Be.init(t,e)}),SO=I("ZodCIDRv4",(t,e)=>{zd.init(t,e),Be.init(t,e)}),$O=I("ZodCIDRv6",(t,e)=>{jd.init(t,e),Be.init(t,e)}),TO=I("ZodBase64",(t,e)=>{Dd.init(t,e),Be.init(t,e)}),RO=I("ZodBase64URL",(t,e)=>{Md.init(t,e),Be.init(t,e)}),EO=I("ZodE164",(t,e)=>{Ud.init(t,e),Be.init(t,e)}),PO=I("ZodJWT",(t,e)=>{qd.init(t,e),Be.init(t,e)}),Xv=I("ZodNumber",(t,e)=>{La.init(t,e),We.init(t,e),t.gt=(n,o)=>t.check(qa(n,o)),t.gte=(n,o)=>t.check(zs(n,o)),t.min=(n,o)=>t.check(zs(n,o)),t.lt=(n,o)=>t.check(Ua(n,o)),t.lte=(n,o)=>t.check(Ls(n,o)),t.max=(n,o)=>t.check(Ls(n,o)),t.int=n=>t.check(Gv(n)),t.safe=n=>t.check(Gv(n)),t.positive=n=>t.check(qa(0,n)),t.nonnegative=n=>t.check(zs(0,n)),t.negative=n=>t.check(Ua(0,n)),t.nonpositive=n=>t.check(Ls(0,n)),t.multipleOf=(n,o)=>t.check(Fa(n,o)),t.step=(n,o)=>t.check(Fa(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});AO=I("ZodNumberFormat",(t,e)=>{Fd.init(t,e),Xv.init(t,e)});CO=I("ZodBoolean",(t,e)=>{Bd.init(t,e),We.init(t,e)});IO=I("ZodNull",(t,e)=>{Zd.init(t,e),We.init(t,e)});OO=I("ZodUnknown",(t,e)=>{Vd.init(t,e),We.init(t,e)});NO=I("ZodNever",(t,e)=>{Hd.init(t,e),We.init(t,e)});zO=I("ZodArray",(t,e)=>{Kd.init(t,e),We.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(To(r,n)),t.nonempty=r=>t.check(To(1,r)),t.max=(r,n)=>t.check(Ba(r,n)),t.length=(r,n)=>t.check(Za(r,n)),t.unwrap=()=>t.element});ek=I("ZodObject",(t,e)=>{za.init(t,e),We.init(t,e),ve.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Et(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ze()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ze()}),t.strict=()=>t.clone({...t._zod.def,catchall:LO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ve.extend(t,r),t.merge=r=>ve.merge(t,r),t.pick=r=>ve.pick(t,r),t.omit=r=>ve.omit(t,r),t.partial=(...r)=>ve.partial(nk,t,r[0]),t.required=(...r)=>ve.required(ok,t,r[0])});tk=I("ZodUnion",(t,e)=>{ja.init(t,e),We.init(t,e),t.options=e.options});jO=I("ZodDiscriminatedUnion",(t,e)=>{tk.init(t,e),Wd.init(t,e)});DO=I("ZodIntersection",(t,e)=>{Gd.init(t,e),We.init(t,e)});MO=I("ZodRecord",(t,e)=>{Jd.init(t,e),We.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});uh=I("ZodEnum",(t,e)=>{Yd.init(t,e),We.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new uh({...e,checks:[],...ve.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new uh({...e,checks:[],...ve.normalizeParams(o),entries:s})}});UO=I("ZodLiteral",(t,e)=>{Xd.init(t,e),We.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});qO=I("ZodTransform",(t,e)=>{Qd.init(t,e),We.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ve.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ve.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});nk=I("ZodOptional",(t,e)=>{ep.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});FO=I("ZodNullable",(t,e)=>{tp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});BO=I("ZodDefault",(t,e)=>{rp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});VO=I("ZodPrefault",(t,e)=>{np.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});ok=I("ZodNonOptional",(t,e)=>{op.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});WO=I("ZodCatch",(t,e)=>{sp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});JO=I("ZodPipe",(t,e)=>{ip.init(t,e),We.init(t,e),t.in=e.in,t.out=e.out});YO=I("ZodReadonly",(t,e)=>{ap.init(t,e),We.init(t,e)});sk=I("ZodCustom",(t,e)=>{cp.init(t,e),We.init(t,e)})});var ak=O(()=>{});var ck=O(()=>{});var lk=O(()=>{yt();ah();th();ch();lh();ak();yt();wv();Da();ih();ck();Nt(bv())});var uk=O(()=>{lk()});var dk=O(()=>{uk()});function Ek(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Pk(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var fh,pk,tn,Ya,rt,hk,mk,RV,oN,sN,gh,zt,Us,fk,lt,Zt,Vt,ut,Xa,gk,yh,yk,bk,bh,qs,ee,wh,wk,_k,EV,Qa,iN,ec,aN,Fs,Po,vk,cN,lN,uN,dN,pN,hN,_h,mN,fN,vh,tc,gN,yN,rc,bN,Bs,Zs,wN,Vs,Ao,_N,Hs,nc,oc,sc,PV,ic,ac,cc,kk,xk,Sk,kh,$k,Ks,Co,Tk,vN,lc,kN,uc,xN,xh,SN,dc,$N,TN,RN,EN,PN,AN,CN,IN,ON,NN,pc,LN,zN,hc,Sh,$h,Th,jN,DN,MN,Rh,UN,qN,FN,BN,ZN,Rk,mc,VN,fc,AV,HN,Io,KN,CV,Ws,WN,Eh,GN,JN,YN,XN,QN,eL,tL,Ja,rL,nL,oL,Gs,Ph,sL,iL,aL,cL,lL,uL,dL,pL,hL,mL,fL,gL,yL,bL,wL,_L,vL,kL,Oo,xL,SL,$L,gc,TL,RL,EL,Ah,PL,IV,OV,NV,LV,zV,jV,J,mh,No=O(()=>{dk();fh="2025-11-25",pk=[fh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],tn="io.modelcontextprotocol/related-task",Ya="2.0",rt=ik(t=>t!==null&&(typeof t=="object"||typeof t=="function")),hk=Me([C(),Ae().int()]),mk=C(),RV=bt({ttl:Ae().optional(),pollInterval:Ae().optional()}),oN=H({ttl:Ae().optional()}),sN=H({taskId:C()}),gh=bt({progressToken:hk.optional(),[tn]:sN.optional()}),zt=H({_meta:gh.optional()}),Us=zt.extend({task:oN.optional()}),fk=t=>Us.safeParse(t).success,lt=H({method:C(),params:zt.loose().optional()}),Zt=H({_meta:gh.optional()}),Vt=H({method:C(),params:Zt.loose().optional()}),ut=bt({_meta:gh.optional()}),Xa=Me([C(),Ae().int()]),gk=H({jsonrpc:X(Ya),id:Xa,...lt.shape}).strict(),yh=t=>gk.safeParse(t).success,yk=H({jsonrpc:X(Ya),...Vt.shape}).strict(),bk=t=>yk.safeParse(t).success,bh=H({jsonrpc:X(Ya),id:Xa,result:ut}).strict(),qs=t=>bh.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ee||(ee={}));wh=H({jsonrpc:X(Ya),id:Xa.optional(),error:H({code:Ae().int(),message:C(),data:Ze().optional()})}).strict(),wk=t=>wh.safeParse(t).success,_k=Me([gk,yk,bh,wh]),EV=Me([bh,wh]),Qa=ut.strict(),iN=Zt.extend({requestId:Xa.optional(),reason:C().optional()}),ec=Vt.extend({method:X("notifications/cancelled"),params:iN}),aN=H({src:C(),mimeType:C().optional(),sizes:ke(C()).optional(),theme:Et(["light","dark"]).optional()}),Fs=H({icons:ke(aN).optional()}),Po=H({name:C(),title:C().optional()}),vk=Po.extend({...Po.shape,...Fs.shape,version:C(),websiteUrl:C().optional(),description:C().optional()}),cN=Ga(H({applyDefaults:ot().optional()}),De(C(),Ze())),lN=hh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ga(H({form:cN.optional(),url:rt.optional()}),De(C(),Ze()).optional())),uN=bt({list:rt.optional(),cancel:rt.optional(),requests:bt({sampling:bt({createMessage:rt.optional()}).optional(),elicitation:bt({create:rt.optional()}).optional()}).optional()}),dN=bt({list:rt.optional(),cancel:rt.optional(),requests:bt({tools:bt({call:rt.optional()}).optional()}).optional()}),pN=H({experimental:De(C(),rt).optional(),sampling:H({context:rt.optional(),tools:rt.optional()}).optional(),elicitation:lN.optional(),roots:H({listChanged:ot().optional()}).optional(),tasks:uN.optional(),extensions:De(C(),rt).optional()}),hN=zt.extend({protocolVersion:C(),capabilities:pN,clientInfo:vk}),_h=lt.extend({method:X("initialize"),params:hN}),mN=H({experimental:De(C(),rt).optional(),logging:rt.optional(),completions:rt.optional(),prompts:H({listChanged:ot().optional()}).optional(),resources:H({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:H({listChanged:ot().optional()}).optional(),tasks:dN.optional(),extensions:De(C(),rt).optional()}),fN=ut.extend({protocolVersion:C(),capabilities:mN,serverInfo:vk,instructions:C().optional()}),vh=Vt.extend({method:X("notifications/initialized"),params:Zt.optional()}),tc=lt.extend({method:X("ping"),params:zt.optional()}),gN=H({progress:Ae(),total:Ve(Ae()),message:Ve(C())}),yN=H({...Zt.shape,...gN.shape,progressToken:hk}),rc=Vt.extend({method:X("notifications/progress"),params:yN}),bN=zt.extend({cursor:mk.optional()}),Bs=lt.extend({params:bN.optional()}),Zs=ut.extend({nextCursor:mk.optional()}),wN=Et(["working","input_required","completed","failed","cancelled"]),Vs=H({taskId:C(),status:wN,ttl:Me([Ae(),Qv()]),createdAt:C(),lastUpdatedAt:C(),pollInterval:Ve(Ae()),statusMessage:Ve(C())}),Ao=ut.extend({task:Vs}),_N=Zt.merge(Vs),Hs=Vt.extend({method:X("notifications/tasks/status"),params:_N}),nc=lt.extend({method:X("tasks/get"),params:zt.extend({taskId:C()})}),oc=ut.merge(Vs),sc=lt.extend({method:X("tasks/result"),params:zt.extend({taskId:C()})}),PV=ut.loose(),ic=Bs.extend({method:X("tasks/list")}),ac=Zs.extend({tasks:ke(Vs)}),cc=lt.extend({method:X("tasks/cancel"),params:zt.extend({taskId:C()})}),kk=ut.merge(Vs),xk=H({uri:C(),mimeType:Ve(C()),_meta:De(C(),Ze()).optional()}),Sk=xk.extend({text:C()}),kh=C().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),$k=xk.extend({blob:kh}),Ks=Et(["user","assistant"]),Co=H({audience:ke(Ks).optional(),priority:Ae().min(0).max(1).optional(),lastModified:Ds.datetime({offset:!0}).optional()}),Tk=H({...Po.shape,...Fs.shape,uri:C(),description:Ve(C()),mimeType:Ve(C()),size:Ve(Ae()),annotations:Co.optional(),_meta:Ve(bt({}))}),vN=H({...Po.shape,...Fs.shape,uriTemplate:C(),description:Ve(C()),mimeType:Ve(C()),annotations:Co.optional(),_meta:Ve(bt({}))}),lc=Bs.extend({method:X("resources/list")}),kN=Zs.extend({resources:ke(Tk)}),uc=Bs.extend({method:X("resources/templates/list")}),xN=Zs.extend({resourceTemplates:ke(vN)}),xh=zt.extend({uri:C()}),SN=xh,dc=lt.extend({method:X("resources/read"),params:SN}),$N=ut.extend({contents:ke(Me([Sk,$k]))}),TN=Vt.extend({method:X("notifications/resources/list_changed"),params:Zt.optional()}),RN=xh,EN=lt.extend({method:X("resources/subscribe"),params:RN}),PN=xh,AN=lt.extend({method:X("resources/unsubscribe"),params:PN}),CN=Zt.extend({uri:C()}),IN=Vt.extend({method:X("notifications/resources/updated"),params:CN}),ON=H({name:C(),description:Ve(C()),required:Ve(ot())}),NN=H({...Po.shape,...Fs.shape,description:Ve(C()),arguments:Ve(ke(ON)),_meta:Ve(bt({}))}),pc=Bs.extend({method:X("prompts/list")}),LN=Zs.extend({prompts:ke(NN)}),zN=zt.extend({name:C(),arguments:De(C(),C()).optional()}),hc=lt.extend({method:X("prompts/get"),params:zN}),Sh=H({type:X("text"),text:C(),annotations:Co.optional(),_meta:De(C(),Ze()).optional()}),$h=H({type:X("image"),data:kh,mimeType:C(),annotations:Co.optional(),_meta:De(C(),Ze()).optional()}),Th=H({type:X("audio"),data:kh,mimeType:C(),annotations:Co.optional(),_meta:De(C(),Ze()).optional()}),jN=H({type:X("tool_use"),name:C(),id:C(),input:De(C(),Ze()),_meta:De(C(),Ze()).optional()}),DN=H({type:X("resource"),resource:Me([Sk,$k]),annotations:Co.optional(),_meta:De(C(),Ze()).optional()}),MN=Tk.extend({type:X("resource_link")}),Rh=Me([Sh,$h,Th,MN,DN]),UN=H({role:Ks,content:Rh}),qN=ut.extend({description:C().optional(),messages:ke(UN)}),FN=Vt.extend({method:X("notifications/prompts/list_changed"),params:Zt.optional()}),BN=H({title:C().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),ZN=H({taskSupport:Et(["required","optional","forbidden"]).optional()}),Rk=H({...Po.shape,...Fs.shape,description:C().optional(),inputSchema:H({type:X("object"),properties:De(C(),rt).optional(),required:ke(C()).optional()}).catchall(Ze()),outputSchema:H({type:X("object"),properties:De(C(),rt).optional(),required:ke(C()).optional()}).catchall(Ze()).optional(),annotations:BN.optional(),execution:ZN.optional(),_meta:De(C(),Ze()).optional()}),mc=Bs.extend({method:X("tools/list")}),VN=Zs.extend({tools:ke(Rk)}),fc=ut.extend({content:ke(Rh).default([]),structuredContent:De(C(),Ze()).optional(),isError:ot().optional()}),AV=fc.or(ut.extend({toolResult:Ze()})),HN=Us.extend({name:C(),arguments:De(C(),Ze()).optional()}),Io=lt.extend({method:X("tools/call"),params:HN}),KN=Vt.extend({method:X("notifications/tools/list_changed"),params:Zt.optional()}),CV=H({autoRefresh:ot().default(!0),debounceMs:Ae().int().nonnegative().default(300)}),Ws=Et(["debug","info","notice","warning","error","critical","alert","emergency"]),WN=zt.extend({level:Ws}),Eh=lt.extend({method:X("logging/setLevel"),params:WN}),GN=Zt.extend({level:Ws,logger:C().optional(),data:Ze()}),JN=Vt.extend({method:X("notifications/message"),params:GN}),YN=H({name:C().optional()}),XN=H({hints:ke(YN).optional(),costPriority:Ae().min(0).max(1).optional(),speedPriority:Ae().min(0).max(1).optional(),intelligencePriority:Ae().min(0).max(1).optional()}),QN=H({mode:Et(["auto","required","none"]).optional()}),eL=H({type:X("tool_result"),toolUseId:C().describe("The unique identifier for the corresponding tool call."),content:ke(Rh).default([]),structuredContent:H({}).loose().optional(),isError:ot().optional(),_meta:De(C(),Ze()).optional()}),tL=ph("type",[Sh,$h,Th]),Ja=ph("type",[Sh,$h,Th,jN,eL]),rL=H({role:Ks,content:Me([Ja,ke(Ja)]),_meta:De(C(),Ze()).optional()}),nL=Us.extend({messages:ke(rL),modelPreferences:XN.optional(),systemPrompt:C().optional(),includeContext:Et(["none","thisServer","allServers"]).optional(),temperature:Ae().optional(),maxTokens:Ae().int(),stopSequences:ke(C()).optional(),metadata:rt.optional(),tools:ke(Rk).optional(),toolChoice:QN.optional()}),oL=lt.extend({method:X("sampling/createMessage"),params:nL}),Gs=ut.extend({model:C(),stopReason:Ve(Et(["endTurn","stopSequence","maxTokens"]).or(C())),role:Ks,content:tL}),Ph=ut.extend({model:C(),stopReason:Ve(Et(["endTurn","stopSequence","maxTokens","toolUse"]).or(C())),role:Ks,content:Me([Ja,ke(Ja)])}),sL=H({type:X("boolean"),title:C().optional(),description:C().optional(),default:ot().optional()}),iL=H({type:X("string"),title:C().optional(),description:C().optional(),minLength:Ae().optional(),maxLength:Ae().optional(),format:Et(["email","uri","date","date-time"]).optional(),default:C().optional()}),aL=H({type:Et(["number","integer"]),title:C().optional(),description:C().optional(),minimum:Ae().optional(),maximum:Ae().optional(),default:Ae().optional()}),cL=H({type:X("string"),title:C().optional(),description:C().optional(),enum:ke(C()),default:C().optional()}),lL=H({type:X("string"),title:C().optional(),description:C().optional(),oneOf:ke(H({const:C(),title:C()})),default:C().optional()}),uL=H({type:X("string"),title:C().optional(),description:C().optional(),enum:ke(C()),enumNames:ke(C()).optional(),default:C().optional()}),dL=Me([cL,lL]),pL=H({type:X("array"),title:C().optional(),description:C().optional(),minItems:Ae().optional(),maxItems:Ae().optional(),items:H({type:X("string"),enum:ke(C())}),default:ke(C()).optional()}),hL=H({type:X("array"),title:C().optional(),description:C().optional(),minItems:Ae().optional(),maxItems:Ae().optional(),items:H({anyOf:ke(H({const:C(),title:C()}))}),default:ke(C()).optional()}),mL=Me([pL,hL]),fL=Me([uL,dL,mL]),gL=Me([fL,sL,iL,aL]),yL=Us.extend({mode:X("form").optional(),message:C(),requestedSchema:H({type:X("object"),properties:De(C(),gL),required:ke(C()).optional()})}),bL=Us.extend({mode:X("url"),message:C(),elicitationId:C(),url:C().url()}),wL=Me([yL,bL]),_L=lt.extend({method:X("elicitation/create"),params:wL}),vL=Zt.extend({elicitationId:C()}),kL=Vt.extend({method:X("notifications/elicitation/complete"),params:vL}),Oo=ut.extend({action:Et(["accept","decline","cancel"]),content:hh(t=>t===null?void 0:t,De(C(),Me([C(),Ae(),ot(),ke(C())])).optional())}),xL=H({type:X("ref/resource"),uri:C()}),SL=H({type:X("ref/prompt"),name:C()}),$L=zt.extend({ref:Me([SL,xL]),argument:H({name:C(),value:C()}),context:H({arguments:De(C(),C()).optional()}).optional()}),gc=lt.extend({method:X("completion/complete"),params:$L});TL=ut.extend({completion:bt({values:ke(C()).max(100),total:Ve(Ae().int()),hasMore:Ve(ot())})}),RL=H({uri:C().startsWith("file://"),name:C().optional(),_meta:De(C(),Ze()).optional()}),EL=lt.extend({method:X("roots/list"),params:zt.optional()}),Ah=ut.extend({roots:ke(RL)}),PL=Vt.extend({method:X("notifications/roots/list_changed"),params:Zt.optional()}),IV=Me([tc,_h,gc,Eh,hc,pc,lc,uc,dc,EN,AN,Io,mc,nc,sc,ic,cc]),OV=Me([ec,rc,vh,PL,Hs]),NV=Me([Qa,Gs,Ph,Oo,Ah,oc,ac,Ao]),LV=Me([tc,oL,_L,EL,nc,sc,ic,cc]),zV=Me([ec,rc,JN,IN,TN,KN,FN,Hs,kL]),jV=Me([Qa,fN,TL,qN,LN,kN,xN,$N,fc,VN,oc,ac,Ao]),J=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===ee.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new mh(o.elicitations,r)}return new t(e,r,n)}},mh=class extends J{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(ee.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function rn(t){return t==="completed"||t==="failed"||t==="cancelled"}var Ak=O(()=>{});var Ik,Ck,Ok,yc=O(()=>{Ik=Symbol("Let zodToJsonSchema decide on which parser to use"),Ck={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ok=t=>typeof t=="string"?{...Ck,name:t}:{...Ck,...t}});var Nk,Ch=O(()=>{yc();Nk=t=>{let e=Ok(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Ih(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,Ih(t,e,n,o)}var nn=O(()=>{});var bc,wc=O(()=>{bc=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function He(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?bc(e,t.currentPath):e.join("/")}}var Ht=O(()=>{wc()});function Lk(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=ae(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Oh=O(()=>{Ss();nn();et()});function zk(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var Nh=O(()=>{nn()});function jk(){return{type:"boolean"}}var Lh=O(()=>{});function _c(t,e){return ae(t.type._def,e)}var vc=O(()=>{et()});var Dk,zh=O(()=>{et();Dk=(t,e)=>ae(t.innerType._def,e)});function jh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>jh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return AL(t,e)}}var AL,Dh=O(()=>{nn();AL=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r}});function Mk(t,e){return{...ae(t.innerType._def,e),default:t.defaultValue()}}var Mh=O(()=>{et()});function Uk(t,e){return e.effectStrategy==="input"?ae(t.schema._def,e):He(e)}var Uh=O(()=>{et();Ht()});function qk(t){return{type:"string",enum:Array.from(t.values)}}var qh=O(()=>{});function Fk(t,e){let r=[ae(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ae(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(CL(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var CL,Fh=O(()=>{et();CL=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Bk(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Bh=O(()=>{});function kc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":sr(r,"email",n.message,e);break;case"format:idn-email":sr(r,"idn-email",n.message,e);break;case"pattern:zod":wt(r,or.email,n.message,e);break}break;case"url":sr(r,"uri",n.message,e);break;case"uuid":sr(r,"uuid",n.message,e);break;case"regex":wt(r,n.regex,n.message,e);break;case"cuid":wt(r,or.cuid,n.message,e);break;case"cuid2":wt(r,or.cuid2,n.message,e);break;case"startsWith":wt(r,RegExp(`^${Vh(n.value,e)}`),n.message,e);break;case"endsWith":wt(r,RegExp(`${Vh(n.value,e)}$`),n.message,e);break;case"datetime":sr(r,"date-time",n.message,e);break;case"date":sr(r,"date",n.message,e);break;case"time":sr(r,"time",n.message,e);break;case"duration":sr(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{wt(r,RegExp(Vh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&sr(r,"ipv4",n.message,e),n.version!=="v4"&&sr(r,"ipv6",n.message,e);break}case"base64url":wt(r,or.base64url,n.message,e);break;case"jwt":wt(r,or.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&wt(r,or.ipv4Cidr,n.message,e),n.version!=="v4"&&wt(r,or.ipv6Cidr,n.message,e);break}case"emoji":wt(r,or.emoji(),n.message,e);break;case"ulid":{wt(r,or.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{sr(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{wt(r,or.base64,n.message,e);break}}break}case"nanoid":wt(r,or.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Vh(t,e){return e.patternStrategy==="escape"?OL(t):t}function OL(t){let e="";for(let r=0;r<t.length;r++)IL.has(t[r])||(e+="\\"),e+=t[r];return e}function sr(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):xe(t,"format",e,r,n)}function wt(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Zk(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",Zk(e,n),r,n)}function Zk(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
2345
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){i(u);continue}if(n.external){let f=n.external.registry.get(u[0])?.id;if(e!==u[0]&&f){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let b=this.seen.get(u),f=b.def??b.schema,m={...f};if(b.ref===null)return;let w=b.ref;if(b.ref=null,w){a(w,p);let $=this.seen.get(w).schema;$.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push($)):(Object.assign(f,$),Object.assign(f,m))}b.isParent||this.override({zodSchema:u,jsonSchema:f,path:b.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let p=u[1];p.def&&p.defId&&(l[p.defId]=p.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Ov=N(()=>{});var yt=N(()=>{$o();gd();ld();vv();Oa();kd();wr();Ia();Ma();dp();vd();Cv();Av();Iv();Ov()});var Qp=N(()=>{yt()});function eh(t,e){let r={type:"object",get shape(){return ve.assignProp(this,"shape",{...t}),this.shape},...ve.normalizeParams(e)};return new cO(r)}var aO,cO,Nv=N(()=>{yt();yt();Qp();aO=I("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ie.init(t,e),t.def=e,t.parse=(r,n)=>dd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Mn(t,r,n),t.parseAsync=async(r,n)=>hd(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Un(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Lt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),cO=I("ZodMiniObject",(t,e)=>{za.init(t,e),aO.init(t,e),ve.defineLazy(t,"shape",()=>e.shape)})});var Lv=N(()=>{});var jv=N(()=>{});var zv=N(()=>{});var Dv=N(()=>{yt();Qp();Nv();Lv();yt();Ma();jv();zv()});var Mv=N(()=>{Dv()});var th=N(()=>{Mv()});function _r(t){return!!t._zod}function Bn(t){let e=Object.values(t);if(e.length===0)return eh({});let r=e.every(_r),n=e.every(o=>!_r(o));if(r)return eh(t);if(n)return Zl(t);throw new Error("Mixed Zod versions detected in object shape.")}function Qr(t,e){return _r(t)?Mn(t,e):t.safeParse(e)}async function Ka(t,e){return _r(t)?await Un(t,e):await t.safeParseAsync(e)}function en(t){if(!t)return;let e;if(_r(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Po(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Bn(t)}}if(_r(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function dO(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Wa(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${dO(e.path)}`:e.message).join(`
|
|
2346
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function qv(t){return t.description}function Fv(t){if(_r(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Ao(t){if(_r(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Ms=N(()=>{Ts();th()});var rh=N(()=>{yt()});var Us={};rs(Us,{ZodISODate:()=>Zv,ZodISODateTime:()=>Bv,ZodISODuration:()=>Hv,ZodISOTime:()=>Vv,date:()=>oh,datetime:()=>nh,duration:()=>ih,time:()=>sh});function nh(t){return $v(Bv,t)}function oh(t){return Tv(Zv,t)}function sh(t){return Rv(Vv,t)}function ih(t){return Ev(Hv,t)}var Bv,Zv,Vv,Hv,ah=N(()=>{yt();ch();Bv=I("ZodISODateTime",(t,e)=>{gv.init(t,e),Be.init(t,e)});Zv=I("ZodISODate",(t,e)=>{yv.init(t,e),Be.init(t,e)});Vv=I("ZodISOTime",(t,e)=>{bv.init(t,e),Be.init(t,e)});Hv=I("ZodISODuration",(t,e)=>{wv.init(t,e),Be.init(t,e)})});var Kv,wV,qs,lh=N(()=>{yt();yt();Kv=(t,e)=>{Aa.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>cd(t,r)},flatten:{value:r=>ad(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},wV=I("ZodError",Kv),qs=I("ZodError",Kv,{Parent:Error})});var Wv,Gv,Jv,Yv,uh=N(()=>{yt();lh();Wv=ud(qs),Gv=pd(qs),Jv=md(qs),Yv=fd(qs)});function C(t){return pp(wO,t)}function Ae(t){return Np(rk,t)}function Qv(t){return Lp(zO,t)}function ot(t){return jp(DO,t)}function nk(t){return zp(MO,t)}function Ze(){return Dp(UO)}function FO(t){return Mp(qO,t)}function ke(t,e){return Pv(BO,t,e)}function H(t,e){let r={type:"object",get shape(){return ve.assignProp(this,"shape",{...t}),this.shape},...ve.normalizeParams(e)};return new ok(r)}function bt(t,e){return new ok({type:"object",get shape(){return ve.assignProp(this,"shape",{...t}),this.shape},catchall:Ze(),...ve.normalizeParams(e)})}function Me(t,e){return new sk({type:"union",options:t,...ve.normalizeParams(e)})}function hh(t,e,r){return new ZO({type:"union",options:e,discriminator:t,...ve.normalizeParams(r)})}function Ja(t,e){return new VO({type:"intersection",left:t,right:e})}function De(t,e,r){return new HO({type:"record",keyType:t,valueType:e,...ve.normalizeParams(r)})}function Et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new dh({type:"enum",entries:r,...ve.normalizeParams(e)})}function X(t,e){return new KO({type:"literal",values:Array.isArray(t)?t:[t],...ve.normalizeParams(e)})}function ik(t){return new WO({type:"transform",transform:t})}function Ve(t){return new ak({type:"optional",innerType:t})}function ek(t){return new GO({type:"nullable",innerType:t})}function YO(t,e){return new JO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function QO(t,e){return new XO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function eN(t,e){return new ck({type:"nonoptional",innerType:t,...ve.normalizeParams(e)})}function rN(t,e){return new tN({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function ph(t,e){return new nN({type:"pipe",in:t,out:e})}function sN(t){return new oN({type:"readonly",innerType:t})}function iN(t){let e=new ct({check:"custom"});return e._zod.check=t,e}function uk(t,e){return Jp(lk,t??(()=>!0),e)}function aN(t,e={}){return Yp(lk,t,e)}function cN(t){let e=iN(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ve.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ve.issue(o))}},t(r.value,r)));return e}function mh(t,e){return ph(ik(t),e)}var We,tk,wO,Be,_O,Xv,Ga,vO,kO,xO,SO,$O,TO,RO,EO,PO,AO,CO,IO,OO,NO,LO,jO,rk,zO,DO,MO,UO,qO,BO,ok,sk,ZO,VO,HO,dh,KO,WO,ak,GO,JO,XO,ck,tN,nN,oN,lk,ch=N(()=>{yt();yt();rh();ah();uh();We=I("ZodType",(t,e)=>(Ie.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Lt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Wv(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Jv(t,r,n),t.parseAsync=async(r,n)=>Gv(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Yv(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(aN(r,n)),t.superRefine=r=>t.check(cN(r)),t.overwrite=r=>t.check(qn(r)),t.optional=()=>Ve(t),t.nullable=()=>ek(t),t.nullish=()=>Ve(ek(t)),t.nonoptional=r=>eN(t,r),t.array=()=>ke(t),t.or=r=>Me([t,r]),t.and=r=>Ja(t,r),t.transform=r=>ph(t,ik(r)),t.default=r=>YO(t,r),t.prefault=r=>QO(t,r),t.catch=r=>rN(t,r),t.pipe=r=>ph(t,r),t.readonly=()=>sN(t),t.describe=r=>{let n=t.clone();return Xr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Xr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Xr.get(t);let n=t.clone();return Xr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),tk=I("_ZodString",(t,e)=>{Ls.init(t,e),We.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Up(...n)),t.includes=(...n)=>t.check(Bp(...n)),t.startsWith=(...n)=>t.check(Zp(...n)),t.endsWith=(...n)=>t.check(Vp(...n)),t.min=(...n)=>t.check(Eo(...n)),t.max=(...n)=>t.check(Za(...n)),t.length=(...n)=>t.check(Va(...n)),t.nonempty=(...n)=>t.check(Eo(1,...n)),t.lowercase=n=>t.check(qp(n)),t.uppercase=n=>t.check(Fp(n)),t.trim=()=>t.check(Kp()),t.normalize=(...n)=>t.check(Hp(...n)),t.toLowerCase=()=>t.check(Wp()),t.toUpperCase=()=>t.check(Gp())}),wO=I("ZodString",(t,e)=>{Ls.init(t,e),tk.init(t,e),t.email=r=>t.check(hp(_O,r)),t.url=r=>t.check(bp(vO,r)),t.jwt=r=>t.check(Op(jO,r)),t.emoji=r=>t.check(wp(kO,r)),t.guid=r=>t.check(Ua(Xv,r)),t.uuid=r=>t.check(mp(Ga,r)),t.uuidv4=r=>t.check(fp(Ga,r)),t.uuidv6=r=>t.check(gp(Ga,r)),t.uuidv7=r=>t.check(yp(Ga,r)),t.nanoid=r=>t.check(_p(xO,r)),t.guid=r=>t.check(Ua(Xv,r)),t.cuid=r=>t.check(vp(SO,r)),t.cuid2=r=>t.check(kp($O,r)),t.ulid=r=>t.check(xp(TO,r)),t.base64=r=>t.check(Ap(OO,r)),t.base64url=r=>t.check(Cp(NO,r)),t.xid=r=>t.check(Sp(RO,r)),t.ksuid=r=>t.check($p(EO,r)),t.ipv4=r=>t.check(Tp(PO,r)),t.ipv6=r=>t.check(Rp(AO,r)),t.cidrv4=r=>t.check(Ep(CO,r)),t.cidrv6=r=>t.check(Pp(IO,r)),t.e164=r=>t.check(Ip(LO,r)),t.datetime=r=>t.check(nh(r)),t.date=r=>t.check(oh(r)),t.time=r=>t.check(sh(r)),t.duration=r=>t.check(ih(r))});Be=I("ZodStringFormat",(t,e)=>{ze.init(t,e),tk.init(t,e)}),_O=I("ZodEmail",(t,e)=>{Td.init(t,e),Be.init(t,e)}),Xv=I("ZodGUID",(t,e)=>{Sd.init(t,e),Be.init(t,e)}),Ga=I("ZodUUID",(t,e)=>{$d.init(t,e),Be.init(t,e)}),vO=I("ZodURL",(t,e)=>{Rd.init(t,e),Be.init(t,e)}),kO=I("ZodEmoji",(t,e)=>{Ed.init(t,e),Be.init(t,e)}),xO=I("ZodNanoID",(t,e)=>{Pd.init(t,e),Be.init(t,e)}),SO=I("ZodCUID",(t,e)=>{Ad.init(t,e),Be.init(t,e)}),$O=I("ZodCUID2",(t,e)=>{Cd.init(t,e),Be.init(t,e)}),TO=I("ZodULID",(t,e)=>{Id.init(t,e),Be.init(t,e)}),RO=I("ZodXID",(t,e)=>{Od.init(t,e),Be.init(t,e)}),EO=I("ZodKSUID",(t,e)=>{Nd.init(t,e),Be.init(t,e)}),PO=I("ZodIPv4",(t,e)=>{Ld.init(t,e),Be.init(t,e)}),AO=I("ZodIPv6",(t,e)=>{jd.init(t,e),Be.init(t,e)}),CO=I("ZodCIDRv4",(t,e)=>{zd.init(t,e),Be.init(t,e)}),IO=I("ZodCIDRv6",(t,e)=>{Dd.init(t,e),Be.init(t,e)}),OO=I("ZodBase64",(t,e)=>{Md.init(t,e),Be.init(t,e)}),NO=I("ZodBase64URL",(t,e)=>{Ud.init(t,e),Be.init(t,e)}),LO=I("ZodE164",(t,e)=>{qd.init(t,e),Be.init(t,e)}),jO=I("ZodJWT",(t,e)=>{Fd.init(t,e),Be.init(t,e)}),rk=I("ZodNumber",(t,e)=>{ja.init(t,e),We.init(t,e),t.gt=(n,o)=>t.check(Fa(n,o)),t.gte=(n,o)=>t.check(Ds(n,o)),t.min=(n,o)=>t.check(Ds(n,o)),t.lt=(n,o)=>t.check(qa(n,o)),t.lte=(n,o)=>t.check(zs(n,o)),t.max=(n,o)=>t.check(zs(n,o)),t.int=n=>t.check(Qv(n)),t.safe=n=>t.check(Qv(n)),t.positive=n=>t.check(Fa(0,n)),t.nonnegative=n=>t.check(Ds(0,n)),t.negative=n=>t.check(qa(0,n)),t.nonpositive=n=>t.check(zs(0,n)),t.multipleOf=(n,o)=>t.check(Ba(n,o)),t.step=(n,o)=>t.check(Ba(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});zO=I("ZodNumberFormat",(t,e)=>{Bd.init(t,e),rk.init(t,e)});DO=I("ZodBoolean",(t,e)=>{Zd.init(t,e),We.init(t,e)});MO=I("ZodNull",(t,e)=>{Vd.init(t,e),We.init(t,e)});UO=I("ZodUnknown",(t,e)=>{Hd.init(t,e),We.init(t,e)});qO=I("ZodNever",(t,e)=>{Kd.init(t,e),We.init(t,e)});BO=I("ZodArray",(t,e)=>{Wd.init(t,e),We.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Eo(r,n)),t.nonempty=r=>t.check(Eo(1,r)),t.max=(r,n)=>t.check(Za(r,n)),t.length=(r,n)=>t.check(Va(r,n)),t.unwrap=()=>t.element});ok=I("ZodObject",(t,e)=>{za.init(t,e),We.init(t,e),ve.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Et(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ze()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ze()}),t.strict=()=>t.clone({...t._zod.def,catchall:FO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ve.extend(t,r),t.merge=r=>ve.merge(t,r),t.pick=r=>ve.pick(t,r),t.omit=r=>ve.omit(t,r),t.partial=(...r)=>ve.partial(ak,t,r[0]),t.required=(...r)=>ve.required(ck,t,r[0])});sk=I("ZodUnion",(t,e)=>{Da.init(t,e),We.init(t,e),t.options=e.options});ZO=I("ZodDiscriminatedUnion",(t,e)=>{sk.init(t,e),Gd.init(t,e)});VO=I("ZodIntersection",(t,e)=>{Jd.init(t,e),We.init(t,e)});HO=I("ZodRecord",(t,e)=>{Yd.init(t,e),We.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});dh=I("ZodEnum",(t,e)=>{Xd.init(t,e),We.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new dh({...e,checks:[],...ve.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new dh({...e,checks:[],...ve.normalizeParams(o),entries:s})}});KO=I("ZodLiteral",(t,e)=>{Qd.init(t,e),We.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});WO=I("ZodTransform",(t,e)=>{ep.init(t,e),We.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ve.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ve.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});ak=I("ZodOptional",(t,e)=>{tp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});GO=I("ZodNullable",(t,e)=>{rp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});JO=I("ZodDefault",(t,e)=>{np.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});XO=I("ZodPrefault",(t,e)=>{op.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});ck=I("ZodNonOptional",(t,e)=>{sp.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType});tN=I("ZodCatch",(t,e)=>{ip.init(t,e),We.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});nN=I("ZodPipe",(t,e)=>{ap.init(t,e),We.init(t,e),t.in=e.in,t.out=e.out});oN=I("ZodReadonly",(t,e)=>{cp.init(t,e),We.init(t,e)});lk=I("ZodCustom",(t,e)=>{lp.init(t,e),We.init(t,e)})});var dk=N(()=>{});var pk=N(()=>{});var hk=N(()=>{yt();ch();rh();lh();uh();dk();yt();xv();Ma();ah();pk();Nt(kv())});var mk=N(()=>{hk()});var fk=N(()=>{mk()});function Ik(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Ok(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var gh,gk,tn,Xa,rt,yk,bk,LV,dN,pN,yh,jt,Fs,wk,lt,Zt,Vt,ut,Qa,_k,bh,vk,kk,wh,Bs,te,_h,xk,Sk,jV,ec,hN,tc,mN,Zs,Co,$k,fN,gN,yN,bN,wN,_N,vh,vN,kN,kh,rc,xN,SN,nc,$N,Vs,Hs,TN,Ks,Io,RN,Ws,oc,sc,ic,zV,ac,cc,lc,Tk,Rk,Ek,xh,Pk,Gs,Oo,Ak,EN,uc,PN,dc,AN,Sh,CN,pc,IN,ON,NN,LN,jN,zN,DN,MN,UN,qN,hc,FN,BN,mc,$h,Th,Rh,ZN,VN,HN,Eh,KN,WN,GN,JN,YN,Ck,fc,XN,gc,DV,QN,No,eL,MV,Js,tL,Ph,rL,nL,oL,sL,iL,aL,cL,Ya,lL,uL,dL,Ys,Ah,pL,hL,mL,fL,gL,yL,bL,wL,_L,vL,kL,xL,SL,$L,TL,RL,EL,PL,Lo,AL,CL,IL,yc,OL,NL,LL,Ch,jL,UV,qV,FV,BV,ZV,VV,Y,fh,jo=N(()=>{fk();gh="2025-11-25",gk=[gh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],tn="io.modelcontextprotocol/related-task",Xa="2.0",rt=uk(t=>t!==null&&(typeof t=="object"||typeof t=="function")),yk=Me([C(),Ae().int()]),bk=C(),LV=bt({ttl:Ae().optional(),pollInterval:Ae().optional()}),dN=H({ttl:Ae().optional()}),pN=H({taskId:C()}),yh=bt({progressToken:yk.optional(),[tn]:pN.optional()}),jt=H({_meta:yh.optional()}),Fs=jt.extend({task:dN.optional()}),wk=t=>Fs.safeParse(t).success,lt=H({method:C(),params:jt.loose().optional()}),Zt=H({_meta:yh.optional()}),Vt=H({method:C(),params:Zt.loose().optional()}),ut=bt({_meta:yh.optional()}),Qa=Me([C(),Ae().int()]),_k=H({jsonrpc:X(Xa),id:Qa,...lt.shape}).strict(),bh=t=>_k.safeParse(t).success,vk=H({jsonrpc:X(Xa),...Vt.shape}).strict(),kk=t=>vk.safeParse(t).success,wh=H({jsonrpc:X(Xa),id:Qa,result:ut}).strict(),Bs=t=>wh.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(te||(te={}));_h=H({jsonrpc:X(Xa),id:Qa.optional(),error:H({code:Ae().int(),message:C(),data:Ze().optional()})}).strict(),xk=t=>_h.safeParse(t).success,Sk=Me([_k,vk,wh,_h]),jV=Me([wh,_h]),ec=ut.strict(),hN=Zt.extend({requestId:Qa.optional(),reason:C().optional()}),tc=Vt.extend({method:X("notifications/cancelled"),params:hN}),mN=H({src:C(),mimeType:C().optional(),sizes:ke(C()).optional(),theme:Et(["light","dark"]).optional()}),Zs=H({icons:ke(mN).optional()}),Co=H({name:C(),title:C().optional()}),$k=Co.extend({...Co.shape,...Zs.shape,version:C(),websiteUrl:C().optional(),description:C().optional()}),fN=Ja(H({applyDefaults:ot().optional()}),De(C(),Ze())),gN=mh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ja(H({form:fN.optional(),url:rt.optional()}),De(C(),Ze()).optional())),yN=bt({list:rt.optional(),cancel:rt.optional(),requests:bt({sampling:bt({createMessage:rt.optional()}).optional(),elicitation:bt({create:rt.optional()}).optional()}).optional()}),bN=bt({list:rt.optional(),cancel:rt.optional(),requests:bt({tools:bt({call:rt.optional()}).optional()}).optional()}),wN=H({experimental:De(C(),rt).optional(),sampling:H({context:rt.optional(),tools:rt.optional()}).optional(),elicitation:gN.optional(),roots:H({listChanged:ot().optional()}).optional(),tasks:yN.optional(),extensions:De(C(),rt).optional()}),_N=jt.extend({protocolVersion:C(),capabilities:wN,clientInfo:$k}),vh=lt.extend({method:X("initialize"),params:_N}),vN=H({experimental:De(C(),rt).optional(),logging:rt.optional(),completions:rt.optional(),prompts:H({listChanged:ot().optional()}).optional(),resources:H({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:H({listChanged:ot().optional()}).optional(),tasks:bN.optional(),extensions:De(C(),rt).optional()}),kN=ut.extend({protocolVersion:C(),capabilities:vN,serverInfo:$k,instructions:C().optional()}),kh=Vt.extend({method:X("notifications/initialized"),params:Zt.optional()}),rc=lt.extend({method:X("ping"),params:jt.optional()}),xN=H({progress:Ae(),total:Ve(Ae()),message:Ve(C())}),SN=H({...Zt.shape,...xN.shape,progressToken:yk}),nc=Vt.extend({method:X("notifications/progress"),params:SN}),$N=jt.extend({cursor:bk.optional()}),Vs=lt.extend({params:$N.optional()}),Hs=ut.extend({nextCursor:bk.optional()}),TN=Et(["working","input_required","completed","failed","cancelled"]),Ks=H({taskId:C(),status:TN,ttl:Me([Ae(),nk()]),createdAt:C(),lastUpdatedAt:C(),pollInterval:Ve(Ae()),statusMessage:Ve(C())}),Io=ut.extend({task:Ks}),RN=Zt.merge(Ks),Ws=Vt.extend({method:X("notifications/tasks/status"),params:RN}),oc=lt.extend({method:X("tasks/get"),params:jt.extend({taskId:C()})}),sc=ut.merge(Ks),ic=lt.extend({method:X("tasks/result"),params:jt.extend({taskId:C()})}),zV=ut.loose(),ac=Vs.extend({method:X("tasks/list")}),cc=Hs.extend({tasks:ke(Ks)}),lc=lt.extend({method:X("tasks/cancel"),params:jt.extend({taskId:C()})}),Tk=ut.merge(Ks),Rk=H({uri:C(),mimeType:Ve(C()),_meta:De(C(),Ze()).optional()}),Ek=Rk.extend({text:C()}),xh=C().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Pk=Rk.extend({blob:xh}),Gs=Et(["user","assistant"]),Oo=H({audience:ke(Gs).optional(),priority:Ae().min(0).max(1).optional(),lastModified:Us.datetime({offset:!0}).optional()}),Ak=H({...Co.shape,...Zs.shape,uri:C(),description:Ve(C()),mimeType:Ve(C()),size:Ve(Ae()),annotations:Oo.optional(),_meta:Ve(bt({}))}),EN=H({...Co.shape,...Zs.shape,uriTemplate:C(),description:Ve(C()),mimeType:Ve(C()),annotations:Oo.optional(),_meta:Ve(bt({}))}),uc=Vs.extend({method:X("resources/list")}),PN=Hs.extend({resources:ke(Ak)}),dc=Vs.extend({method:X("resources/templates/list")}),AN=Hs.extend({resourceTemplates:ke(EN)}),Sh=jt.extend({uri:C()}),CN=Sh,pc=lt.extend({method:X("resources/read"),params:CN}),IN=ut.extend({contents:ke(Me([Ek,Pk]))}),ON=Vt.extend({method:X("notifications/resources/list_changed"),params:Zt.optional()}),NN=Sh,LN=lt.extend({method:X("resources/subscribe"),params:NN}),jN=Sh,zN=lt.extend({method:X("resources/unsubscribe"),params:jN}),DN=Zt.extend({uri:C()}),MN=Vt.extend({method:X("notifications/resources/updated"),params:DN}),UN=H({name:C(),description:Ve(C()),required:Ve(ot())}),qN=H({...Co.shape,...Zs.shape,description:Ve(C()),arguments:Ve(ke(UN)),_meta:Ve(bt({}))}),hc=Vs.extend({method:X("prompts/list")}),FN=Hs.extend({prompts:ke(qN)}),BN=jt.extend({name:C(),arguments:De(C(),C()).optional()}),mc=lt.extend({method:X("prompts/get"),params:BN}),$h=H({type:X("text"),text:C(),annotations:Oo.optional(),_meta:De(C(),Ze()).optional()}),Th=H({type:X("image"),data:xh,mimeType:C(),annotations:Oo.optional(),_meta:De(C(),Ze()).optional()}),Rh=H({type:X("audio"),data:xh,mimeType:C(),annotations:Oo.optional(),_meta:De(C(),Ze()).optional()}),ZN=H({type:X("tool_use"),name:C(),id:C(),input:De(C(),Ze()),_meta:De(C(),Ze()).optional()}),VN=H({type:X("resource"),resource:Me([Ek,Pk]),annotations:Oo.optional(),_meta:De(C(),Ze()).optional()}),HN=Ak.extend({type:X("resource_link")}),Eh=Me([$h,Th,Rh,HN,VN]),KN=H({role:Gs,content:Eh}),WN=ut.extend({description:C().optional(),messages:ke(KN)}),GN=Vt.extend({method:X("notifications/prompts/list_changed"),params:Zt.optional()}),JN=H({title:C().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),YN=H({taskSupport:Et(["required","optional","forbidden"]).optional()}),Ck=H({...Co.shape,...Zs.shape,description:C().optional(),inputSchema:H({type:X("object"),properties:De(C(),rt).optional(),required:ke(C()).optional()}).catchall(Ze()),outputSchema:H({type:X("object"),properties:De(C(),rt).optional(),required:ke(C()).optional()}).catchall(Ze()).optional(),annotations:JN.optional(),execution:YN.optional(),_meta:De(C(),Ze()).optional()}),fc=Vs.extend({method:X("tools/list")}),XN=Hs.extend({tools:ke(Ck)}),gc=ut.extend({content:ke(Eh).default([]),structuredContent:De(C(),Ze()).optional(),isError:ot().optional()}),DV=gc.or(ut.extend({toolResult:Ze()})),QN=Fs.extend({name:C(),arguments:De(C(),Ze()).optional()}),No=lt.extend({method:X("tools/call"),params:QN}),eL=Vt.extend({method:X("notifications/tools/list_changed"),params:Zt.optional()}),MV=H({autoRefresh:ot().default(!0),debounceMs:Ae().int().nonnegative().default(300)}),Js=Et(["debug","info","notice","warning","error","critical","alert","emergency"]),tL=jt.extend({level:Js}),Ph=lt.extend({method:X("logging/setLevel"),params:tL}),rL=Zt.extend({level:Js,logger:C().optional(),data:Ze()}),nL=Vt.extend({method:X("notifications/message"),params:rL}),oL=H({name:C().optional()}),sL=H({hints:ke(oL).optional(),costPriority:Ae().min(0).max(1).optional(),speedPriority:Ae().min(0).max(1).optional(),intelligencePriority:Ae().min(0).max(1).optional()}),iL=H({mode:Et(["auto","required","none"]).optional()}),aL=H({type:X("tool_result"),toolUseId:C().describe("The unique identifier for the corresponding tool call."),content:ke(Eh).default([]),structuredContent:H({}).loose().optional(),isError:ot().optional(),_meta:De(C(),Ze()).optional()}),cL=hh("type",[$h,Th,Rh]),Ya=hh("type",[$h,Th,Rh,ZN,aL]),lL=H({role:Gs,content:Me([Ya,ke(Ya)]),_meta:De(C(),Ze()).optional()}),uL=Fs.extend({messages:ke(lL),modelPreferences:sL.optional(),systemPrompt:C().optional(),includeContext:Et(["none","thisServer","allServers"]).optional(),temperature:Ae().optional(),maxTokens:Ae().int(),stopSequences:ke(C()).optional(),metadata:rt.optional(),tools:ke(Ck).optional(),toolChoice:iL.optional()}),dL=lt.extend({method:X("sampling/createMessage"),params:uL}),Ys=ut.extend({model:C(),stopReason:Ve(Et(["endTurn","stopSequence","maxTokens"]).or(C())),role:Gs,content:cL}),Ah=ut.extend({model:C(),stopReason:Ve(Et(["endTurn","stopSequence","maxTokens","toolUse"]).or(C())),role:Gs,content:Me([Ya,ke(Ya)])}),pL=H({type:X("boolean"),title:C().optional(),description:C().optional(),default:ot().optional()}),hL=H({type:X("string"),title:C().optional(),description:C().optional(),minLength:Ae().optional(),maxLength:Ae().optional(),format:Et(["email","uri","date","date-time"]).optional(),default:C().optional()}),mL=H({type:Et(["number","integer"]),title:C().optional(),description:C().optional(),minimum:Ae().optional(),maximum:Ae().optional(),default:Ae().optional()}),fL=H({type:X("string"),title:C().optional(),description:C().optional(),enum:ke(C()),default:C().optional()}),gL=H({type:X("string"),title:C().optional(),description:C().optional(),oneOf:ke(H({const:C(),title:C()})),default:C().optional()}),yL=H({type:X("string"),title:C().optional(),description:C().optional(),enum:ke(C()),enumNames:ke(C()).optional(),default:C().optional()}),bL=Me([fL,gL]),wL=H({type:X("array"),title:C().optional(),description:C().optional(),minItems:Ae().optional(),maxItems:Ae().optional(),items:H({type:X("string"),enum:ke(C())}),default:ke(C()).optional()}),_L=H({type:X("array"),title:C().optional(),description:C().optional(),minItems:Ae().optional(),maxItems:Ae().optional(),items:H({anyOf:ke(H({const:C(),title:C()}))}),default:ke(C()).optional()}),vL=Me([wL,_L]),kL=Me([yL,bL,vL]),xL=Me([kL,pL,hL,mL]),SL=Fs.extend({mode:X("form").optional(),message:C(),requestedSchema:H({type:X("object"),properties:De(C(),xL),required:ke(C()).optional()})}),$L=Fs.extend({mode:X("url"),message:C(),elicitationId:C(),url:C().url()}),TL=Me([SL,$L]),RL=lt.extend({method:X("elicitation/create"),params:TL}),EL=Zt.extend({elicitationId:C()}),PL=Vt.extend({method:X("notifications/elicitation/complete"),params:EL}),Lo=ut.extend({action:Et(["accept","decline","cancel"]),content:mh(t=>t===null?void 0:t,De(C(),Me([C(),Ae(),ot(),ke(C())])).optional())}),AL=H({type:X("ref/resource"),uri:C()}),CL=H({type:X("ref/prompt"),name:C()}),IL=jt.extend({ref:Me([CL,AL]),argument:H({name:C(),value:C()}),context:H({arguments:De(C(),C()).optional()}).optional()}),yc=lt.extend({method:X("completion/complete"),params:IL});OL=ut.extend({completion:bt({values:ke(C()).max(100),total:Ve(Ae().int()),hasMore:Ve(ot())})}),NL=H({uri:C().startsWith("file://"),name:C().optional(),_meta:De(C(),Ze()).optional()}),LL=lt.extend({method:X("roots/list"),params:jt.optional()}),Ch=ut.extend({roots:ke(NL)}),jL=Vt.extend({method:X("notifications/roots/list_changed"),params:Zt.optional()}),UV=Me([rc,vh,yc,Ph,mc,hc,uc,dc,pc,LN,zN,No,fc,oc,ic,ac,lc]),qV=Me([tc,nc,kh,jL,Ws]),FV=Me([ec,Ys,Ah,Lo,Ch,sc,cc,Io]),BV=Me([rc,dL,RL,LL,oc,ic,ac,lc]),ZV=Me([tc,nc,nL,MN,ON,eL,GN,Ws,PL]),VV=Me([ec,kN,OL,WN,FN,PN,AN,IN,gc,XN,sc,cc,Io]),Y=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===te.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new fh(o.elicitations,r)}return new t(e,r,n)}},fh=class extends Y{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(te.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function rn(t){return t==="completed"||t==="failed"||t==="cancelled"}var Nk=N(()=>{});var jk,Lk,zk,bc=N(()=>{jk=Symbol("Let zodToJsonSchema decide on which parser to use"),Lk={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},zk=t=>typeof t=="string"?{...Lk,name:t}:{...Lk,...t}});var Dk,Ih=N(()=>{bc();Dk=t=>{let e=zk(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Oh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,Oh(t,e,n,o)}var nn=N(()=>{});var wc,_c=N(()=>{wc=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function He(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?wc(e,t.currentPath):e.join("/")}}var Ht=N(()=>{_c()});function Mk(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=ce(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Nh=N(()=>{Ts();nn();et()});function Uk(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var Lh=N(()=>{nn()});function qk(){return{type:"boolean"}}var jh=N(()=>{});function vc(t,e){return ce(t.type._def,e)}var kc=N(()=>{et()});var Fk,zh=N(()=>{et();Fk=(t,e)=>ce(t.innerType._def,e)});function Dh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Dh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zL(t,e)}}var zL,Mh=N(()=>{nn();zL=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r}});function Bk(t,e){return{...ce(t.innerType._def,e),default:t.defaultValue()}}var Uh=N(()=>{et()});function Zk(t,e){return e.effectStrategy==="input"?ce(t.schema._def,e):He(e)}var qh=N(()=>{et();Ht()});function Vk(t){return{type:"string",enum:Array.from(t.values)}}var Fh=N(()=>{});function Hk(t,e){let r=[ce(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ce(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(DL(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var DL,Bh=N(()=>{et();DL=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Kk(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Zh=N(()=>{});function xc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":sr(r,"email",n.message,e);break;case"format:idn-email":sr(r,"idn-email",n.message,e);break;case"pattern:zod":wt(r,or.email,n.message,e);break}break;case"url":sr(r,"uri",n.message,e);break;case"uuid":sr(r,"uuid",n.message,e);break;case"regex":wt(r,n.regex,n.message,e);break;case"cuid":wt(r,or.cuid,n.message,e);break;case"cuid2":wt(r,or.cuid2,n.message,e);break;case"startsWith":wt(r,RegExp(`^${Hh(n.value,e)}`),n.message,e);break;case"endsWith":wt(r,RegExp(`${Hh(n.value,e)}$`),n.message,e);break;case"datetime":sr(r,"date-time",n.message,e);break;case"date":sr(r,"date",n.message,e);break;case"time":sr(r,"time",n.message,e);break;case"duration":sr(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{wt(r,RegExp(Hh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&sr(r,"ipv4",n.message,e),n.version!=="v4"&&sr(r,"ipv6",n.message,e);break}case"base64url":wt(r,or.base64url,n.message,e);break;case"jwt":wt(r,or.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&wt(r,or.ipv4Cidr,n.message,e),n.version!=="v4"&&wt(r,or.ipv6Cidr,n.message,e);break}case"emoji":wt(r,or.emoji(),n.message,e);break;case"ulid":{wt(r,or.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{sr(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{wt(r,or.base64,n.message,e);break}}break}case"nanoid":wt(r,or.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Hh(t,e){return e.patternStrategy==="escape"?UL(t):t}function UL(t){let e="";for(let r=0;r<t.length;r++)ML.has(t[r])||(e+="\\"),e+=t[r];return e}function sr(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):xe(t,"format",e,r,n)}function wt(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Wk(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",Wk(e,n),r,n)}function Wk(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
2347
2347
|
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
2348
2348
|
]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
|
|
2349
2349
|
`:`[${n[c]}\r
|
|
2350
|
-
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Zh,or,IL,xc=O(()=>{nn();or={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Zh===void 0&&(Zh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Zh),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};IL=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Sc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:ae(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??He(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ae(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=kc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=_c(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var $c=O(()=>{Ss();et();xc();vc();Ht()});function Vk(t,e){if(e.mapStrategy==="record")return Sc(t,e);let r=ae(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||He(e),n=ae(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||He(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Hh=O(()=>{et();$c();Ht()});function Hk(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Kh=O(()=>{});function Kk(t){return t.target==="openAi"?void 0:{not:He({...t,currentPath:[...t.currentPath,"not"]})}}var Wh=O(()=>{Ht()});function Wk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Gh=O(()=>{});function Jk(t,e){if(e.target==="openApi3")return Gk(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Js&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Js[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Gk(t,e)}var Js,Gk,Tc=O(()=>{et();Js={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Gk=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ae(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function Yk(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Js[t.innerType._def.typeName],nullable:!0}:{type:[Js[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ae(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ae(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Jh=O(()=>{et();Tc()});function Xk(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Ih(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var Yh=O(()=>{nn()});function Qk(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let l=LL(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ae(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||o.push(a))}o.length&&(n.required=o);let i=NL(t,e);return i!==void 0&&(n.additionalProperties=i),n}function NL(t,e){if(t.catchall._def.typeName!=="ZodNever")return ae(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function LL(t){try{return t.isOptional()}catch{return!0}}var Xh=O(()=>{et()});var ex,Qh=O(()=>{et();Ht();ex=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ae(t.innerType._def,e);let r=ae(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:He(e)},r]}:He(e)}});var tx,em=O(()=>{et();tx=(t,e)=>{if(e.pipeStrategy==="input")return ae(t.in._def,e);if(e.pipeStrategy==="output")return ae(t.out._def,e);let r=ae(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ae(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function rx(t,e){return ae(t.type._def,e)}var tm=O(()=>{et()});function nx(t,e){let n={type:"array",uniqueItems:!0,items:ae(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var rm=O(()=>{nn();et()});function ox(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ae(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ae(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ae(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var nm=O(()=>{et()});function sx(t){return{not:He(t)}}var om=O(()=>{Ht()});function ix(t){return He(t)}var sm=O(()=>{Ht()});var ax,im=O(()=>{et();ax=(t,e)=>ae(t.innerType._def,e)});var cx,am=O(()=>{Ss();Ht();Oh();Nh();Lh();vc();zh();Dh();Mh();Uh();qh();Fh();Bh();Hh();Kh();Wh();Gh();Jh();Yh();Xh();Qh();em();tm();$c();rm();xc();nm();om();Tc();sm();im();cx=(t,e,r)=>{switch(e){case D.ZodString:return kc(t,r);case D.ZodNumber:return Xk(t,r);case D.ZodObject:return Qk(t,r);case D.ZodBigInt:return zk(t,r);case D.ZodBoolean:return jk();case D.ZodDate:return jh(t,r);case D.ZodUndefined:return sx(r);case D.ZodNull:return Wk(r);case D.ZodArray:return Lk(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return Jk(t,r);case D.ZodIntersection:return Fk(t,r);case D.ZodTuple:return ox(t,r);case D.ZodRecord:return Sc(t,r);case D.ZodLiteral:return Bk(t,r);case D.ZodEnum:return qk(t);case D.ZodNativeEnum:return Hk(t);case D.ZodNullable:return Yk(t,r);case D.ZodOptional:return ex(t,r);case D.ZodMap:return Vk(t,r);case D.ZodSet:return nx(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return rx(t,r);case D.ZodNaN:case D.ZodNever:return Kk(r);case D.ZodEffects:return Uk(t,r);case D.ZodAny:return He(r);case D.ZodUnknown:return ix(r);case D.ZodDefault:return Mk(t,r);case D.ZodBranded:return _c(t,r);case D.ZodReadonly:return ax(t,r);case D.ZodCatch:return Dk(t,r);case D.ZodPipeline:return tx(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function ae(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Ik)return a}if(n&&!r){let a=zL(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=cx(t,t.typeName,e),i=typeof s=="function"?ae(s(),e):s;if(i&&jL(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var zL,jL,et=O(()=>{yc();am();wc();Ht();zL=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:bc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),He(e)):e.$refStrategy==="seen"?He(e):void 0}},jL=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var lx=O(()=>{});var cm,lm=O(()=>{et();Ch();Ht();cm=(t,e)=>{let r=Nk(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ae(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??He(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ae(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??He(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var ux=O(()=>{yc();Ch();nn();wc();et();lx();Ht();Oh();Nh();Lh();vc();zh();Dh();Mh();Uh();qh();Fh();Bh();Hh();Kh();Wh();Gh();Jh();Yh();Xh();Qh();em();tm();im();$c();rm();xc();nm();om();Tc();sm();am();lm();lm()});function DL(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function um(t,e){return _r(t)?Yp(t,{target:DL(e?.target),io:e?.pipeStrategy??"input"}):cm(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function dm(t){let r=en(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Eo(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function pm(t,e){let r=Qr(t,e);if(!r.success)throw r.error;return r.data}var hm=O(()=>{eh();js();ux()});function dx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function px(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];dx(i)&&dx(s)?r[o]={...i,...s}:r[o]=s}return r}var ML,Rc,hx=O(()=>{js();No();Ak();hm();ML=6e4,Rc=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ec,r=>{this._oncancel(r)}),this.setNotificationHandler(rc,r=>{this._onprogress(r)}),this.setRequestHandler(tc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(nc,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(ee.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(sc,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let p=c,b=new J(p.error.code,p.error.message,p.error.data);u(b)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new J(ee.InvalidParams,`Task not found: ${s}`);if(!rn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(rn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[tn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ic,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new J(ee.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(cc,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(ee.InvalidParams,`Task not found: ${r.params.taskId}`);if(rn(o.status))throw new J(ee.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new J(ee.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof J?o:new J(ee.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),J.fromError(ee.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),qs(s)||wk(s)?this._onresponse(s):yh(s)?this._onrequest(s,i):bk(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=J.fromError(ee.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[tn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:ee.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=fk(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,b)=>{if(i.signal.aborted)throw new J(ee.ConnectionClosed,"Request was cancelled");let f={...b,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let h=f.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,p,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:ee.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),qs(e))n(e);else{let i=new J(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(qs(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),qs(e))o(e);else{let i=J.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof J?i:new J(ee.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Ao,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new J(ee.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},rn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new J(ee.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new J(ee.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof J?i:new J(ee.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=A=>{u(A)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(A){p(A);return}n?.signal?.throwIfAborted();let b=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:b}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[tn]:c}});let h=A=>{this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(A)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(F=>this._onerror(new Error(`Failed to send cancellation: ${F}`)));let L=A instanceof J?A:new J(ee.RequestTimeout,String(A));u(L)};this._responseHandlers.set(b,A=>{if(!n?.signal?.aborted){if(A instanceof Error)return u(A);try{let L=Qr(r,A.result);L.success?l(L.data):u(L.error)}catch(L){u(L)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let w=n?.timeout??ML,S=()=>h(J.fromError(ee.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(b,w,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let R=c?.taskId;if(R){let A=L=>{let F=this._responseHandlers.get(b);F?F(L):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,A),this._enqueueTaskMessage(R,{type:"request",message:f,timestamp:Date.now()}).catch(L=>{this._cleanupTimeout(b),u(L)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(A=>{this._cleanupTimeout(b),u(A)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},oc,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ac,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},kk,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[tn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[tn]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[tn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=dm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=pm(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=dm(e);this._notificationHandlers.set(n,o=>{let s=pm(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&yh(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new J(ee.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new J(ee.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new J(ee.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new J(ee.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Hs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),rn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new J(ee.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(rn(a.status))throw new J(ee.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=Hs.parse({method:"notifications/tasks/status",params:c});await this.notification(l),rn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Qs=B(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.regexpCode=Re.getEsmExportName=Re.getProperty=Re.safeStringify=Re.stringify=Re.strConcat=Re.addCodeArg=Re.str=Re._=Re.nil=Re._Code=Re.Name=Re.IDENTIFIER=Re._CodeOrName=void 0;var Ys=class{};Re._CodeOrName=Ys;Re.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Zn=class extends Ys{constructor(e){if(super(),!Re.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Re.Name=Zn;var Kt=class extends Ys{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Zn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Re._Code=Kt;Re.nil=new Kt("");function mx(t,...e){let r=[t[0]],n=0;for(;n<e.length;)fm(r,e[n]),r.push(t[++n]);return new Kt(r)}Re._=mx;var mm=new Kt("+");function fx(t,...e){let r=[Xs(t[0])],n=0;for(;n<e.length;)r.push(mm),fm(r,e[n]),r.push(mm,Xs(t[++n]));return UL(r),new Kt(r)}Re.str=fx;function fm(t,e){e instanceof Kt?t.push(...e._items):e instanceof Zn?t.push(e):t.push(BL(e))}Re.addCodeArg=fm;function UL(t){let e=1;for(;e<t.length-1;){if(t[e]===mm){let r=qL(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function qL(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Zn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Zn))return`"${t}${e.slice(1)}`}function FL(t,e){return e.emptyStr()?t:t.emptyStr()?e:fx`${t}${e}`}Re.strConcat=FL;function BL(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Xs(Array.isArray(t)?t.join(","):t)}function ZL(t){return new Kt(Xs(t))}Re.stringify=ZL;function Xs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Re.safeStringify=Xs;function VL(t){return typeof t=="string"&&Re.IDENTIFIER.test(t)?new Kt(`.${t}`):mx`[${t}]`}Re.getProperty=VL;function HL(t){if(typeof t=="string"&&Re.IDENTIFIER.test(t))return new Kt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Re.getEsmExportName=HL;function KL(t){return new Kt(t.toString())}Re.regexpCode=KL});var bm=B(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.ValueScope=At.ValueScopeName=At.Scope=At.varKinds=At.UsedValueState=void 0;var Pt=Qs(),gm=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ec;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ec||(At.UsedValueState=Ec={}));At.varKinds={const:new Pt.Name("const"),let:new Pt.Name("let"),var:new Pt.Name("var")};var Pc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Pt.Name?e:this.name(e)}name(e){return new Pt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};At.Scope=Pc;var Ac=class extends Pt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Pt._)`.${new Pt.Name(r)}[${n}]`}};At.ValueScopeName=Ac;var WL=(0,Pt._)`\n`,ym=class extends Pc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?WL:Pt.nil}}get(){return this._scope}name(e){return new Ac(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Pt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Pt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Ec.Started);let u=r(l);if(u){let p=this.opts.es5?At.varKinds.var:At.varKinds.const;s=(0,Pt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Pt._)`${s}${u}${this.opts._n}`;else throw new gm(l);c.set(l,Ec.Completed)})}return s}};At.ValueScope=ym});var me=B(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var Se=Qs(),ir=bm(),on=Qs();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return on._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return on.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return on.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return on.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return on.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return on.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return on.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return on.Name}});var Nc=bm();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return Nc.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return Nc.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return Nc.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return Nc.varKinds}});fe.operators={GT:new Se._Code(">"),GTE:new Se._Code(">="),LT:new Se._Code("<"),LTE:new Se._Code("<="),EQ:new Se._Code("==="),NEQ:new Se._Code("!=="),NOT:new Se._Code("!"),OR:new Se._Code("||"),AND:new Se._Code("&&"),ADD:new Se._Code("+")};var zr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},wm=class extends zr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ir.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=zo(this.rhs,e,r)),this}get names(){return this.rhs instanceof Se._CodeOrName?this.rhs.names:{}}},Cc=class extends zr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Se.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=zo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Se.Name?{}:{...this.lhs.names};return Oc(e,this.rhs)}},_m=class extends Cc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},vm=class extends zr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},km=class extends zr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},xm=class extends zr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Sm=class extends zr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=zo(this.code,e,r),this}get names(){return this.code instanceof Se._CodeOrName?this.code.names:{}}},ei=class extends zr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(GL(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Kn(e,r.names),{})}},jr=class extends ei{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},$m=class extends ei{},Lo=class extends jr{};Lo.kind="else";var Vn=class t extends jr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Lo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(gx(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=zo(this.condition,e,r),this}get names(){let e=super.names;return Oc(e,this.condition),this.else&&Kn(e,this.else.names),e}};Vn.kind="if";var Hn=class extends jr{};Hn.kind="for";var Tm=class extends Hn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=zo(this.iteration,e,r),this}get names(){return Kn(super.names,this.iteration.names)}},Rm=class extends Hn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?ir.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Oc(super.names,this.from);return Oc(e,this.to)}},Ic=class extends Hn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=zo(this.iterable,e,r),this}get names(){return Kn(super.names,this.iterable.names)}},ti=class extends jr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ti.kind="func";var ri=class extends ei{render(e){return"return "+super.render(e)}};ri.kind="return";var Em=class extends jr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Kn(e,this.catch.names),this.finally&&Kn(e,this.finally.names),e}},ni=class extends jr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ni.kind="catch";var oi=class extends jr{render(e){return"finally"+super.render(e)}};oi.kind="finally";var Pm=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2351
|
-
`:""},this._extScope=e,this._scope=new ir.Scope({parent:e}),this._nodes=[new $m]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new wm(e,s,n)),s}const(e,r,n){return this._def(ir.varKinds.const,e,r,n)}let(e,r,n){return this._def(ir.varKinds.let,e,r,n)}var(e,r,n){return this._def(ir.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Cc(e,r,n))}add(e,r){return this._leafNode(new _m(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Se.nil&&this._leafNode(new Sm(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,Se.addCodeArg)(r,o));return r.push("}"),new Se._Code(r)}if(e,r,n){if(this._blockNode(new Vn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Vn(e))}else(){return this._elseNode(new Lo)}endIf(){return this._endBlockNode(Vn,Lo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Tm(e),r)}forRange(e,r,n,o,s=this.opts.es5?ir.varKinds.var:ir.varKinds.let){let i=this._scope.toName(e);return this._for(new Rm(s,i,r,n),()=>o(i))}forOf(e,r,n,o=ir.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof Se.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Se._)`${i}.length`,a=>{this.var(s,(0,Se._)`${i}[${a}]`),n(s)})}return this._for(new Ic("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?ir.varKinds.var:ir.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Se._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ic("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Hn)}label(e){return this._leafNode(new vm(e))}break(e){return this._leafNode(new km(e))}return(e){let r=new ri;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ri)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Em;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ni(s),r(s)}return n&&(this._currNode=o.finally=new oi,this.code(n)),this._endBlockNode(ni,oi)}throw(e){return this._leafNode(new xm(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Se.nil,n,o){return this._blockNode(new ti(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ti)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Vn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};fe.CodeGen=Pm;function Kn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Oc(t,e){return e instanceof Se._CodeOrName?Kn(t,e.names):t}function zo(t,e,r){if(t instanceof Se.Name)return n(t);if(!o(t))return t;return new Se._Code(t._items.reduce((s,i)=>(i instanceof Se.Name&&(i=n(i)),i instanceof Se._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof Se._Code&&s._items.some(i=>i instanceof Se.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function GL(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function gx(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Se._)`!${Am(t)}`}fe.not=gx;var JL=yx(fe.operators.AND);function YL(...t){return t.reduce(JL)}fe.and=YL;var XL=yx(fe.operators.OR);function QL(...t){return t.reduce(XL)}fe.or=QL;function yx(t){return(e,r)=>e===Se.nil?r:r===Se.nil?e:(0,Se._)`${Am(e)} ${t} ${Am(r)}`}function Am(t){return t instanceof Se.Name?t:(0,Se._)`(${t})`}});var $e=B(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.checkStrictMode=ge.getErrorPath=ge.Type=ge.useFunc=ge.setEvaluated=ge.evaluatedPropsToName=ge.mergeEvaluated=ge.eachItem=ge.unescapeJsonPointer=ge.escapeJsonPointer=ge.escapeFragment=ge.unescapeFragment=ge.schemaRefOrVal=ge.schemaHasRulesButRef=ge.schemaHasRules=ge.checkUnknownRules=ge.alwaysValidSchema=ge.toHash=void 0;var Ne=me(),ez=Qs();function tz(t){let e={};for(let r of t)e[r]=!0;return e}ge.toHash=tz;function rz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(_x(t,e),!vx(e,t.self.RULES.all))}ge.alwaysValidSchema=rz;function _x(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Sx(t,`unknown keyword: "${s}"`)}ge.checkUnknownRules=_x;function vx(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ge.schemaHasRules=vx;function nz(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ge.schemaHasRulesButRef=nz;function oz({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ne._)`${r}`}return(0,Ne._)`${t}${e}${(0,Ne.getProperty)(n)}`}ge.schemaRefOrVal=oz;function sz(t){return kx(decodeURIComponent(t))}ge.unescapeFragment=sz;function iz(t){return encodeURIComponent(Im(t))}ge.escapeFragment=iz;function Im(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ge.escapeJsonPointer=Im;function kx(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ge.unescapeJsonPointer=kx;function az(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ge.eachItem=az;function bx({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ne.Name?(s instanceof Ne.Name?t(o,s,i):e(o,s,i),i):s instanceof Ne.Name?(e(o,i,s),s):r(s,i);return a===Ne.Name&&!(c instanceof Ne.Name)?n(o,c):c}}ge.mergeEvaluated={props:bx({mergeNames:(t,e,r)=>t.if((0,Ne._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ne._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ne._)`${r} || {}`).code((0,Ne._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ne._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ne._)`${r} || {}`),Om(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:xx}),items:bx({mergeNames:(t,e,r)=>t.if((0,Ne._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ne._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ne._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ne._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function xx(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ne._)`{}`);return e!==void 0&&Om(t,r,e),r}ge.evaluatedPropsToName=xx;function Om(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ne._)`${e}${(0,Ne.getProperty)(n)}`,!0))}ge.setEvaluated=Om;var wx={};function cz(t,e){return t.scopeValue("func",{ref:e,code:wx[e.code]||(wx[e.code]=new ez._Code(e.code))})}ge.useFunc=cz;var Cm;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Cm||(ge.Type=Cm={}));function lz(t,e,r){if(t instanceof Ne.Name){let n=e===Cm.Num;return r?n?(0,Ne._)`"[" + ${t} + "]"`:(0,Ne._)`"['" + ${t} + "']"`:n?(0,Ne._)`"/" + ${t}`:(0,Ne._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ne.getProperty)(t).toString():"/"+Im(t)}ge.getErrorPath=lz;function Sx(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ge.checkStrictMode=Sx});var Dr=B(Nm=>{"use strict";Object.defineProperty(Nm,"__esModule",{value:!0});var mt=me(),uz={data:new mt.Name("data"),valCxt:new mt.Name("valCxt"),instancePath:new mt.Name("instancePath"),parentData:new mt.Name("parentData"),parentDataProperty:new mt.Name("parentDataProperty"),rootData:new mt.Name("rootData"),dynamicAnchors:new mt.Name("dynamicAnchors"),vErrors:new mt.Name("vErrors"),errors:new mt.Name("errors"),this:new mt.Name("this"),self:new mt.Name("self"),scope:new mt.Name("scope"),json:new mt.Name("json"),jsonPos:new mt.Name("jsonPos"),jsonLen:new mt.Name("jsonLen"),jsonPart:new mt.Name("jsonPart")};Nm.default=uz});var si=B(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.extendErrors=ft.resetErrorsCount=ft.reportExtraError=ft.reportError=ft.keyword$DataError=ft.keywordError=void 0;var Te=me(),Lc=$e(),_t=Dr();ft.keywordError={message:({keyword:t})=>(0,Te.str)`must pass "${t}" keyword validation`};ft.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Te.str)`"${t}" keyword must be ${e} ($data)`:(0,Te.str)`"${t}" keyword is invalid ($data)`};function dz(t,e=ft.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Rx(t,e,r);n??(i||a)?$x(s,c):Tx(o,(0,Te._)`[${c}]`)}ft.reportError=dz;function pz(t,e=ft.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Rx(t,e,r);$x(o,a),s||i||Tx(n,_t.default.vErrors)}ft.reportExtraError=pz;function hz(t,e){t.assign(_t.default.errors,e),t.if((0,Te._)`${_t.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Te._)`${_t.default.vErrors}.length`,e),()=>t.assign(_t.default.vErrors,null)))}ft.resetErrorsCount=hz;function mz({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,_t.default.errors,a=>{t.const(i,(0,Te._)`${_t.default.vErrors}[${a}]`),t.if((0,Te._)`${i}.instancePath === undefined`,()=>t.assign((0,Te._)`${i}.instancePath`,(0,Te.strConcat)(_t.default.instancePath,s.errorPath))),t.assign((0,Te._)`${i}.schemaPath`,(0,Te.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Te._)`${i}.schema`,r),t.assign((0,Te._)`${i}.data`,n))})}ft.extendErrors=mz;function $x(t,e){let r=t.const("err",e);t.if((0,Te._)`${_t.default.vErrors} === null`,()=>t.assign(_t.default.vErrors,(0,Te._)`[${r}]`),(0,Te._)`${_t.default.vErrors}.push(${r})`),t.code((0,Te._)`${_t.default.errors}++`)}function Tx(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Te._)`new ${t.ValidationError}(${e})`):(r.assign((0,Te._)`${n}.errors`,e),r.return(!1))}var Wn={keyword:new Te.Name("keyword"),schemaPath:new Te.Name("schemaPath"),params:new Te.Name("params"),propertyName:new Te.Name("propertyName"),message:new Te.Name("message"),schema:new Te.Name("schema"),parentSchema:new Te.Name("parentSchema")};function Rx(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Te._)`{}`:fz(t,e,r)}function fz(t,e,r={}){let{gen:n,it:o}=t,s=[gz(o,r),yz(t,r)];return bz(t,e,s),n.object(...s)}function gz({errorPath:t},{instancePath:e}){let r=e?(0,Te.str)`${t}${(0,Lc.getErrorPath)(e,Lc.Type.Str)}`:t;return[_t.default.instancePath,(0,Te.strConcat)(_t.default.instancePath,r)]}function yz({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Te.str)`${e}/${t}`;return r&&(o=(0,Te.str)`${o}${(0,Lc.getErrorPath)(r,Lc.Type.Str)}`),[Wn.schemaPath,o]}function bz(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;n.push([Wn.keyword,o],[Wn.params,typeof e=="function"?e(t):e||(0,Te._)`{}`]),c.messages&&n.push([Wn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Wn.schema,i],[Wn.parentSchema,(0,Te._)`${u}${p}`],[_t.default.data,s]),l&&n.push([Wn.propertyName,l])}});var Px=B(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.boolOrEmptySchema=jo.topBoolOrEmptySchema=void 0;var wz=si(),_z=me(),vz=Dr(),kz={message:"boolean schema is false"};function xz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ex(t,!1):typeof r=="object"&&r.$async===!0?e.return(vz.default.data):(e.assign((0,_z._)`${n}.errors`,null),e.return(!0))}jo.topBoolOrEmptySchema=xz;function Sz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ex(t)):r.var(e,!0)}jo.boolOrEmptySchema=Sz;function Ex(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,wz.reportError)(o,kz,void 0,e)}});var Lm=B(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.getRules=Do.isJSONType=void 0;var $z=["string","number","integer","boolean","null","object","array"],Tz=new Set($z);function Rz(t){return typeof t=="string"&&Tz.has(t)}Do.isJSONType=Rz;function Ez(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Do.getRules=Ez});var zm=B(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.shouldUseRule=sn.shouldUseGroup=sn.schemaHasRulesForType=void 0;function Pz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Ax(t,n)}sn.schemaHasRulesForType=Pz;function Ax(t,e){return e.rules.some(r=>Cx(t,r))}sn.shouldUseGroup=Ax;function Cx(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}sn.shouldUseRule=Cx});var ii=B(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.reportTypeError=gt.checkDataTypes=gt.checkDataType=gt.coerceAndCheckDataType=gt.getJSONTypes=gt.getSchemaTypes=gt.DataType=void 0;var Az=Lm(),Cz=zm(),Iz=si(),pe=me(),Ix=$e(),Mo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Mo||(gt.DataType=Mo={}));function Oz(t){let e=Ox(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}gt.getSchemaTypes=Oz;function Ox(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Az.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}gt.getJSONTypes=Ox;function Nz(t,e){let{gen:r,data:n,opts:o}=t,s=Lz(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Cz.schemaHasRulesForType)(t,e[0]));if(i){let a=Dm(e,n,o.strictNumbers,Mo.Wrong);r.if(a,()=>{s.length?zz(t,e,s):Mm(t)})}return i}gt.coerceAndCheckDataType=Nz;var Nx=new Set(["string","number","integer","boolean","null"]);function Lz(t,e){return e?t.filter(r=>Nx.has(r)||e==="array"&&r==="array"):[]}function zz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,pe._)`typeof ${o}`),a=n.let("coerced",(0,pe._)`undefined`);s.coerceTypes==="array"&&n.if((0,pe._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,pe._)`${o}[0]`).assign(i,(0,pe._)`typeof ${o}`).if(Dm(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,pe._)`${a} !== undefined`);for(let l of r)(Nx.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Mm(t),n.endIf(),n.if((0,pe._)`${a} !== undefined`,()=>{n.assign(o,a),jz(t,a)});function c(l){switch(l){case"string":n.elseIf((0,pe._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,pe._)`"" + ${o}`).elseIf((0,pe._)`${o} === null`).assign(a,(0,pe._)`""`);return;case"number":n.elseIf((0,pe._)`${i} == "boolean" || ${o} === null
|
|
2350
|
+
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Vh,or,ML,Sc=N(()=>{nn();or={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Vh===void 0&&(Vh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Vh),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};ML=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function $c(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??He(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=xc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=vc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Tc=N(()=>{Ts();et();Sc();kc();Ht()});function Gk(t,e){if(e.mapStrategy==="record")return $c(t,e);let r=ce(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||He(e),n=ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||He(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Kh=N(()=>{et();Tc();Ht()});function Jk(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Wh=N(()=>{});function Yk(t){return t.target==="openAi"?void 0:{not:He({...t,currentPath:[...t.currentPath,"not"]})}}var Gh=N(()=>{Ht()});function Xk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Jh=N(()=>{});function ex(t,e){if(e.target==="openApi3")return Qk(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Xs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Xs[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Qk(t,e)}var Xs,Qk,Rc=N(()=>{et();Xs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Qk=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ce(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function tx(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Xs[t.innerType._def.typeName],nullable:!0}:{type:[Xs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ce(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ce(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Yh=N(()=>{et();Rc()});function rx(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Oh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var Xh=N(()=>{nn()});function nx(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let l=FL(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ce(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||o.push(a))}o.length&&(n.required=o);let i=qL(t,e);return i!==void 0&&(n.additionalProperties=i),n}function qL(t,e){if(t.catchall._def.typeName!=="ZodNever")return ce(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function FL(t){try{return t.isOptional()}catch{return!0}}var Qh=N(()=>{et()});var ox,em=N(()=>{et();Ht();ox=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ce(t.innerType._def,e);let r=ce(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:He(e)},r]}:He(e)}});var sx,tm=N(()=>{et();sx=(t,e)=>{if(e.pipeStrategy==="input")return ce(t.in._def,e);if(e.pipeStrategy==="output")return ce(t.out._def,e);let r=ce(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ce(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function ix(t,e){return ce(t.type._def,e)}var rm=N(()=>{et()});function ax(t,e){let n={type:"array",uniqueItems:!0,items:ce(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var nm=N(()=>{nn();et()});function cx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ce(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ce(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ce(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var om=N(()=>{et()});function lx(t){return{not:He(t)}}var sm=N(()=>{Ht()});function ux(t){return He(t)}var im=N(()=>{Ht()});var dx,am=N(()=>{et();dx=(t,e)=>ce(t.innerType._def,e)});var px,cm=N(()=>{Ts();Ht();Nh();Lh();jh();kc();zh();Mh();Uh();qh();Fh();Bh();Zh();Kh();Wh();Gh();Jh();Yh();Xh();Qh();em();tm();rm();Tc();nm();Sc();om();sm();Rc();im();am();px=(t,e,r)=>{switch(e){case D.ZodString:return xc(t,r);case D.ZodNumber:return rx(t,r);case D.ZodObject:return nx(t,r);case D.ZodBigInt:return Uk(t,r);case D.ZodBoolean:return qk();case D.ZodDate:return Dh(t,r);case D.ZodUndefined:return lx(r);case D.ZodNull:return Xk(r);case D.ZodArray:return Mk(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return ex(t,r);case D.ZodIntersection:return Hk(t,r);case D.ZodTuple:return cx(t,r);case D.ZodRecord:return $c(t,r);case D.ZodLiteral:return Kk(t,r);case D.ZodEnum:return Vk(t);case D.ZodNativeEnum:return Jk(t);case D.ZodNullable:return tx(t,r);case D.ZodOptional:return ox(t,r);case D.ZodMap:return Gk(t,r);case D.ZodSet:return ax(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return ix(t,r);case D.ZodNaN:case D.ZodNever:return Yk(r);case D.ZodEffects:return Zk(t,r);case D.ZodAny:return He(r);case D.ZodUnknown:return ux(r);case D.ZodDefault:return Bk(t,r);case D.ZodBranded:return vc(t,r);case D.ZodReadonly:return dx(t,r);case D.ZodCatch:return Fk(t,r);case D.ZodPipeline:return sx(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function ce(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==jk)return a}if(n&&!r){let a=BL(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=px(t,t.typeName,e),i=typeof s=="function"?ce(s(),e):s;if(i&&ZL(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var BL,ZL,et=N(()=>{bc();cm();_c();Ht();BL=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:wc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),He(e)):e.$refStrategy==="seen"?He(e):void 0}},ZL=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var hx=N(()=>{});var lm,um=N(()=>{et();Ih();Ht();lm=(t,e)=>{let r=Dk(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ce(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??He(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ce(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??He(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var mx=N(()=>{bc();Ih();nn();_c();et();hx();Ht();Nh();Lh();jh();kc();zh();Mh();Uh();qh();Fh();Bh();Zh();Kh();Wh();Gh();Jh();Yh();Xh();Qh();em();tm();rm();am();Tc();nm();Sc();om();sm();Rc();im();cm();um();um()});function VL(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function dm(t,e){return _r(t)?Xp(t,{target:VL(e?.target),io:e?.pipeStrategy??"input"}):lm(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function pm(t){let r=en(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ao(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function hm(t,e){let r=Qr(t,e);if(!r.success)throw r.error;return r.data}var mm=N(()=>{th();Ms();mx()});function fx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gx(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];fx(i)&&fx(s)?r[o]={...i,...s}:r[o]=s}return r}var HL,Ec,yx=N(()=>{Ms();jo();Nk();mm();HL=6e4,Ec=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(tc,r=>{this._oncancel(r)}),this.setNotificationHandler(nc,r=>{this._onprogress(r)}),this.setRequestHandler(rc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(oc,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Y(te.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ic,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let p=c,b=new Y(p.error.code,p.error.message,p.error.data);u(b)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new Y(te.InvalidParams,`Task not found: ${s}`);if(!rn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(rn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[tn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ac,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new Y(te.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(lc,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Y(te.InvalidParams,`Task not found: ${r.params.taskId}`);if(rn(o.status))throw new Y(te.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Y(te.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Y?o:new Y(te.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Y.fromError(te.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Bs(s)||xk(s)?this._onresponse(s):bh(s)?this._onrequest(s,i):kk(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=Y.fromError(te.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[tn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:te.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=wk(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,b)=>{if(i.signal.aborted)throw new Y(te.ConnectionClosed,"Request was cancelled");let f={...b,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,p,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:te.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Bs(e))n(e);else{let i=new Y(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Bs(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Bs(e))o(e);else{let i=Y.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof Y?i:new Y(te.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Io,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Y(te.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},rn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new Y(te.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Y(te.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Y?i:new Y(te.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=A=>{u(A)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(A){p(A);return}n?.signal?.throwIfAborted();let b=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:b}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[tn]:c}});let m=A=>{this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(A)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(F=>this._onerror(new Error(`Failed to send cancellation: ${F}`)));let L=A instanceof Y?A:new Y(te.RequestTimeout,String(A));u(L)};this._responseHandlers.set(b,A=>{if(!n?.signal?.aborted){if(A instanceof Error)return u(A);try{let L=Qr(r,A.result);L.success?l(L.data):u(L.error)}catch(L){u(L)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let w=n?.timeout??HL,$=()=>m(Y.fromError(te.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(b,w,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let R=c?.taskId;if(R){let A=L=>{let F=this._responseHandlers.get(b);F?F(L):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,A),this._enqueueTaskMessage(R,{type:"request",message:f,timestamp:Date.now()}).catch(L=>{this._cleanupTimeout(b),u(L)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(A=>{this._cleanupTimeout(b),u(A)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},sc,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},cc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Tk,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[tn]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[tn]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[tn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=pm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=hm(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=pm(e);this._notificationHandlers.set(n,o=>{let s=hm(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&bh(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Y(te.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new Y(te.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new Y(te.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new Y(te.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Ws.parse({method:"notifications/tasks/status",params:a});await this.notification(c),rn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new Y(te.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(rn(a.status))throw new Y(te.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=Ws.parse({method:"notifications/tasks/status",params:c});await this.notification(l),rn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ti=B(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.regexpCode=Re.getEsmExportName=Re.getProperty=Re.safeStringify=Re.stringify=Re.strConcat=Re.addCodeArg=Re.str=Re._=Re.nil=Re._Code=Re.Name=Re.IDENTIFIER=Re._CodeOrName=void 0;var Qs=class{};Re._CodeOrName=Qs;Re.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Zn=class extends Qs{constructor(e){if(super(),!Re.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Re.Name=Zn;var Kt=class extends Qs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Zn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Re._Code=Kt;Re.nil=new Kt("");function bx(t,...e){let r=[t[0]],n=0;for(;n<e.length;)gm(r,e[n]),r.push(t[++n]);return new Kt(r)}Re._=bx;var fm=new Kt("+");function wx(t,...e){let r=[ei(t[0])],n=0;for(;n<e.length;)r.push(fm),gm(r,e[n]),r.push(fm,ei(t[++n]));return KL(r),new Kt(r)}Re.str=wx;function gm(t,e){e instanceof Kt?t.push(...e._items):e instanceof Zn?t.push(e):t.push(JL(e))}Re.addCodeArg=gm;function KL(t){let e=1;for(;e<t.length-1;){if(t[e]===fm){let r=WL(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function WL(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Zn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Zn))return`"${t}${e.slice(1)}`}function GL(t,e){return e.emptyStr()?t:t.emptyStr()?e:wx`${t}${e}`}Re.strConcat=GL;function JL(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ei(Array.isArray(t)?t.join(","):t)}function YL(t){return new Kt(ei(t))}Re.stringify=YL;function ei(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Re.safeStringify=ei;function XL(t){return typeof t=="string"&&Re.IDENTIFIER.test(t)?new Kt(`.${t}`):bx`[${t}]`}Re.getProperty=XL;function QL(t){if(typeof t=="string"&&Re.IDENTIFIER.test(t))return new Kt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Re.getEsmExportName=QL;function ej(t){return new Kt(t.toString())}Re.regexpCode=ej});var wm=B(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.ValueScope=At.ValueScopeName=At.Scope=At.varKinds=At.UsedValueState=void 0;var Pt=ti(),ym=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Pc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Pc||(At.UsedValueState=Pc={}));At.varKinds={const:new Pt.Name("const"),let:new Pt.Name("let"),var:new Pt.Name("var")};var Ac=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Pt.Name?e:this.name(e)}name(e){return new Pt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};At.Scope=Ac;var Cc=class extends Pt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Pt._)`.${new Pt.Name(r)}[${n}]`}};At.ValueScopeName=Cc;var tj=(0,Pt._)`\n`,bm=class extends Ac{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?tj:Pt.nil}}get(){return this._scope}name(e){return new Cc(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Pt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Pt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Pc.Started);let u=r(l);if(u){let p=this.opts.es5?At.varKinds.var:At.varKinds.const;s=(0,Pt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Pt._)`${s}${u}${this.opts._n}`;else throw new ym(l);c.set(l,Pc.Completed)})}return s}};At.ValueScope=bm});var me=B(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var Se=ti(),ir=wm(),on=ti();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return on._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return on.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return on.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return on.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return on.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return on.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return on.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return on.Name}});var Lc=wm();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return Lc.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return Lc.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return Lc.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return Lc.varKinds}});fe.operators={GT:new Se._Code(">"),GTE:new Se._Code(">="),LT:new Se._Code("<"),LTE:new Se._Code("<="),EQ:new Se._Code("==="),NEQ:new Se._Code("!=="),NOT:new Se._Code("!"),OR:new Se._Code("||"),AND:new Se._Code("&&"),ADD:new Se._Code("+")};var jr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},_m=class extends jr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ir.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Do(this.rhs,e,r)),this}get names(){return this.rhs instanceof Se._CodeOrName?this.rhs.names:{}}},Ic=class extends jr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Se.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Do(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Se.Name?{}:{...this.lhs.names};return Nc(e,this.rhs)}},vm=class extends Ic{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},km=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},xm=class extends jr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Sm=class extends jr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},$m=class extends jr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Do(this.code,e,r),this}get names(){return this.code instanceof Se._CodeOrName?this.code.names:{}}},ri=class extends jr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(rj(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Kn(e,r.names),{})}},zr=class extends ri{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Tm=class extends ri{},zo=class extends zr{};zo.kind="else";var Vn=class t extends zr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new zo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(_x(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Do(this.condition,e,r),this}get names(){let e=super.names;return Nc(e,this.condition),this.else&&Kn(e,this.else.names),e}};Vn.kind="if";var Hn=class extends zr{};Hn.kind="for";var Rm=class extends Hn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Do(this.iteration,e,r),this}get names(){return Kn(super.names,this.iteration.names)}},Em=class extends Hn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?ir.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Nc(super.names,this.from);return Nc(e,this.to)}},Oc=class extends Hn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Do(this.iterable,e,r),this}get names(){return Kn(super.names,this.iterable.names)}},ni=class extends zr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ni.kind="func";var oi=class extends ri{render(e){return"return "+super.render(e)}};oi.kind="return";var Pm=class extends zr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Kn(e,this.catch.names),this.finally&&Kn(e,this.finally.names),e}},si=class extends zr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};si.kind="catch";var ii=class extends zr{render(e){return"finally"+super.render(e)}};ii.kind="finally";var Am=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2351
|
+
`:""},this._extScope=e,this._scope=new ir.Scope({parent:e}),this._nodes=[new Tm]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new _m(e,s,n)),s}const(e,r,n){return this._def(ir.varKinds.const,e,r,n)}let(e,r,n){return this._def(ir.varKinds.let,e,r,n)}var(e,r,n){return this._def(ir.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ic(e,r,n))}add(e,r){return this._leafNode(new vm(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Se.nil&&this._leafNode(new $m(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,Se.addCodeArg)(r,o));return r.push("}"),new Se._Code(r)}if(e,r,n){if(this._blockNode(new Vn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Vn(e))}else(){return this._elseNode(new zo)}endIf(){return this._endBlockNode(Vn,zo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Rm(e),r)}forRange(e,r,n,o,s=this.opts.es5?ir.varKinds.var:ir.varKinds.let){let i=this._scope.toName(e);return this._for(new Em(s,i,r,n),()=>o(i))}forOf(e,r,n,o=ir.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof Se.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Se._)`${i}.length`,a=>{this.var(s,(0,Se._)`${i}[${a}]`),n(s)})}return this._for(new Oc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?ir.varKinds.var:ir.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Se._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Oc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Hn)}label(e){return this._leafNode(new km(e))}break(e){return this._leafNode(new xm(e))}return(e){let r=new oi;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(oi)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Pm;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new si(s),r(s)}return n&&(this._currNode=o.finally=new ii,this.code(n)),this._endBlockNode(si,ii)}throw(e){return this._leafNode(new Sm(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Se.nil,n,o){return this._blockNode(new ni(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ni)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Vn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};fe.CodeGen=Am;function Kn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Nc(t,e){return e instanceof Se._CodeOrName?Kn(t,e.names):t}function Do(t,e,r){if(t instanceof Se.Name)return n(t);if(!o(t))return t;return new Se._Code(t._items.reduce((s,i)=>(i instanceof Se.Name&&(i=n(i)),i instanceof Se._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof Se._Code&&s._items.some(i=>i instanceof Se.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function rj(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function _x(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Se._)`!${Cm(t)}`}fe.not=_x;var nj=vx(fe.operators.AND);function oj(...t){return t.reduce(nj)}fe.and=oj;var sj=vx(fe.operators.OR);function ij(...t){return t.reduce(sj)}fe.or=ij;function vx(t){return(e,r)=>e===Se.nil?r:r===Se.nil?e:(0,Se._)`${Cm(e)} ${t} ${Cm(r)}`}function Cm(t){return t instanceof Se.Name?t:(0,Se._)`(${t})`}});var $e=B(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.checkStrictMode=ye.getErrorPath=ye.Type=ye.useFunc=ye.setEvaluated=ye.evaluatedPropsToName=ye.mergeEvaluated=ye.eachItem=ye.unescapeJsonPointer=ye.escapeJsonPointer=ye.escapeFragment=ye.unescapeFragment=ye.schemaRefOrVal=ye.schemaHasRulesButRef=ye.schemaHasRules=ye.checkUnknownRules=ye.alwaysValidSchema=ye.toHash=void 0;var Ne=me(),aj=ti();function cj(t){let e={};for(let r of t)e[r]=!0;return e}ye.toHash=cj;function lj(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Sx(t,e),!$x(e,t.self.RULES.all))}ye.alwaysValidSchema=lj;function Sx(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Ex(t,`unknown keyword: "${s}"`)}ye.checkUnknownRules=Sx;function $x(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ye.schemaHasRules=$x;function uj(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ye.schemaHasRulesButRef=uj;function dj({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ne._)`${r}`}return(0,Ne._)`${t}${e}${(0,Ne.getProperty)(n)}`}ye.schemaRefOrVal=dj;function pj(t){return Tx(decodeURIComponent(t))}ye.unescapeFragment=pj;function hj(t){return encodeURIComponent(Om(t))}ye.escapeFragment=hj;function Om(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ye.escapeJsonPointer=Om;function Tx(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ye.unescapeJsonPointer=Tx;function mj(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ye.eachItem=mj;function kx({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ne.Name?(s instanceof Ne.Name?t(o,s,i):e(o,s,i),i):s instanceof Ne.Name?(e(o,i,s),s):r(s,i);return a===Ne.Name&&!(c instanceof Ne.Name)?n(o,c):c}}ye.mergeEvaluated={props:kx({mergeNames:(t,e,r)=>t.if((0,Ne._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ne._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ne._)`${r} || {}`).code((0,Ne._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ne._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ne._)`${r} || {}`),Nm(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Rx}),items:kx({mergeNames:(t,e,r)=>t.if((0,Ne._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ne._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ne._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ne._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Rx(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ne._)`{}`);return e!==void 0&&Nm(t,r,e),r}ye.evaluatedPropsToName=Rx;function Nm(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ne._)`${e}${(0,Ne.getProperty)(n)}`,!0))}ye.setEvaluated=Nm;var xx={};function fj(t,e){return t.scopeValue("func",{ref:e,code:xx[e.code]||(xx[e.code]=new aj._Code(e.code))})}ye.useFunc=fj;var Im;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Im||(ye.Type=Im={}));function gj(t,e,r){if(t instanceof Ne.Name){let n=e===Im.Num;return r?n?(0,Ne._)`"[" + ${t} + "]"`:(0,Ne._)`"['" + ${t} + "']"`:n?(0,Ne._)`"/" + ${t}`:(0,Ne._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ne.getProperty)(t).toString():"/"+Om(t)}ye.getErrorPath=gj;function Ex(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ye.checkStrictMode=Ex});var Dr=B(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});var mt=me(),yj={data:new mt.Name("data"),valCxt:new mt.Name("valCxt"),instancePath:new mt.Name("instancePath"),parentData:new mt.Name("parentData"),parentDataProperty:new mt.Name("parentDataProperty"),rootData:new mt.Name("rootData"),dynamicAnchors:new mt.Name("dynamicAnchors"),vErrors:new mt.Name("vErrors"),errors:new mt.Name("errors"),this:new mt.Name("this"),self:new mt.Name("self"),scope:new mt.Name("scope"),json:new mt.Name("json"),jsonPos:new mt.Name("jsonPos"),jsonLen:new mt.Name("jsonLen"),jsonPart:new mt.Name("jsonPart")};Lm.default=yj});var ai=B(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.extendErrors=ft.resetErrorsCount=ft.reportExtraError=ft.reportError=ft.keyword$DataError=ft.keywordError=void 0;var Te=me(),jc=$e(),_t=Dr();ft.keywordError={message:({keyword:t})=>(0,Te.str)`must pass "${t}" keyword validation`};ft.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Te.str)`"${t}" keyword must be ${e} ($data)`:(0,Te.str)`"${t}" keyword is invalid ($data)`};function bj(t,e=ft.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Cx(t,e,r);n??(i||a)?Px(s,c):Ax(o,(0,Te._)`[${c}]`)}ft.reportError=bj;function wj(t,e=ft.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Cx(t,e,r);Px(o,a),s||i||Ax(n,_t.default.vErrors)}ft.reportExtraError=wj;function _j(t,e){t.assign(_t.default.errors,e),t.if((0,Te._)`${_t.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Te._)`${_t.default.vErrors}.length`,e),()=>t.assign(_t.default.vErrors,null)))}ft.resetErrorsCount=_j;function vj({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,_t.default.errors,a=>{t.const(i,(0,Te._)`${_t.default.vErrors}[${a}]`),t.if((0,Te._)`${i}.instancePath === undefined`,()=>t.assign((0,Te._)`${i}.instancePath`,(0,Te.strConcat)(_t.default.instancePath,s.errorPath))),t.assign((0,Te._)`${i}.schemaPath`,(0,Te.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Te._)`${i}.schema`,r),t.assign((0,Te._)`${i}.data`,n))})}ft.extendErrors=vj;function Px(t,e){let r=t.const("err",e);t.if((0,Te._)`${_t.default.vErrors} === null`,()=>t.assign(_t.default.vErrors,(0,Te._)`[${r}]`),(0,Te._)`${_t.default.vErrors}.push(${r})`),t.code((0,Te._)`${_t.default.errors}++`)}function Ax(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Te._)`new ${t.ValidationError}(${e})`):(r.assign((0,Te._)`${n}.errors`,e),r.return(!1))}var Wn={keyword:new Te.Name("keyword"),schemaPath:new Te.Name("schemaPath"),params:new Te.Name("params"),propertyName:new Te.Name("propertyName"),message:new Te.Name("message"),schema:new Te.Name("schema"),parentSchema:new Te.Name("parentSchema")};function Cx(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Te._)`{}`:kj(t,e,r)}function kj(t,e,r={}){let{gen:n,it:o}=t,s=[xj(o,r),Sj(t,r)];return $j(t,e,s),n.object(...s)}function xj({errorPath:t},{instancePath:e}){let r=e?(0,Te.str)`${t}${(0,jc.getErrorPath)(e,jc.Type.Str)}`:t;return[_t.default.instancePath,(0,Te.strConcat)(_t.default.instancePath,r)]}function Sj({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Te.str)`${e}/${t}`;return r&&(o=(0,Te.str)`${o}${(0,jc.getErrorPath)(r,jc.Type.Str)}`),[Wn.schemaPath,o]}function $j(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;n.push([Wn.keyword,o],[Wn.params,typeof e=="function"?e(t):e||(0,Te._)`{}`]),c.messages&&n.push([Wn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Wn.schema,i],[Wn.parentSchema,(0,Te._)`${u}${p}`],[_t.default.data,s]),l&&n.push([Wn.propertyName,l])}});var Ox=B(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.boolOrEmptySchema=Mo.topBoolOrEmptySchema=void 0;var Tj=ai(),Rj=me(),Ej=Dr(),Pj={message:"boolean schema is false"};function Aj(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ix(t,!1):typeof r=="object"&&r.$async===!0?e.return(Ej.default.data):(e.assign((0,Rj._)`${n}.errors`,null),e.return(!0))}Mo.topBoolOrEmptySchema=Aj;function Cj(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ix(t)):r.var(e,!0)}Mo.boolOrEmptySchema=Cj;function Ix(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Tj.reportError)(o,Pj,void 0,e)}});var jm=B(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.getRules=Uo.isJSONType=void 0;var Ij=["string","number","integer","boolean","null","object","array"],Oj=new Set(Ij);function Nj(t){return typeof t=="string"&&Oj.has(t)}Uo.isJSONType=Nj;function Lj(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Uo.getRules=Lj});var zm=B(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.shouldUseRule=sn.shouldUseGroup=sn.schemaHasRulesForType=void 0;function jj({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Nx(t,n)}sn.schemaHasRulesForType=jj;function Nx(t,e){return e.rules.some(r=>Lx(t,r))}sn.shouldUseGroup=Nx;function Lx(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}sn.shouldUseRule=Lx});var ci=B(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.reportTypeError=gt.checkDataTypes=gt.checkDataType=gt.coerceAndCheckDataType=gt.getJSONTypes=gt.getSchemaTypes=gt.DataType=void 0;var zj=jm(),Dj=zm(),Mj=ai(),pe=me(),jx=$e(),qo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(qo||(gt.DataType=qo={}));function Uj(t){let e=zx(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}gt.getSchemaTypes=Uj;function zx(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(zj.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}gt.getJSONTypes=zx;function qj(t,e){let{gen:r,data:n,opts:o}=t,s=Fj(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Dj.schemaHasRulesForType)(t,e[0]));if(i){let a=Mm(e,n,o.strictNumbers,qo.Wrong);r.if(a,()=>{s.length?Bj(t,e,s):Um(t)})}return i}gt.coerceAndCheckDataType=qj;var Dx=new Set(["string","number","integer","boolean","null"]);function Fj(t,e){return e?t.filter(r=>Dx.has(r)||e==="array"&&r==="array"):[]}function Bj(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,pe._)`typeof ${o}`),a=n.let("coerced",(0,pe._)`undefined`);s.coerceTypes==="array"&&n.if((0,pe._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,pe._)`${o}[0]`).assign(i,(0,pe._)`typeof ${o}`).if(Mm(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,pe._)`${a} !== undefined`);for(let l of r)(Dx.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Um(t),n.endIf(),n.if((0,pe._)`${a} !== undefined`,()=>{n.assign(o,a),Zj(t,a)});function c(l){switch(l){case"string":n.elseIf((0,pe._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,pe._)`"" + ${o}`).elseIf((0,pe._)`${o} === null`).assign(a,(0,pe._)`""`);return;case"number":n.elseIf((0,pe._)`${i} == "boolean" || ${o} === null
|
|
2352
2352
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,pe._)`+${o}`);return;case"integer":n.elseIf((0,pe._)`${i} === "boolean" || ${o} === null
|
|
2353
2353
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,pe._)`+${o}`);return;case"boolean":n.elseIf((0,pe._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,pe._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,pe._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,pe._)`${i} === "string" || ${i} === "number"
|
|
2354
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,pe._)`[${o}]`)}}}function jz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,pe._)`${e} !== undefined`,()=>t.assign((0,pe._)`${e}[${r}]`,n))}function jm(t,e,r,n=Mo.Correct){let o=n===Mo.Correct?pe.operators.EQ:pe.operators.NEQ,s;switch(t){case"null":return(0,pe._)`${e} ${o} null`;case"array":s=(0,pe._)`Array.isArray(${e})`;break;case"object":s=(0,pe._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,pe._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,pe._)`typeof ${e} ${o} ${t}`}return n===Mo.Correct?s:(0,pe.not)(s);function i(a=pe.nil){return(0,pe.and)((0,pe._)`typeof ${e} == "number"`,a,r?(0,pe._)`isFinite(${e})`:pe.nil)}}gt.checkDataType=jm;function Dm(t,e,r,n){if(t.length===1)return jm(t[0],e,r,n);let o,s=(0,Ix.toHash)(t);if(s.array&&s.object){let i=(0,pe._)`typeof ${e} != "object"`;o=s.null?i:(0,pe._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=pe.nil;s.number&&delete s.integer;for(let i in s)o=(0,pe.and)(o,jm(i,e,r,n));return o}gt.checkDataTypes=Dm;var Dz={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,pe._)`{type: ${t}}`:(0,pe._)`{type: ${e}}`};function Mm(t){let e=Mz(t);(0,Iz.reportError)(e,Dz)}gt.reportTypeError=Mm;function Mz(t){let{gen:e,data:r,schema:n}=t,o=(0,Ix.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var zx=B(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.assignDefaults=void 0;var Uo=me(),Uz=$e();function qz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Lx(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Lx(t,s,o.default))}zc.assignDefaults=qz;function Lx(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Uo._)`${s}${(0,Uo.getProperty)(e)}`;if(o){(0,Uz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Uo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Uo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Uo._)`${a} = ${(0,Uo.stringify)(r)}`)}});var Wt=B(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.validateUnion=Oe.validateArray=Oe.usePattern=Oe.callValidateCode=Oe.schemaProperties=Oe.allSchemaProperties=Oe.noPropertyInData=Oe.propertyInData=Oe.isOwnProperty=Oe.hasPropFunc=Oe.reportMissingProp=Oe.checkMissingProp=Oe.checkReportMissingProp=void 0;var Ue=me(),Um=$e(),an=Dr(),Fz=$e();function Bz(t,e){let{gen:r,data:n,it:o}=t;r.if(Fm(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ue._)`${e}`},!0),t.error()})}Oe.checkReportMissingProp=Bz;function Zz({gen:t,data:e,it:{opts:r}},n,o){return(0,Ue.or)(...n.map(s=>(0,Ue.and)(Fm(t,e,s,r.ownProperties),(0,Ue._)`${o} = ${s}`)))}Oe.checkMissingProp=Zz;function Vz(t,e){t.setParams({missingProperty:e},!0),t.error()}Oe.reportMissingProp=Vz;function jx(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ue._)`Object.prototype.hasOwnProperty`})}Oe.hasPropFunc=jx;function qm(t,e,r){return(0,Ue._)`${jx(t)}.call(${e}, ${r})`}Oe.isOwnProperty=qm;function Hz(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} !== undefined`;return n?(0,Ue._)`${o} && ${qm(t,e,r)}`:o}Oe.propertyInData=Hz;function Fm(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} === undefined`;return n?(0,Ue.or)(o,(0,Ue.not)(qm(t,e,r))):o}Oe.noPropertyInData=Fm;function Dx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Oe.allSchemaProperties=Dx;function Kz(t,e){return Dx(e).filter(r=>!(0,Um.alwaysValidSchema)(t,e[r]))}Oe.schemaProperties=Kz;function Wz({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Ue._)`${t}, ${e}, ${n}${o}`:e,p=[[an.default.instancePath,(0,Ue.strConcat)(an.default.instancePath,s)],[an.default.parentData,i.parentData],[an.default.parentDataProperty,i.parentDataProperty],[an.default.rootData,an.default.rootData]];i.opts.dynamicRef&&p.push([an.default.dynamicAnchors,an.default.dynamicAnchors]);let b=(0,Ue._)`${u}, ${r.object(...p)}`;return c!==Ue.nil?(0,Ue._)`${a}.call(${c}, ${b})`:(0,Ue._)`${a}(${b})`}Oe.callValidateCode=Wz;var Gz=(0,Ue._)`new RegExp`;function Jz({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ue._)`${o.code==="new RegExp"?Gz:(0,Fz.useFunc)(t,o)}(${r}, ${n})`})}Oe.usePattern=Jz;function Yz(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Ue._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:Um.Type.Num},s),e.if((0,Ue.not)(s),a)})}}Oe.validateArray=Yz;function Xz(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Um.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,Ue._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Ue.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Oe.validateUnion=Xz});var qx=B(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.validateKeywordUsage=vr.validSchemaType=vr.funcKeywordCode=vr.macroKeywordCode=void 0;var vt=me(),Gn=Dr(),Qz=Wt(),ej=si();function tj(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Ux(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:vt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}vr.macroKeywordCode=tj;function rj(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;oj(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Ux(n,o,l),p=n.let("valid");t.block$data(p,b),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function b(){if(e.errors===!1)w(),e.modifying&&Mx(t),S(()=>t.error());else{let R=e.async?f():h();e.modifying&&Mx(t),S(()=>nj(t,R))}}function f(){let R=n.let("ruleErrs",null);return n.try(()=>w((0,vt._)`await `),A=>n.assign(p,!1).if((0,vt._)`${A} instanceof ${c.ValidationError}`,()=>n.assign(R,(0,vt._)`${A}.errors`),()=>n.throw(A))),R}function h(){let R=(0,vt._)`${u}.errors`;return n.assign(R,null),w(vt.nil),R}function w(R=e.async?(0,vt._)`await `:vt.nil){let A=c.opts.passContext?Gn.default.this:Gn.default.self,L=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,vt._)`${R}${(0,Qz.callValidateCode)(t,u,A,L)}`,e.modifying)}function S(R){var A;n.if((0,vt.not)((A=e.valid)!==null&&A!==void 0?A:p),R)}}vr.funcKeywordCode=rj;function Mx(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,vt._)`${n.parentData}[${n.parentDataProperty}]`))}function nj(t,e){let{gen:r}=t;r.if((0,vt._)`Array.isArray(${e})`,()=>{r.assign(Gn.default.vErrors,(0,vt._)`${Gn.default.vErrors} === null ? ${e} : ${Gn.default.vErrors}.concat(${e})`).assign(Gn.default.errors,(0,vt._)`${Gn.default.vErrors}.length`),(0,ej.extendErrors)(t)},()=>t.error())}function oj({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ux(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,vt.stringify)(r)})}function sj(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}vr.validSchemaType=sj;function ij({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}vr.validateKeywordUsage=ij});var Bx=B(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.extendSubschemaMode=cn.extendSubschemaData=cn.getSubschema=void 0;var kr=me(),Fx=$e();function aj(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}${(0,kr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Fx.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}cn.getSubschema=aj;function cj(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:p}=e,b=a.let("data",(0,kr._)`${e.data}${(0,kr.getProperty)(r)}`,!0);c(b),t.errorPath=(0,kr.str)`${l}${(0,Fx.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,kr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof kr.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}cn.extendSubschemaData=cj;function lj(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}cn.extendSubschemaMode=lj});var Bm=B((QK,Zx)=>{"use strict";Zx.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Hx=B((eW,Vx)=>{"use strict";var ln=Vx.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};jc(e,n,o,t,"",t)};ln.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ln.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ln.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ln.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function jc(t,e,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,l);for(var u in n){var p=n[u];if(Array.isArray(p)){if(u in ln.arrayKeywords)for(var b=0;b<p.length;b++)jc(t,e,r,p[b],o+"/"+u+"/"+b,s,o,u,n,b)}else if(u in ln.propsKeywords){if(p&&typeof p=="object")for(var f in p)jc(t,e,r,p[f],o+"/"+u+"/"+uj(f),s,o,u,n,f)}else(u in ln.keywords||t.allKeys&&!(u in ln.skipKeywords))&&jc(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function uj(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ai=B(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.getSchemaRefs=Ct.resolveUrl=Ct.normalizeId=Ct._getFullPath=Ct.getFullPath=Ct.inlineRef=void 0;var dj=$e(),pj=Bm(),hj=Hx(),mj=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function fj(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Zm(t):e?Kx(t)<=e:!1}Ct.inlineRef=fj;var gj=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Zm(t){for(let e in t){if(gj.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Zm)||typeof r=="object"&&Zm(r))return!0}return!1}function Kx(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!mj.has(r)&&(typeof t[r]=="object"&&(0,dj.eachItem)(t[r],n=>e+=Kx(n)),e===1/0))return 1/0}return e}function Wx(t,e="",r){r!==!1&&(e=qo(e));let n=t.parse(e);return Gx(t,n)}Ct.getFullPath=Wx;function Gx(t,e){return t.serialize(e).split("#")[0]+"#"}Ct._getFullPath=Gx;var yj=/#\/?$/;function qo(t){return t?t.replace(yj,""):""}Ct.normalizeId=qo;function bj(t,e,r){return r=qo(r),t.resolve(e,r)}Ct.resolveUrl=bj;var wj=/^[a-z_][-a-z0-9._]*$/i;function _j(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=qo(t[r]||e),s={"":o},i=Wx(n,o,!1),a={},c=new Set;return hj(t,{allKeys:!0},(p,b,f,h)=>{if(h===void 0)return;let w=i+b,S=s[h];typeof p[r]=="string"&&(S=R.call(this,p[r])),A.call(this,p.$anchor),A.call(this,p.$dynamicAnchor),s[b]=S;function R(L){let F=this.opts.uriResolver.resolve;if(L=qo(S?F(S,L):L),c.has(L))throw u(L);c.add(L);let W=this.refs[L];return typeof W=="string"&&(W=this.refs[W]),typeof W=="object"?l(p,W.schema,L):L!==qo(w)&&(L[0]==="#"?(l(p,a[L],L),a[L]=p):this.refs[L]=w),L}function A(L){if(typeof L=="string"){if(!wj.test(L))throw new Error(`invalid anchor "${L}"`);R.call(this,`#${L}`)}}}),a;function l(p,b,f){if(b!==void 0&&!pj(p,b))throw u(f)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Ct.getSchemaRefs=_j});var ui=B(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.getData=un.KeywordCxt=un.validateFunctionCode=void 0;var eS=Px(),Jx=ii(),Hm=zm(),Dc=ii(),vj=zx(),li=qx(),Vm=Bx(),Q=me(),ue=Dr(),kj=ai(),Mr=$e(),ci=si();function xj(t){if(nS(t)&&(oS(t),rS(t))){Tj(t);return}tS(t,()=>(0,eS.topBoolOrEmptySchema)(t))}un.validateFunctionCode=xj;function tS({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Q._)`${ue.default.data}, ${ue.default.valCxt}`,n.$async,()=>{t.code((0,Q._)`"use strict"; ${Yx(r,o)}`),$j(t,o),t.code(s)}):t.func(e,(0,Q._)`${ue.default.data}, ${Sj(o)}`,n.$async,()=>t.code(Yx(r,o)).code(s))}function Sj(t){return(0,Q._)`{${ue.default.instancePath}="", ${ue.default.parentData}, ${ue.default.parentDataProperty}, ${ue.default.rootData}=${ue.default.data}${t.dynamicRef?(0,Q._)`, ${ue.default.dynamicAnchors}={}`:Q.nil}}={}`}function $j(t,e){t.if(ue.default.valCxt,()=>{t.var(ue.default.instancePath,(0,Q._)`${ue.default.valCxt}.${ue.default.instancePath}`),t.var(ue.default.parentData,(0,Q._)`${ue.default.valCxt}.${ue.default.parentData}`),t.var(ue.default.parentDataProperty,(0,Q._)`${ue.default.valCxt}.${ue.default.parentDataProperty}`),t.var(ue.default.rootData,(0,Q._)`${ue.default.valCxt}.${ue.default.rootData}`),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,Q._)`${ue.default.valCxt}.${ue.default.dynamicAnchors}`)},()=>{t.var(ue.default.instancePath,(0,Q._)`""`),t.var(ue.default.parentData,(0,Q._)`undefined`),t.var(ue.default.parentDataProperty,(0,Q._)`undefined`),t.var(ue.default.rootData,ue.default.data),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,Q._)`{}`)})}function Tj(t){let{schema:e,opts:r,gen:n}=t;tS(t,()=>{r.$comment&&e.$comment&&iS(t),Cj(t),n.let(ue.default.vErrors,null),n.let(ue.default.errors,0),r.unevaluated&&Rj(t),sS(t),Nj(t)})}function Rj(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Q._)`${r}.evaluated`),e.if((0,Q._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Q._)`${t.evaluated}.props`,(0,Q._)`undefined`)),e.if((0,Q._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Q._)`${t.evaluated}.items`,(0,Q._)`undefined`))}function Yx(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Q._)`/*# sourceURL=${r} */`:Q.nil}function Ej(t,e){if(nS(t)&&(oS(t),rS(t))){Pj(t,e);return}(0,eS.boolOrEmptySchema)(t,e)}function rS({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function nS(t){return typeof t.schema!="boolean"}function Pj(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&iS(t),Ij(t),Oj(t);let s=n.const("_errs",ue.default.errors);sS(t,s),n.var(e,(0,Q._)`${s} === ${ue.default.errors}`)}function oS(t){(0,Mr.checkUnknownRules)(t),Aj(t)}function sS(t,e){if(t.opts.jtd)return Xx(t,[],!1,e);let r=(0,Jx.getSchemaTypes)(t.schema),n=(0,Jx.coerceAndCheckDataType)(t,r);Xx(t,r,!n,e)}function Aj(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Mr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Cj(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Mr.checkStrictMode)(t,"default is ignored in the schema root")}function Ij(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,kj.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Oj(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function iS({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Q._)`${ue.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Q.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Q._)`${ue.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Nj(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Q._)`${ue.default.errors} === 0`,()=>e.return(ue.default.data),()=>e.throw((0,Q._)`new ${o}(${ue.default.vErrors})`)):(e.assign((0,Q._)`${n}.errors`,ue.default.vErrors),s.unevaluated&&Lj(t),e.return((0,Q._)`${ue.default.errors} === 0`))}function Lj({gen:t,evaluated:e,props:r,items:n}){r instanceof Q.Name&&t.assign((0,Q._)`${e}.props`,r),n instanceof Q.Name&&t.assign((0,Q._)`${e}.items`,n)}function Xx(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Mr.schemaHasRulesButRef)(s,u))){o.block(()=>cS(t,"$ref",u.all.$ref.definition));return}c.jtd||zj(t,e),o.block(()=>{for(let b of u.rules)p(b);p(u.post)});function p(b){(0,Hm.shouldUseGroup)(s,b)&&(b.type?(o.if((0,Dc.checkDataType)(b.type,i,c.strictNumbers)),Qx(t,b),e.length===1&&e[0]===b.type&&r&&(o.else(),(0,Dc.reportTypeError)(t)),o.endIf()):Qx(t,b),a||o.if((0,Q._)`${ue.default.errors} === ${n||0}`))}}function Qx(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,vj.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Hm.shouldUseRule)(n,s)&&cS(t,s.keyword,s.definition,e.type)})}function zj(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(jj(t,e),t.opts.allowUnionTypes||Dj(t,e),Mj(t,t.dataTypes))}function jj(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{aS(t.dataTypes,r)||Km(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),qj(t,e)}}function Dj(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Km(t,"use allowUnionTypes to allow union type keyword")}function Mj(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Hm.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Uj(e,i))&&Km(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Uj(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function aS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function qj(t,e){let r=[];for(let n of t.dataTypes)aS(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Km(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Mr.checkStrictMode)(t,e,t.opts.strictTypes)}var Mc=class{constructor(e,r,n){if((0,li.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Mr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",lS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,li.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ue.default.errors))}result(e,r,n){this.failResult((0,Q.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,Q.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,Q._)`${r} !== undefined && (${(0,Q.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?ci.reportExtraError:ci.reportError)(this,this.def.error,r)}$dataError(){(0,ci.reportError)(this,this.def.$dataError||ci.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ci.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=Q.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Q.nil,r=Q.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Q.or)((0,Q._)`${o} === undefined`,r)),e!==Q.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Q.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Q.or)(i(),a());function i(){if(n.length){if(!(r instanceof Q.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Q._)`${(0,Dc.checkDataTypes)(c,r,s.opts.strictNumbers,Dc.DataType.Wrong)}`}return Q.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Q._)`!${c}(${r})`}return Q.nil}}subschema(e,r){let n=(0,Vm.getSubschema)(this.it,e);(0,Vm.extendSubschemaData)(n,this.it,e),(0,Vm.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Ej(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Mr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Mr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,Q.Name)),!0}};un.KeywordCxt=Mc;function cS(t,e,r,n){let o=new Mc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,li.funcKeywordCode)(o,r):"macro"in r?(0,li.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,li.funcKeywordCode)(o,r)}var Fj=/^\/(?:[^~]|~0|~1)*$/,Bj=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function lS(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ue.default.rootData;if(t[0]==="/"){if(!Fj.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ue.default.rootData}else{let l=Bj.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,Q._)`${s}${(0,Q.getProperty)((0,Mr.unescapeJsonPointer)(l))}`,i=(0,Q._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}un.getData=lS});var Uc=B(Gm=>{"use strict";Object.defineProperty(Gm,"__esModule",{value:!0});var Wm=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Gm.default=Wm});var di=B(Xm=>{"use strict";Object.defineProperty(Xm,"__esModule",{value:!0});var Jm=ai(),Ym=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Jm.resolveUrl)(e,r,n),this.missingSchema=(0,Jm.normalizeId)((0,Jm.getFullPath)(e,this.missingRef))}};Xm.default=Ym});var Fc=B(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.resolveSchema=Gt.getCompilingSchema=Gt.resolveRef=Gt.compileSchema=Gt.SchemaEnv=void 0;var ar=me(),Zj=Uc(),Jn=Dr(),cr=ai(),uS=$e(),Vj=ui(),Fo=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,cr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Gt.SchemaEnv=Fo;function ef(t){let e=dS.call(this,t);if(e)return e;let r=(0,cr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new ar.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Zj.default,code:(0,ar._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Jn.default.data,parentData:Jn.default.parentData,parentDataProperty:Jn.default.parentDataProperty,dataNames:[Jn.default.data],dataPathArr:[ar.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ar.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ar.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ar._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Vj.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Jn.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${Jn.default.self}`,`${Jn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:w}=l;f.evaluated={props:h instanceof ar.Name?void 0:h,items:w instanceof ar.Name?void 0:w,dynamicProps:h instanceof ar.Name,dynamicItems:w instanceof ar.Name},f.source&&(f.source.evaluated=(0,ar.stringify)(f.evaluated))}return t.validate=f,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}Gt.compileSchema=ef;function Hj(t,e,r){var n;r=(0,cr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Gj.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Fo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Kj.call(this,s)}Gt.resolveRef=Hj;function Kj(t){return(0,cr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ef.call(this,t)}function dS(t){for(let e of this._compilations)if(Wj(e,t))return e}Gt.getCompilingSchema=dS;function Wj(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Gj(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||qc.call(this,t,e)}function qc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,cr._getFullPath)(this.opts.uriResolver,r),o=(0,cr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Qm.call(this,r,t);let s=(0,cr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=qc.call(this,t,i);return typeof a?.schema!="object"?void 0:Qm.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ef.call(this,i),s===(0,cr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,cr.resolveUrl)(this.opts.uriResolver,o,l)),new Fo({schema:a,schemaId:c,root:t,baseId:o})}return Qm.call(this,r,i)}}Gt.resolveSchema=qc;var Jj=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Qm(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,uS.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!Jj.has(a)&&l&&(e=(0,cr.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,uS.schemaHasRulesButRef)(r,this.RULES)){let a=(0,cr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=qc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Fo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var pS=B((iW,Yj)=>{Yj.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var nf=B((aW,bS)=>{"use strict";var Xj=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),mS=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),tf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),fS=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Qj=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function rf(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var eD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function hS(t){return t.length=0,!0}function tD(t,e,r){if(t.length){let n=rf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function rD(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=tD;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=hS}else{o.push(l);continue}}return o.length&&(a===hS?r.zone=o.join(""):i?n.push(o.join("")):n.push(rf(o))),r.address=n.join(""),r}function gS(t){if(nD(t,":")<2)return{host:t,isIPV6:!1};let e=rD(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function nD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function oD(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var sD={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},iD=/[@/?#:]/g,aD=/[@/?#]/g;function yS(t,e){let r=e?aD:iD;return r.lastIndex=0,t.replace(r,n=>sD[n])}function cD(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(tf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&fS(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function lD(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(tf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&fS(s)?e+=s:e+="%"+o,r+=2;continue}}Qj(t[r])?e+=t[r]:e+=escape(t[r])}return e}function uD(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(tf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function dD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!mS(r)){let n=gS(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=yS(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}bS.exports={nonSimpleDomain:eD,recomposeAuthority:dD,reescapeHostDelimiters:yS,normalizePercentEncoding:cD,normalizePathEncoding:lD,escapePreservingEscapes:uD,removeDotSegments:oD,isIPv4:mS,isUUID:Xj,normalizeIPv6:gS,stringArrayToHexStripped:rf}});var xS=B((cW,kS)=>{"use strict";var{isUUID:pD}=nf(),hD=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,mD=["http","https","ws","wss","urn","urn:uuid"];function fD(t){return mD.indexOf(t)!==-1}function of(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function wS(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function _S(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function gD(t){return t.secure=of(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function yD(t){if((t.port===(of(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function bD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(hD);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=sf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function wD(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=sf(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function _D(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!pD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function vD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var vS={scheme:"http",domainHost:!0,parse:wS,serialize:_S},kD={scheme:"https",domainHost:vS.domainHost,parse:wS,serialize:_S},Bc={scheme:"ws",domainHost:!0,parse:gD,serialize:yD},xD={scheme:"wss",domainHost:Bc.domainHost,parse:Bc.parse,serialize:Bc.serialize},SD={scheme:"urn",parse:bD,serialize:wD,skipNormalize:!0},$D={scheme:"urn:uuid",parse:_D,serialize:vD,skipNormalize:!0},Zc={http:vS,https:kD,ws:Bc,wss:xD,urn:SD,"urn:uuid":$D};Object.setPrototypeOf(Zc,null);function sf(t){return t&&(Zc[t]||Zc[t.toLowerCase()])||void 0}kS.exports={wsIsSecure:of,SCHEMES:Zc,isValidSchemeName:fD,getSchemeHandler:sf}});var ES=B((lW,Kc)=>{"use strict";var{normalizeIPv6:TD,removeDotSegments:pi,recomposeAuthority:RD,normalizePercentEncoding:ED,normalizePathEncoding:PD,escapePreservingEscapes:AD,reescapeHostDelimiters:CD,isIPv4:ID,nonSimpleDomain:OD}=nf(),{SCHEMES:ND,getSchemeHandler:$S}=xS();function LD(t,e){return typeof t=="string"?t=FD(t,e):typeof t=="object"&&(t=Hc(Yn(t,e),e)),t}function zD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=Vc(t,n),{parsed:i,malformedAuthorityOrPort:a}=Vc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=TS(o,i,n,!0);return n.skipEscape=!0,Yn(c,n)}function TS(t,e,r,n){let o={};return n||(t=Hc(Yn(t,r),r),e=Hc(Yn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=pi(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=pi(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=pi(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=pi(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function jD(t,e,r){let n=SS(t,r),o=SS(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Yn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=$S(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=ED(r.path):(r.path=AD(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=RD(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=pi(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var DD=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,MD=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,UD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function qD(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Vc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(MD);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(UD);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(DD);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=qD(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(ID(n.host)===!1){let b=TD(n.host);n.host=b.host.toLowerCase(),s=b.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=$S(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&OD(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=CD(unescape(n.host),s))),n.path&&(n.path=PD(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Hc(t,e){return Vc(t,e).parsed}function FD(t,e){return RS(t,e).normalized}function RS(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Vc(t,e);return{normalized:n?t:Yn(r,e),malformedAuthorityOrPort:n}}function SS(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=RS(t,e);return n?void 0:r}if(typeof t=="object")return Yn(t,e)}var af={SCHEMES:ND,normalize:LD,resolve:zD,resolveComponent:TS,equal:jD,serialize:Yn,parse:Hc};Kc.exports=af;Kc.exports.default=af;Kc.exports.fastUri=af});var AS=B(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var PS=ES();PS.code='require("ajv/dist/runtime/uri").default';cf.default=PS});var DS=B(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.CodeGen=dt.Name=dt.nil=dt.stringify=dt.str=dt._=dt.KeywordCxt=void 0;var BD=ui();Object.defineProperty(dt,"KeywordCxt",{enumerable:!0,get:function(){return BD.KeywordCxt}});var Bo=me();Object.defineProperty(dt,"_",{enumerable:!0,get:function(){return Bo._}});Object.defineProperty(dt,"str",{enumerable:!0,get:function(){return Bo.str}});Object.defineProperty(dt,"stringify",{enumerable:!0,get:function(){return Bo.stringify}});Object.defineProperty(dt,"nil",{enumerable:!0,get:function(){return Bo.nil}});Object.defineProperty(dt,"Name",{enumerable:!0,get:function(){return Bo.Name}});Object.defineProperty(dt,"CodeGen",{enumerable:!0,get:function(){return Bo.CodeGen}});var ZD=Uc(),LS=di(),VD=Lm(),hi=Fc(),HD=me(),mi=ai(),Wc=ii(),uf=$e(),CS=pS(),KD=AS(),zS=(t,e)=>new RegExp(t,e);zS.code="new RegExp";var WD=["removeAdditional","useDefaults","coerceTypes"],GD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),JD={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},YD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},IS=200;function XD(t){var e,r,n,o,s,i,a,c,l,u,p,b,f,h,w,S,R,A,L,F,W,Ke,Je,jt,qr;let dr=t.strict,mn=(e=t.code)===null||e===void 0?void 0:e.optimize,fn=mn===!0||mn===void 0?1:mn||0,pr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:zS,_l=(o=t.uriResolver)!==null&&o!==void 0?o:KD.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:dr)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:dr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:dr)!==null&&u!==void 0?u:"log",strictTuples:(b=(p=t.strictTuples)!==null&&p!==void 0?p:dr)!==null&&b!==void 0?b:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:dr)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:fn,regExp:pr}:{optimize:fn,regExp:pr},loopRequired:(w=t.loopRequired)!==null&&w!==void 0?w:IS,loopEnum:(S=t.loopEnum)!==null&&S!==void 0?S:IS,meta:(R=t.meta)!==null&&R!==void 0?R:!0,messages:(A=t.messages)!==null&&A!==void 0?A:!0,inlineRefs:(L=t.inlineRefs)!==null&&L!==void 0?L:!0,schemaId:(F=t.schemaId)!==null&&F!==void 0?F:"$id",addUsedSchema:(W=t.addUsedSchema)!==null&&W!==void 0?W:!0,validateSchema:(Ke=t.validateSchema)!==null&&Ke!==void 0?Ke:!0,validateFormats:(Je=t.validateFormats)!==null&&Je!==void 0?Je:!0,unicodeRegExp:(jt=t.unicodeRegExp)!==null&&jt!==void 0?jt:!0,int32range:(qr=t.int32range)!==null&&qr!==void 0?qr:!0,uriResolver:_l}}var fi=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...XD(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new HD.ValueScope({scope:{},prefixes:GD,es5:r,lines:n}),this.logger=o1(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,VD.getRules)(),OS.call(this,JD,e,"NOT SUPPORTED"),OS.call(this,YD,e,"DEPRECATED","warn"),this._metaOpts=r1.call(this),e.formats&&e1.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&t1.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),QD.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=CS;n==="id"&&(o={...CS},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(u,p){await s.call(this,u.$schema);let b=this._addSchema(u,p);return b.validate||i.call(this,b)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(p){if(!(p instanceof LS.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await s.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function l(u){let p=this._loading[u];if(p)return p;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,mi.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=NS.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new hi.SchemaEnv({schema:{},schemaId:n});if(r=hi.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=NS.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,mi.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(i1.call(this,n,r),!r)return(0,uf.eachItem)(n,s=>lf.call(this,s)),this;c1.call(this,r);let o={...r,type:(0,Wc.getJSONTypes)(r.type),schemaType:(0,Wc.getJSONTypes)(r.schemaType)};return(0,uf.eachItem)(n,o.type.length===0?s=>lf.call(this,s,o):s=>o.type.forEach(i=>lf.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=jS(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,mi.normalizeId)(i||n);let l=mi.getSchemaRefs.call(this,e,n);return c=new hi.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):hi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{hi.compileSchema.call(this,e)}finally{this.opts=r}}};fi.ValidationError=ZD.default;fi.MissingRefError=LS.default;dt.default=fi;function OS(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function NS(t){return t=(0,mi.normalizeId)(t),this.schemas[t]||this.refs[t]}function QD(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function e1(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function t1(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function r1(){let t={...this.opts};for(let e of WD)delete t[e];return t}var n1={log(){},warn(){},error(){}};function o1(t){if(t===!1)return n1;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var s1=/^[a-z_$][a-z0-9_$:-]*$/i;function i1(t,e){let{RULES:r}=this;if((0,uf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!s1.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function lf(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Wc.getJSONTypes)(e.type),schemaType:(0,Wc.getJSONTypes)(e.schemaType)}};e.before?a1.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function a1(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function c1(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=jS(e)),t.validateSchema=this.compile(e,!0))}var l1={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function jS(t){return{anyOf:[t,l1]}}});var MS=B(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var u1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};df.default=u1});var BS=B(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.callRef=Xn.getValidate=void 0;var d1=di(),US=Wt(),It=me(),Zo=Dr(),qS=Fc(),Gc=$e(),p1={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return p();let u=qS.resolveRef.call(c,l,o,r);if(u===void 0)throw new d1.default(n.opts.uriResolver,o,r);if(u instanceof qS.SchemaEnv)return b(u);return f(u);function p(){if(s===l)return Jc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:l});return Jc(t,(0,It._)`${h}.validate`,l,l.$async)}function b(h){let w=FS(t,h);Jc(t,w,h,h.$async)}function f(h){let w=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,It.stringify)(h)}:{ref:h}),S=e.name("valid"),R=t.subschema({schema:h,dataTypes:[],schemaPath:It.nil,topSchemaRef:w,errSchemaPath:r},S);t.mergeEvaluated(R),t.ok(S)}}};function FS(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,It._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Xn.getValidate=FS;function Jc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Zo.default.this:It.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,It._)`await ${(0,US.callValidateCode)(t,e,l)}`),f(e),i||o.assign(h,!0)},w=>{o.if((0,It._)`!(${w} instanceof ${s.ValidationError})`,()=>o.throw(w)),b(w),i||o.assign(h,!1)}),t.ok(h)}function p(){t.result((0,US.callValidateCode)(t,e,l),()=>f(e),()=>b(e))}function b(h){let w=(0,It._)`${h}.errors`;o.assign(Zo.default.vErrors,(0,It._)`${Zo.default.vErrors} === null ? ${w} : ${Zo.default.vErrors}.concat(${w})`),o.assign(Zo.default.errors,(0,It._)`${Zo.default.vErrors}.length`)}function f(h){var w;if(!s.opts.unevaluated)return;let S=(w=r?.validate)===null||w===void 0?void 0:w.evaluated;if(s.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(s.props=Gc.mergeEvaluated.props(o,S.props,s.props));else{let R=o.var("props",(0,It._)`${h}.evaluated.props`);s.props=Gc.mergeEvaluated.props(o,R,s.props,It.Name)}if(s.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(s.items=Gc.mergeEvaluated.items(o,S.items,s.items));else{let R=o.var("items",(0,It._)`${h}.evaluated.items`);s.items=Gc.mergeEvaluated.items(o,R,s.items,It.Name)}}}Xn.callRef=Jc;Xn.default=p1});var ZS=B(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var h1=MS(),m1=BS(),f1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",h1.default,m1.default];pf.default=f1});var VS=B(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var Yc=me(),dn=Yc.operators,Xc={maximum:{okStr:"<=",ok:dn.LTE,fail:dn.GT},minimum:{okStr:">=",ok:dn.GTE,fail:dn.LT},exclusiveMaximum:{okStr:"<",ok:dn.LT,fail:dn.GTE},exclusiveMinimum:{okStr:">",ok:dn.GT,fail:dn.LTE}},g1={message:({keyword:t,schemaCode:e})=>(0,Yc.str)`must be ${Xc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Yc._)`{comparison: ${Xc[t].okStr}, limit: ${e}}`},y1={keyword:Object.keys(Xc),type:"number",schemaType:"number",$data:!0,error:g1,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Yc._)`${r} ${Xc[e].fail} ${n} || isNaN(${r})`)}};hf.default=y1});var HS=B(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var gi=me(),b1={message:({schemaCode:t})=>(0,gi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,gi._)`{multipleOf: ${t}}`},w1={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:b1,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,gi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,gi._)`${i} !== parseInt(${i})`;t.fail$data((0,gi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};mf.default=w1});var WS=B(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});function KS(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}ff.default=KS;KS.code='require("ajv/dist/runtime/ucs2length").default'});var GS=B(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var Qn=me(),_1=$e(),v1=WS(),k1={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Qn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Qn._)`{limit: ${t}}`},x1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:k1,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Qn.operators.GT:Qn.operators.LT,i=o.opts.unicode===!1?(0,Qn._)`${r}.length`:(0,Qn._)`${(0,_1.useFunc)(t.gen,v1.default)}(${r})`;t.fail$data((0,Qn._)`${i} ${s} ${n}`)}};gf.default=x1});var JS=B(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var S1=Wt(),$1=$e(),Vo=me(),T1={message:({schemaCode:t})=>(0,Vo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Vo._)`{pattern: ${t}}`},R1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:T1,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,Vo._)`new RegExp`:(0,$1.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Vo._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Vo._)`!${u}`)}else{let c=(0,S1.usePattern)(t,o);t.fail$data((0,Vo._)`!${c}.test(${r})`)}}};yf.default=R1});var YS=B(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var yi=me(),E1={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,yi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,yi._)`{limit: ${t}}`},P1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:E1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?yi.operators.GT:yi.operators.LT;t.fail$data((0,yi._)`Object.keys(${r}).length ${o} ${n}`)}};bf.default=P1});var XS=B(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var bi=Wt(),wi=me(),A1=$e(),C1={message:({params:{missingProperty:t}})=>(0,wi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,wi._)`{missingProperty: ${t}}`},I1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:C1,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let w of r)if(f?.[w]===void 0&&!h.has(w)){let S=i.schemaEnv.baseId+i.errSchemaPath,R=`required property "${w}" is not defined at "${S}" (strictRequired)`;(0,A1.checkStrictMode)(i,R,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(wi.nil,p);else for(let f of r)(0,bi.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>b(f,h)),t.ok(h)}else e.if((0,bi.checkMissingProp)(t,r,f)),(0,bi.reportMissingProp)(t,f),e.else()}function p(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,bi.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function b(f,h){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(h,(0,bi.propertyInData)(e,o,f,a.ownProperties)),e.if((0,wi.not)(h),()=>{t.error(),e.break()})},wi.nil)}}};wf.default=I1});var QS=B(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var _i=me(),O1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,_i.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,_i._)`{limit: ${t}}`},N1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:O1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?_i.operators.GT:_i.operators.LT;t.fail$data((0,_i._)`${r}.length ${o} ${n}`)}};_f.default=N1});var Qc=B(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var e$=Bm();e$.code='require("ajv/dist/runtime/equal").default';vf.default=e$});var t$=B(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var kf=ii(),pt=me(),L1=$e(),z1=Qc(),j1={message:({params:{i:t,j:e}})=>(0,pt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,pt._)`{i: ${t}, j: ${e}}`},D1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:j1,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),l=s.items?(0,kf.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,pt._)`${i} === false`),t.ok(c);function u(){let h=e.let("i",(0,pt._)`${r}.length`),w=e.let("j");t.setParams({i:h,j:w}),e.assign(c,!0),e.if((0,pt._)`${h} > 1`,()=>(p()?b:f)(h,w))}function p(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function b(h,w){let S=e.name("item"),R=(0,kf.checkDataTypes)(l,S,a.opts.strictNumbers,kf.DataType.Wrong),A=e.const("indices",(0,pt._)`{}`);e.for((0,pt._)`;${h}--;`,()=>{e.let(S,(0,pt._)`${r}[${h}]`),e.if(R,(0,pt._)`continue`),l.length>1&&e.if((0,pt._)`typeof ${S} == "string"`,(0,pt._)`${S} += "_"`),e.if((0,pt._)`typeof ${A}[${S}] == "number"`,()=>{e.assign(w,(0,pt._)`${A}[${S}]`),t.error(),e.assign(c,!1).break()}).code((0,pt._)`${A}[${S}] = ${h}`)})}function f(h,w){let S=(0,L1.useFunc)(e,z1.default),R=e.name("outer");e.label(R).for((0,pt._)`;${h}--;`,()=>e.for((0,pt._)`${w} = ${h}; ${w}--;`,()=>e.if((0,pt._)`${S}(${r}[${h}], ${r}[${w}])`,()=>{t.error(),e.assign(c,!1).break(R)})))}}};xf.default=D1});var r$=B($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var Sf=me(),M1=$e(),U1=Qc(),q1={message:"must be equal to constant",params:({schemaCode:t})=>(0,Sf._)`{allowedValue: ${t}}`},F1={keyword:"const",$data:!0,error:q1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Sf._)`!${(0,M1.useFunc)(e,U1.default)}(${r}, ${o})`):t.fail((0,Sf._)`${s} !== ${r}`)}};$f.default=F1});var n$=B(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var vi=me(),B1=$e(),Z1=Qc(),V1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,vi._)`{allowedValues: ${t}}`},H1={keyword:"enum",schemaType:"array",$data:!0,error:V1,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,B1.useFunc)(e,Z1.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);u=(0,vi.or)(...o.map((h,w)=>b(f,w)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,f=>e.if((0,vi._)`${l()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function b(f,h){let w=o[h];return typeof w=="object"&&w!==null?(0,vi._)`${l()}(${r}, ${f}[${h}])`:(0,vi._)`${r} === ${w}`}}};Tf.default=H1});var o$=B(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var K1=VS(),W1=HS(),G1=GS(),J1=JS(),Y1=YS(),X1=XS(),Q1=QS(),eM=t$(),tM=r$(),rM=n$(),nM=[K1.default,W1.default,G1.default,J1.default,Y1.default,X1.default,Q1.default,eM.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},tM.default,rM.default];Rf.default=nM});var Pf=B(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.validateAdditionalItems=void 0;var eo=me(),Ef=$e(),oM={message:({params:{len:t}})=>(0,eo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,eo._)`{limit: ${t}}`},sM={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oM,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Ef.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}s$(t,n)}};function s$(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,eo._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,eo._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Ef.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,eo._)`${a} <= ${e.length}`);r.if((0,eo.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Ef.Type.Num},l),i.allErrors||r.if((0,eo.not)(l),()=>r.break())})}}ki.validateAdditionalItems=s$;ki.default=sM});var Af=B(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.validateTuple=void 0;var i$=me(),el=$e(),iM=Wt(),aM={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return a$(t,"additionalItems",e);r.items=!0,!(0,el.alwaysValidSchema)(r,e)&&t.ok((0,iM.validateArray)(t))}};function a$(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=el.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,i$._)`${s}.length`);r.forEach((p,b)=>{(0,el.alwaysValidSchema)(a,p)||(n.if((0,i$._)`${l} > ${b}`,()=>t.subschema({keyword:i,schemaProp:b,dataProp:b},c)),t.ok(c))});function u(p){let{opts:b,errSchemaPath:f}=a,h=r.length,w=h===p.minItems&&(h===p.maxItems||p[e]===!1);if(b.strictTuples&&!w){let S=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,el.checkStrictMode)(a,S,b.strictTuples)}}}xi.validateTuple=a$;xi.default=aM});var c$=B(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var cM=Af(),lM={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,cM.validateTuple)(t,"items")};Cf.default=lM});var u$=B(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var l$=me(),uM=$e(),dM=Wt(),pM=Pf(),hM={message:({params:{len:t}})=>(0,l$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,l$._)`{limit: ${t}}`},mM={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:hM,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,uM.alwaysValidSchema)(n,e)&&(o?(0,pM.validateAdditionalItems)(t,o):t.ok((0,dM.validateArray)(t)))}};If.default=mM});var d$=B(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var Jt=me(),tl=$e(),fM={message:({params:{min:t,max:e}})=>e===void 0?(0,Jt.str)`must contain at least ${t} valid item(s)`:(0,Jt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Jt._)`{minContains: ${t}}`:(0,Jt._)`{minContains: ${t}, maxContains: ${e}}`},gM={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:fM,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,Jt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,tl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,tl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,tl.alwaysValidSchema)(s,r)){let w=(0,Jt._)`${u} >= ${i}`;a!==void 0&&(w=(0,Jt._)`${w} && ${u} <= ${a}`),t.pass(w);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?f(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,Jt._)`${o}.length > 0`,b)):(e.let(p,!1),b()),t.result(p,()=>t.reset());function b(){let w=e.name("_valid"),S=e.let("count",0);f(w,()=>e.if(w,()=>h(S)))}function f(w,S){e.forRange("i",0,u,R=>{t.subschema({keyword:"contains",dataProp:R,dataPropType:tl.Type.Num,compositeRule:!0},w),S()})}function h(w){e.code((0,Jt._)`${w}++`),a===void 0?e.if((0,Jt._)`${w} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,Jt._)`${w} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,Jt._)`${w} >= ${i}`,()=>e.assign(p,!0)))}}};Of.default=gM});var m$=B(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateSchemaDeps=xr.validatePropertyDeps=xr.error=void 0;var Nf=me(),yM=$e(),Si=Wt();xr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Nf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Nf._)`{property: ${t},
|
|
2354
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,pe._)`[${o}]`)}}}function Zj({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,pe._)`${e} !== undefined`,()=>t.assign((0,pe._)`${e}[${r}]`,n))}function Dm(t,e,r,n=qo.Correct){let o=n===qo.Correct?pe.operators.EQ:pe.operators.NEQ,s;switch(t){case"null":return(0,pe._)`${e} ${o} null`;case"array":s=(0,pe._)`Array.isArray(${e})`;break;case"object":s=(0,pe._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,pe._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,pe._)`typeof ${e} ${o} ${t}`}return n===qo.Correct?s:(0,pe.not)(s);function i(a=pe.nil){return(0,pe.and)((0,pe._)`typeof ${e} == "number"`,a,r?(0,pe._)`isFinite(${e})`:pe.nil)}}gt.checkDataType=Dm;function Mm(t,e,r,n){if(t.length===1)return Dm(t[0],e,r,n);let o,s=(0,jx.toHash)(t);if(s.array&&s.object){let i=(0,pe._)`typeof ${e} != "object"`;o=s.null?i:(0,pe._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=pe.nil;s.number&&delete s.integer;for(let i in s)o=(0,pe.and)(o,Dm(i,e,r,n));return o}gt.checkDataTypes=Mm;var Vj={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,pe._)`{type: ${t}}`:(0,pe._)`{type: ${e}}`};function Um(t){let e=Hj(t);(0,Mj.reportError)(e,Vj)}gt.reportTypeError=Um;function Hj(t){let{gen:e,data:r,schema:n}=t,o=(0,jx.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Ux=B(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.assignDefaults=void 0;var Fo=me(),Kj=$e();function Wj(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Mx(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Mx(t,s,o.default))}zc.assignDefaults=Wj;function Mx(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Fo._)`${s}${(0,Fo.getProperty)(e)}`;if(o){(0,Kj.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Fo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Fo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Fo._)`${a} = ${(0,Fo.stringify)(r)}`)}});var Wt=B(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.validateUnion=Oe.validateArray=Oe.usePattern=Oe.callValidateCode=Oe.schemaProperties=Oe.allSchemaProperties=Oe.noPropertyInData=Oe.propertyInData=Oe.isOwnProperty=Oe.hasPropFunc=Oe.reportMissingProp=Oe.checkMissingProp=Oe.checkReportMissingProp=void 0;var Ue=me(),qm=$e(),an=Dr(),Gj=$e();function Jj(t,e){let{gen:r,data:n,it:o}=t;r.if(Bm(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ue._)`${e}`},!0),t.error()})}Oe.checkReportMissingProp=Jj;function Yj({gen:t,data:e,it:{opts:r}},n,o){return(0,Ue.or)(...n.map(s=>(0,Ue.and)(Bm(t,e,s,r.ownProperties),(0,Ue._)`${o} = ${s}`)))}Oe.checkMissingProp=Yj;function Xj(t,e){t.setParams({missingProperty:e},!0),t.error()}Oe.reportMissingProp=Xj;function qx(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ue._)`Object.prototype.hasOwnProperty`})}Oe.hasPropFunc=qx;function Fm(t,e,r){return(0,Ue._)`${qx(t)}.call(${e}, ${r})`}Oe.isOwnProperty=Fm;function Qj(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} !== undefined`;return n?(0,Ue._)`${o} && ${Fm(t,e,r)}`:o}Oe.propertyInData=Qj;function Bm(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} === undefined`;return n?(0,Ue.or)(o,(0,Ue.not)(Fm(t,e,r))):o}Oe.noPropertyInData=Bm;function Fx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Oe.allSchemaProperties=Fx;function ez(t,e){return Fx(e).filter(r=>!(0,qm.alwaysValidSchema)(t,e[r]))}Oe.schemaProperties=ez;function tz({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Ue._)`${t}, ${e}, ${n}${o}`:e,p=[[an.default.instancePath,(0,Ue.strConcat)(an.default.instancePath,s)],[an.default.parentData,i.parentData],[an.default.parentDataProperty,i.parentDataProperty],[an.default.rootData,an.default.rootData]];i.opts.dynamicRef&&p.push([an.default.dynamicAnchors,an.default.dynamicAnchors]);let b=(0,Ue._)`${u}, ${r.object(...p)}`;return c!==Ue.nil?(0,Ue._)`${a}.call(${c}, ${b})`:(0,Ue._)`${a}(${b})`}Oe.callValidateCode=tz;var rz=(0,Ue._)`new RegExp`;function nz({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ue._)`${o.code==="new RegExp"?rz:(0,Gj.useFunc)(t,o)}(${r}, ${n})`})}Oe.usePattern=nz;function oz(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Ue._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:qm.Type.Num},s),e.if((0,Ue.not)(s),a)})}}Oe.validateArray=oz;function sz(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,qm.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,Ue._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Ue.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Oe.validateUnion=sz});var Vx=B(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.validateKeywordUsage=vr.validSchemaType=vr.funcKeywordCode=vr.macroKeywordCode=void 0;var vt=me(),Gn=Dr(),iz=Wt(),az=ai();function cz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Zx(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:vt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}vr.macroKeywordCode=cz;function lz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;dz(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Zx(n,o,l),p=n.let("valid");t.block$data(p,b),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function b(){if(e.errors===!1)w(),e.modifying&&Bx(t),$(()=>t.error());else{let R=e.async?f():m();e.modifying&&Bx(t),$(()=>uz(t,R))}}function f(){let R=n.let("ruleErrs",null);return n.try(()=>w((0,vt._)`await `),A=>n.assign(p,!1).if((0,vt._)`${A} instanceof ${c.ValidationError}`,()=>n.assign(R,(0,vt._)`${A}.errors`),()=>n.throw(A))),R}function m(){let R=(0,vt._)`${u}.errors`;return n.assign(R,null),w(vt.nil),R}function w(R=e.async?(0,vt._)`await `:vt.nil){let A=c.opts.passContext?Gn.default.this:Gn.default.self,L=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,vt._)`${R}${(0,iz.callValidateCode)(t,u,A,L)}`,e.modifying)}function $(R){var A;n.if((0,vt.not)((A=e.valid)!==null&&A!==void 0?A:p),R)}}vr.funcKeywordCode=lz;function Bx(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,vt._)`${n.parentData}[${n.parentDataProperty}]`))}function uz(t,e){let{gen:r}=t;r.if((0,vt._)`Array.isArray(${e})`,()=>{r.assign(Gn.default.vErrors,(0,vt._)`${Gn.default.vErrors} === null ? ${e} : ${Gn.default.vErrors}.concat(${e})`).assign(Gn.default.errors,(0,vt._)`${Gn.default.vErrors}.length`),(0,az.extendErrors)(t)},()=>t.error())}function dz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Zx(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,vt.stringify)(r)})}function pz(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}vr.validSchemaType=pz;function hz({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}vr.validateKeywordUsage=hz});var Kx=B(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.extendSubschemaMode=cn.extendSubschemaData=cn.getSubschema=void 0;var kr=me(),Hx=$e();function mz(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}${(0,kr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Hx.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}cn.getSubschema=mz;function fz(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:p}=e,b=a.let("data",(0,kr._)`${e.data}${(0,kr.getProperty)(r)}`,!0);c(b),t.errorPath=(0,kr.str)`${l}${(0,Hx.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,kr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof kr.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}cn.extendSubschemaData=fz;function gz(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}cn.extendSubschemaMode=gz});var Zm=B((aW,Wx)=>{"use strict";Wx.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Jx=B((cW,Gx)=>{"use strict";var ln=Gx.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Dc(e,n,o,t,"",t)};ln.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ln.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ln.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ln.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Dc(t,e,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,l);for(var u in n){var p=n[u];if(Array.isArray(p)){if(u in ln.arrayKeywords)for(var b=0;b<p.length;b++)Dc(t,e,r,p[b],o+"/"+u+"/"+b,s,o,u,n,b)}else if(u in ln.propsKeywords){if(p&&typeof p=="object")for(var f in p)Dc(t,e,r,p[f],o+"/"+u+"/"+yz(f),s,o,u,n,f)}else(u in ln.keywords||t.allKeys&&!(u in ln.skipKeywords))&&Dc(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function yz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var li=B(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.getSchemaRefs=Ct.resolveUrl=Ct.normalizeId=Ct._getFullPath=Ct.getFullPath=Ct.inlineRef=void 0;var bz=$e(),wz=Zm(),_z=Jx(),vz=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function kz(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Vm(t):e?Yx(t)<=e:!1}Ct.inlineRef=kz;var xz=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Vm(t){for(let e in t){if(xz.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Vm)||typeof r=="object"&&Vm(r))return!0}return!1}function Yx(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!vz.has(r)&&(typeof t[r]=="object"&&(0,bz.eachItem)(t[r],n=>e+=Yx(n)),e===1/0))return 1/0}return e}function Xx(t,e="",r){r!==!1&&(e=Bo(e));let n=t.parse(e);return Qx(t,n)}Ct.getFullPath=Xx;function Qx(t,e){return t.serialize(e).split("#")[0]+"#"}Ct._getFullPath=Qx;var Sz=/#\/?$/;function Bo(t){return t?t.replace(Sz,""):""}Ct.normalizeId=Bo;function $z(t,e,r){return r=Bo(r),t.resolve(e,r)}Ct.resolveUrl=$z;var Tz=/^[a-z_][-a-z0-9._]*$/i;function Rz(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Bo(t[r]||e),s={"":o},i=Xx(n,o,!1),a={},c=new Set;return _z(t,{allKeys:!0},(p,b,f,m)=>{if(m===void 0)return;let w=i+b,$=s[m];typeof p[r]=="string"&&($=R.call(this,p[r])),A.call(this,p.$anchor),A.call(this,p.$dynamicAnchor),s[b]=$;function R(L){let F=this.opts.uriResolver.resolve;if(L=Bo($?F($,L):L),c.has(L))throw u(L);c.add(L);let W=this.refs[L];return typeof W=="string"&&(W=this.refs[W]),typeof W=="object"?l(p,W.schema,L):L!==Bo(w)&&(L[0]==="#"?(l(p,a[L],L),a[L]=p):this.refs[L]=w),L}function A(L){if(typeof L=="string"){if(!Tz.test(L))throw new Error(`invalid anchor "${L}"`);R.call(this,`#${L}`)}}}),a;function l(p,b,f){if(b!==void 0&&!wz(p,b))throw u(f)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Ct.getSchemaRefs=Rz});var pi=B(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.getData=un.KeywordCxt=un.validateFunctionCode=void 0;var oS=Ox(),eS=ci(),Km=zm(),Mc=ci(),Ez=Ux(),di=Vx(),Hm=Kx(),Q=me(),ue=Dr(),Pz=li(),Mr=$e(),ui=ai();function Az(t){if(aS(t)&&(cS(t),iS(t))){Oz(t);return}sS(t,()=>(0,oS.topBoolOrEmptySchema)(t))}un.validateFunctionCode=Az;function sS({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Q._)`${ue.default.data}, ${ue.default.valCxt}`,n.$async,()=>{t.code((0,Q._)`"use strict"; ${tS(r,o)}`),Iz(t,o),t.code(s)}):t.func(e,(0,Q._)`${ue.default.data}, ${Cz(o)}`,n.$async,()=>t.code(tS(r,o)).code(s))}function Cz(t){return(0,Q._)`{${ue.default.instancePath}="", ${ue.default.parentData}, ${ue.default.parentDataProperty}, ${ue.default.rootData}=${ue.default.data}${t.dynamicRef?(0,Q._)`, ${ue.default.dynamicAnchors}={}`:Q.nil}}={}`}function Iz(t,e){t.if(ue.default.valCxt,()=>{t.var(ue.default.instancePath,(0,Q._)`${ue.default.valCxt}.${ue.default.instancePath}`),t.var(ue.default.parentData,(0,Q._)`${ue.default.valCxt}.${ue.default.parentData}`),t.var(ue.default.parentDataProperty,(0,Q._)`${ue.default.valCxt}.${ue.default.parentDataProperty}`),t.var(ue.default.rootData,(0,Q._)`${ue.default.valCxt}.${ue.default.rootData}`),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,Q._)`${ue.default.valCxt}.${ue.default.dynamicAnchors}`)},()=>{t.var(ue.default.instancePath,(0,Q._)`""`),t.var(ue.default.parentData,(0,Q._)`undefined`),t.var(ue.default.parentDataProperty,(0,Q._)`undefined`),t.var(ue.default.rootData,ue.default.data),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,Q._)`{}`)})}function Oz(t){let{schema:e,opts:r,gen:n}=t;sS(t,()=>{r.$comment&&e.$comment&&uS(t),Dz(t),n.let(ue.default.vErrors,null),n.let(ue.default.errors,0),r.unevaluated&&Nz(t),lS(t),qz(t)})}function Nz(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Q._)`${r}.evaluated`),e.if((0,Q._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Q._)`${t.evaluated}.props`,(0,Q._)`undefined`)),e.if((0,Q._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Q._)`${t.evaluated}.items`,(0,Q._)`undefined`))}function tS(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Q._)`/*# sourceURL=${r} */`:Q.nil}function Lz(t,e){if(aS(t)&&(cS(t),iS(t))){jz(t,e);return}(0,oS.boolOrEmptySchema)(t,e)}function iS({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function aS(t){return typeof t.schema!="boolean"}function jz(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&uS(t),Mz(t),Uz(t);let s=n.const("_errs",ue.default.errors);lS(t,s),n.var(e,(0,Q._)`${s} === ${ue.default.errors}`)}function cS(t){(0,Mr.checkUnknownRules)(t),zz(t)}function lS(t,e){if(t.opts.jtd)return rS(t,[],!1,e);let r=(0,eS.getSchemaTypes)(t.schema),n=(0,eS.coerceAndCheckDataType)(t,r);rS(t,r,!n,e)}function zz(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Mr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Dz(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Mr.checkStrictMode)(t,"default is ignored in the schema root")}function Mz(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Pz.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Uz(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function uS({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Q._)`${ue.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Q.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Q._)`${ue.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function qz(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Q._)`${ue.default.errors} === 0`,()=>e.return(ue.default.data),()=>e.throw((0,Q._)`new ${o}(${ue.default.vErrors})`)):(e.assign((0,Q._)`${n}.errors`,ue.default.vErrors),s.unevaluated&&Fz(t),e.return((0,Q._)`${ue.default.errors} === 0`))}function Fz({gen:t,evaluated:e,props:r,items:n}){r instanceof Q.Name&&t.assign((0,Q._)`${e}.props`,r),n instanceof Q.Name&&t.assign((0,Q._)`${e}.items`,n)}function rS(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Mr.schemaHasRulesButRef)(s,u))){o.block(()=>pS(t,"$ref",u.all.$ref.definition));return}c.jtd||Bz(t,e),o.block(()=>{for(let b of u.rules)p(b);p(u.post)});function p(b){(0,Km.shouldUseGroup)(s,b)&&(b.type?(o.if((0,Mc.checkDataType)(b.type,i,c.strictNumbers)),nS(t,b),e.length===1&&e[0]===b.type&&r&&(o.else(),(0,Mc.reportTypeError)(t)),o.endIf()):nS(t,b),a||o.if((0,Q._)`${ue.default.errors} === ${n||0}`))}}function nS(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Ez.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Km.shouldUseRule)(n,s)&&pS(t,s.keyword,s.definition,e.type)})}function Bz(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Zz(t,e),t.opts.allowUnionTypes||Vz(t,e),Hz(t,t.dataTypes))}function Zz(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{dS(t.dataTypes,r)||Wm(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Wz(t,e)}}function Vz(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Wm(t,"use allowUnionTypes to allow union type keyword")}function Hz(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Km.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>Kz(e,i))&&Wm(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function Kz(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function dS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Wz(t,e){let r=[];for(let n of t.dataTypes)dS(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Wm(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Mr.checkStrictMode)(t,e,t.opts.strictTypes)}var Uc=class{constructor(e,r,n){if((0,di.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Mr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",hS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,di.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",ue.default.errors))}result(e,r,n){this.failResult((0,Q.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,Q.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,Q._)`${r} !== undefined && (${(0,Q.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?ui.reportExtraError:ui.reportError)(this,this.def.error,r)}$dataError(){(0,ui.reportError)(this,this.def.$dataError||ui.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ui.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=Q.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Q.nil,r=Q.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Q.or)((0,Q._)`${o} === undefined`,r)),e!==Q.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Q.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Q.or)(i(),a());function i(){if(n.length){if(!(r instanceof Q.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Q._)`${(0,Mc.checkDataTypes)(c,r,s.opts.strictNumbers,Mc.DataType.Wrong)}`}return Q.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Q._)`!${c}(${r})`}return Q.nil}}subschema(e,r){let n=(0,Hm.getSubschema)(this.it,e);(0,Hm.extendSubschemaData)(n,this.it,e),(0,Hm.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Lz(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Mr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Mr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,Q.Name)),!0}};un.KeywordCxt=Uc;function pS(t,e,r,n){let o=new Uc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,di.funcKeywordCode)(o,r):"macro"in r?(0,di.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,di.funcKeywordCode)(o,r)}var Gz=/^\/(?:[^~]|~0|~1)*$/,Jz=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function hS(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ue.default.rootData;if(t[0]==="/"){if(!Gz.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ue.default.rootData}else{let l=Jz.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,Q._)`${s}${(0,Q.getProperty)((0,Mr.unescapeJsonPointer)(l))}`,i=(0,Q._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}un.getData=hS});var qc=B(Jm=>{"use strict";Object.defineProperty(Jm,"__esModule",{value:!0});var Gm=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Jm.default=Gm});var hi=B(Qm=>{"use strict";Object.defineProperty(Qm,"__esModule",{value:!0});var Ym=li(),Xm=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ym.resolveUrl)(e,r,n),this.missingSchema=(0,Ym.normalizeId)((0,Ym.getFullPath)(e,this.missingRef))}};Qm.default=Xm});var Bc=B(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.resolveSchema=Gt.getCompilingSchema=Gt.resolveRef=Gt.compileSchema=Gt.SchemaEnv=void 0;var ar=me(),Yz=qc(),Jn=Dr(),cr=li(),mS=$e(),Xz=pi(),Zo=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,cr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Gt.SchemaEnv=Zo;function tf(t){let e=fS.call(this,t);if(e)return e;let r=(0,cr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new ar.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Yz.default,code:(0,ar._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Jn.default.data,parentData:Jn.default.parentData,parentDataProperty:Jn.default.parentDataProperty,dataNames:[Jn.default.data],dataPathArr:[ar.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ar.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ar.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ar._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Xz.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Jn.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let f=new Function(`${Jn.default.self}`,`${Jn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:w}=l;f.evaluated={props:m instanceof ar.Name?void 0:m,items:w instanceof ar.Name?void 0:w,dynamicProps:m instanceof ar.Name,dynamicItems:w instanceof ar.Name},f.source&&(f.source.evaluated=(0,ar.stringify)(f.evaluated))}return t.validate=f,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}Gt.compileSchema=tf;function Qz(t,e,r){var n;r=(0,cr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=rD.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Zo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=eD.call(this,s)}Gt.resolveRef=Qz;function eD(t){return(0,cr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:tf.call(this,t)}function fS(t){for(let e of this._compilations)if(tD(e,t))return e}Gt.getCompilingSchema=fS;function tD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function rD(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Fc.call(this,t,e)}function Fc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,cr._getFullPath)(this.opts.uriResolver,r),o=(0,cr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return ef.call(this,r,t);let s=(0,cr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Fc.call(this,t,i);return typeof a?.schema!="object"?void 0:ef.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||tf.call(this,i),s===(0,cr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,cr.resolveUrl)(this.opts.uriResolver,o,l)),new Zo({schema:a,schemaId:c,root:t,baseId:o})}return ef.call(this,r,i)}}Gt.resolveSchema=Fc;var nD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ef(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,mS.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!nD.has(a)&&l&&(e=(0,cr.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,mS.schemaHasRulesButRef)(r,this.RULES)){let a=(0,cr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Fc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Zo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var gS=B((mW,oD)=>{oD.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var of=B((fW,kS)=>{"use strict";var sD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),bS=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),rf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),wS=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),iD=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function nf(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var aD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function yS(t){return t.length=0,!0}function cD(t,e,r){if(t.length){let n=nf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function lD(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=cD;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=yS}else{o.push(l);continue}}return o.length&&(a===yS?r.zone=o.join(""):i?n.push(o.join("")):n.push(nf(o))),r.address=n.join(""),r}function _S(t){if(uD(t,":")<2)return{host:t,isIPV6:!1};let e=lD(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function uD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function dD(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var pD={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},hD=/[@/?#:]/g,mD=/[@/?#]/g;function vS(t,e){let r=e?mD:hD;return r.lastIndex=0,t.replace(r,n=>pD[n])}function fD(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(rf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&wS(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function gD(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(rf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&wS(s)?e+=s:e+="%"+o,r+=2;continue}}iD(t[r])?e+=t[r]:e+=escape(t[r])}return e}function yD(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(rf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function bD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!bS(r)){let n=_S(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=vS(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}kS.exports={nonSimpleDomain:aD,recomposeAuthority:bD,reescapeHostDelimiters:vS,normalizePercentEncoding:fD,normalizePathEncoding:gD,escapePreservingEscapes:yD,removeDotSegments:dD,isIPv4:bS,isUUID:sD,normalizeIPv6:_S,stringArrayToHexStripped:nf}});var RS=B((gW,TS)=>{"use strict";var{isUUID:wD}=of(),_D=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,vD=["http","https","ws","wss","urn","urn:uuid"];function kD(t){return vD.indexOf(t)!==-1}function sf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function xS(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function SS(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function xD(t){return t.secure=sf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function SD(t){if((t.port===(sf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function $D(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(_D);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=af(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function TD(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=af(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function RD(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!wD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function ED(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var $S={scheme:"http",domainHost:!0,parse:xS,serialize:SS},PD={scheme:"https",domainHost:$S.domainHost,parse:xS,serialize:SS},Zc={scheme:"ws",domainHost:!0,parse:xD,serialize:SD},AD={scheme:"wss",domainHost:Zc.domainHost,parse:Zc.parse,serialize:Zc.serialize},CD={scheme:"urn",parse:$D,serialize:TD,skipNormalize:!0},ID={scheme:"urn:uuid",parse:RD,serialize:ED,skipNormalize:!0},Vc={http:$S,https:PD,ws:Zc,wss:AD,urn:CD,"urn:uuid":ID};Object.setPrototypeOf(Vc,null);function af(t){return t&&(Vc[t]||Vc[t.toLowerCase()])||void 0}TS.exports={wsIsSecure:sf,SCHEMES:Vc,isValidSchemeName:kD,getSchemeHandler:af}});var IS=B((yW,Wc)=>{"use strict";var{normalizeIPv6:OD,removeDotSegments:mi,recomposeAuthority:ND,normalizePercentEncoding:LD,normalizePathEncoding:jD,escapePreservingEscapes:zD,reescapeHostDelimiters:DD,isIPv4:MD,nonSimpleDomain:UD}=of(),{SCHEMES:qD,getSchemeHandler:PS}=RS();function FD(t,e){return typeof t=="string"?t=GD(t,e):typeof t=="object"&&(t=Kc(Yn(t,e),e)),t}function BD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=Hc(t,n),{parsed:i,malformedAuthorityOrPort:a}=Hc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=AS(o,i,n,!0);return n.skipEscape=!0,Yn(c,n)}function AS(t,e,r,n){let o={};return n||(t=Kc(Yn(t,r),r),e=Kc(Yn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=mi(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=mi(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=mi(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=mi(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function ZD(t,e,r){let n=ES(t,r),o=ES(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Yn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=PS(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=LD(r.path):(r.path=zD(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=ND(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=mi(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var VD=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,HD=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,KD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function WD(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Hc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(HD);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(KD);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(VD);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=WD(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(MD(n.host)===!1){let b=OD(n.host);n.host=b.host.toLowerCase(),s=b.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=PS(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&UD(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=DD(unescape(n.host),s))),n.path&&(n.path=jD(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Kc(t,e){return Hc(t,e).parsed}function GD(t,e){return CS(t,e).normalized}function CS(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Hc(t,e);return{normalized:n?t:Yn(r,e),malformedAuthorityOrPort:n}}function ES(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=CS(t,e);return n?void 0:r}if(typeof t=="object")return Yn(t,e)}var cf={SCHEMES:qD,normalize:FD,resolve:BD,resolveComponent:AS,equal:ZD,serialize:Yn,parse:Kc};Wc.exports=cf;Wc.exports.default=cf;Wc.exports.fastUri=cf});var NS=B(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var OS=IS();OS.code='require("ajv/dist/runtime/uri").default';lf.default=OS});var FS=B(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.CodeGen=dt.Name=dt.nil=dt.stringify=dt.str=dt._=dt.KeywordCxt=void 0;var JD=pi();Object.defineProperty(dt,"KeywordCxt",{enumerable:!0,get:function(){return JD.KeywordCxt}});var Vo=me();Object.defineProperty(dt,"_",{enumerable:!0,get:function(){return Vo._}});Object.defineProperty(dt,"str",{enumerable:!0,get:function(){return Vo.str}});Object.defineProperty(dt,"stringify",{enumerable:!0,get:function(){return Vo.stringify}});Object.defineProperty(dt,"nil",{enumerable:!0,get:function(){return Vo.nil}});Object.defineProperty(dt,"Name",{enumerable:!0,get:function(){return Vo.Name}});Object.defineProperty(dt,"CodeGen",{enumerable:!0,get:function(){return Vo.CodeGen}});var YD=qc(),MS=hi(),XD=jm(),fi=Bc(),QD=me(),gi=li(),Gc=ci(),df=$e(),LS=gS(),e1=NS(),US=(t,e)=>new RegExp(t,e);US.code="new RegExp";var t1=["removeAdditional","useDefaults","coerceTypes"],r1=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),n1={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},o1={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},jS=200;function s1(t){var e,r,n,o,s,i,a,c,l,u,p,b,f,m,w,$,R,A,L,F,W,Ke,Je,zt,qr;let dr=t.strict,mn=(e=t.code)===null||e===void 0?void 0:e.optimize,fn=mn===!0||mn===void 0?1:mn||0,pr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:US,vl=(o=t.uriResolver)!==null&&o!==void 0?o:e1.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:dr)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:dr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:dr)!==null&&u!==void 0?u:"log",strictTuples:(b=(p=t.strictTuples)!==null&&p!==void 0?p:dr)!==null&&b!==void 0?b:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:dr)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:fn,regExp:pr}:{optimize:fn,regExp:pr},loopRequired:(w=t.loopRequired)!==null&&w!==void 0?w:jS,loopEnum:($=t.loopEnum)!==null&&$!==void 0?$:jS,meta:(R=t.meta)!==null&&R!==void 0?R:!0,messages:(A=t.messages)!==null&&A!==void 0?A:!0,inlineRefs:(L=t.inlineRefs)!==null&&L!==void 0?L:!0,schemaId:(F=t.schemaId)!==null&&F!==void 0?F:"$id",addUsedSchema:(W=t.addUsedSchema)!==null&&W!==void 0?W:!0,validateSchema:(Ke=t.validateSchema)!==null&&Ke!==void 0?Ke:!0,validateFormats:(Je=t.validateFormats)!==null&&Je!==void 0?Je:!0,unicodeRegExp:(zt=t.unicodeRegExp)!==null&&zt!==void 0?zt:!0,int32range:(qr=t.int32range)!==null&&qr!==void 0?qr:!0,uriResolver:vl}}var yi=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...s1(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new QD.ValueScope({scope:{},prefixes:r1,es5:r,lines:n}),this.logger=d1(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,XD.getRules)(),zS.call(this,n1,e,"NOT SUPPORTED"),zS.call(this,o1,e,"DEPRECATED","warn"),this._metaOpts=l1.call(this),e.formats&&a1.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&c1.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),i1.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=LS;n==="id"&&(o={...LS},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(u,p){await s.call(this,u.$schema);let b=this._addSchema(u,p);return b.validate||i.call(this,b)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(p){if(!(p instanceof MS.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await s.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function l(u){let p=this._loading[u];if(p)return p;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,gi.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=DS.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new fi.SchemaEnv({schema:{},schemaId:n});if(r=fi.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=DS.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,gi.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(h1.call(this,n,r),!r)return(0,df.eachItem)(n,s=>uf.call(this,s)),this;f1.call(this,r);let o={...r,type:(0,Gc.getJSONTypes)(r.type),schemaType:(0,Gc.getJSONTypes)(r.schemaType)};return(0,df.eachItem)(n,o.type.length===0?s=>uf.call(this,s,o):s=>o.type.forEach(i=>uf.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=qS(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,gi.normalizeId)(i||n);let l=gi.getSchemaRefs.call(this,e,n);return c=new fi.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):fi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{fi.compileSchema.call(this,e)}finally{this.opts=r}}};yi.ValidationError=YD.default;yi.MissingRefError=MS.default;dt.default=yi;function zS(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function DS(t){return t=(0,gi.normalizeId)(t),this.schemas[t]||this.refs[t]}function i1(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function a1(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function c1(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function l1(){let t={...this.opts};for(let e of t1)delete t[e];return t}var u1={log(){},warn(){},error(){}};function d1(t){if(t===!1)return u1;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var p1=/^[a-z_$][a-z0-9_$:-]*$/i;function h1(t,e){let{RULES:r}=this;if((0,df.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!p1.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function uf(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Gc.getJSONTypes)(e.type),schemaType:(0,Gc.getJSONTypes)(e.schemaType)}};e.before?m1.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function m1(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function f1(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=qS(e)),t.validateSchema=this.compile(e,!0))}var g1={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function qS(t){return{anyOf:[t,g1]}}});var BS=B(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var y1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};pf.default=y1});var KS=B(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.callRef=Xn.getValidate=void 0;var b1=hi(),ZS=Wt(),It=me(),Ho=Dr(),VS=Bc(),Jc=$e(),w1={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return p();let u=VS.resolveRef.call(c,l,o,r);if(u===void 0)throw new b1.default(n.opts.uriResolver,o,r);if(u instanceof VS.SchemaEnv)return b(u);return f(u);function p(){if(s===l)return Yc(t,i,s,s.$async);let m=e.scopeValue("root",{ref:l});return Yc(t,(0,It._)`${m}.validate`,l,l.$async)}function b(m){let w=HS(t,m);Yc(t,w,m,m.$async)}function f(m){let w=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,It.stringify)(m)}:{ref:m}),$=e.name("valid"),R=t.subschema({schema:m,dataTypes:[],schemaPath:It.nil,topSchemaRef:w,errSchemaPath:r},$);t.mergeEvaluated(R),t.ok($)}}};function HS(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,It._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Xn.getValidate=HS;function Yc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Ho.default.this:It.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,It._)`await ${(0,ZS.callValidateCode)(t,e,l)}`),f(e),i||o.assign(m,!0)},w=>{o.if((0,It._)`!(${w} instanceof ${s.ValidationError})`,()=>o.throw(w)),b(w),i||o.assign(m,!1)}),t.ok(m)}function p(){t.result((0,ZS.callValidateCode)(t,e,l),()=>f(e),()=>b(e))}function b(m){let w=(0,It._)`${m}.errors`;o.assign(Ho.default.vErrors,(0,It._)`${Ho.default.vErrors} === null ? ${w} : ${Ho.default.vErrors}.concat(${w})`),o.assign(Ho.default.errors,(0,It._)`${Ho.default.vErrors}.length`)}function f(m){var w;if(!s.opts.unevaluated)return;let $=(w=r?.validate)===null||w===void 0?void 0:w.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=Jc.mergeEvaluated.props(o,$.props,s.props));else{let R=o.var("props",(0,It._)`${m}.evaluated.props`);s.props=Jc.mergeEvaluated.props(o,R,s.props,It.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=Jc.mergeEvaluated.items(o,$.items,s.items));else{let R=o.var("items",(0,It._)`${m}.evaluated.items`);s.items=Jc.mergeEvaluated.items(o,R,s.items,It.Name)}}}Xn.callRef=Yc;Xn.default=w1});var WS=B(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var _1=BS(),v1=KS(),k1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_1.default,v1.default];hf.default=k1});var GS=B(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var Xc=me(),dn=Xc.operators,Qc={maximum:{okStr:"<=",ok:dn.LTE,fail:dn.GT},minimum:{okStr:">=",ok:dn.GTE,fail:dn.LT},exclusiveMaximum:{okStr:"<",ok:dn.LT,fail:dn.GTE},exclusiveMinimum:{okStr:">",ok:dn.GT,fail:dn.LTE}},x1={message:({keyword:t,schemaCode:e})=>(0,Xc.str)`must be ${Qc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Xc._)`{comparison: ${Qc[t].okStr}, limit: ${e}}`},S1={keyword:Object.keys(Qc),type:"number",schemaType:"number",$data:!0,error:x1,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Xc._)`${r} ${Qc[e].fail} ${n} || isNaN(${r})`)}};mf.default=S1});var JS=B(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var bi=me(),$1={message:({schemaCode:t})=>(0,bi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,bi._)`{multipleOf: ${t}}`},T1={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:$1,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,bi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,bi._)`${i} !== parseInt(${i})`;t.fail$data((0,bi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};ff.default=T1});var XS=B(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});function YS(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}gf.default=YS;YS.code='require("ajv/dist/runtime/ucs2length").default'});var QS=B(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var Qn=me(),R1=$e(),E1=XS(),P1={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Qn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Qn._)`{limit: ${t}}`},A1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:P1,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Qn.operators.GT:Qn.operators.LT,i=o.opts.unicode===!1?(0,Qn._)`${r}.length`:(0,Qn._)`${(0,R1.useFunc)(t.gen,E1.default)}(${r})`;t.fail$data((0,Qn._)`${i} ${s} ${n}`)}};yf.default=A1});var e$=B(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var C1=Wt(),I1=$e(),Ko=me(),O1={message:({schemaCode:t})=>(0,Ko.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ko._)`{pattern: ${t}}`},N1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:O1,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?(0,Ko._)`new RegExp`:(0,I1.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Ko._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Ko._)`!${u}`)}else{let c=(0,C1.usePattern)(t,o);t.fail$data((0,Ko._)`!${c}.test(${r})`)}}};bf.default=N1});var t$=B(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var wi=me(),L1={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,wi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,wi._)`{limit: ${t}}`},j1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:L1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?wi.operators.GT:wi.operators.LT;t.fail$data((0,wi._)`Object.keys(${r}).length ${o} ${n}`)}};wf.default=j1});var r$=B(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var _i=Wt(),vi=me(),z1=$e(),D1={message:({params:{missingProperty:t}})=>(0,vi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,vi._)`{missingProperty: ${t}}`},M1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:D1,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let w of r)if(f?.[w]===void 0&&!m.has(w)){let $=i.schemaEnv.baseId+i.errSchemaPath,R=`required property "${w}" is not defined at "${$}" (strictRequired)`;(0,z1.checkStrictMode)(i,R,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(vi.nil,p);else for(let f of r)(0,_i.checkReportMissingProp)(t,f)}function u(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>b(f,m)),t.ok(m)}else e.if((0,_i.checkMissingProp)(t,r,f)),(0,_i.reportMissingProp)(t,f),e.else()}function p(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,_i.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function b(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,_i.propertyInData)(e,o,f,a.ownProperties)),e.if((0,vi.not)(m),()=>{t.error(),e.break()})},vi.nil)}}};_f.default=M1});var n$=B(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var ki=me(),U1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ki.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ki._)`{limit: ${t}}`},q1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:U1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ki.operators.GT:ki.operators.LT;t.fail$data((0,ki._)`${r}.length ${o} ${n}`)}};vf.default=q1});var el=B(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var o$=Zm();o$.code='require("ajv/dist/runtime/equal").default';kf.default=o$});var s$=B(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var xf=ci(),pt=me(),F1=$e(),B1=el(),Z1={message:({params:{i:t,j:e}})=>(0,pt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,pt._)`{i: ${t}, j: ${e}}`},V1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Z1,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),l=s.items?(0,xf.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,pt._)`${i} === false`),t.ok(c);function u(){let m=e.let("i",(0,pt._)`${r}.length`),w=e.let("j");t.setParams({i:m,j:w}),e.assign(c,!0),e.if((0,pt._)`${m} > 1`,()=>(p()?b:f)(m,w))}function p(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function b(m,w){let $=e.name("item"),R=(0,xf.checkDataTypes)(l,$,a.opts.strictNumbers,xf.DataType.Wrong),A=e.const("indices",(0,pt._)`{}`);e.for((0,pt._)`;${m}--;`,()=>{e.let($,(0,pt._)`${r}[${m}]`),e.if(R,(0,pt._)`continue`),l.length>1&&e.if((0,pt._)`typeof ${$} == "string"`,(0,pt._)`${$} += "_"`),e.if((0,pt._)`typeof ${A}[${$}] == "number"`,()=>{e.assign(w,(0,pt._)`${A}[${$}]`),t.error(),e.assign(c,!1).break()}).code((0,pt._)`${A}[${$}] = ${m}`)})}function f(m,w){let $=(0,F1.useFunc)(e,B1.default),R=e.name("outer");e.label(R).for((0,pt._)`;${m}--;`,()=>e.for((0,pt._)`${w} = ${m}; ${w}--;`,()=>e.if((0,pt._)`${$}(${r}[${m}], ${r}[${w}])`,()=>{t.error(),e.assign(c,!1).break(R)})))}}};Sf.default=V1});var i$=B(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var $f=me(),H1=$e(),K1=el(),W1={message:"must be equal to constant",params:({schemaCode:t})=>(0,$f._)`{allowedValue: ${t}}`},G1={keyword:"const",$data:!0,error:W1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,$f._)`!${(0,H1.useFunc)(e,K1.default)}(${r}, ${o})`):t.fail((0,$f._)`${s} !== ${r}`)}};Tf.default=G1});var a$=B(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var xi=me(),J1=$e(),Y1=el(),X1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,xi._)`{allowedValues: ${t}}`},Q1={keyword:"enum",schemaType:"array",$data:!0,error:X1,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,J1.useFunc)(e,Y1.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);u=(0,xi.or)(...o.map((m,w)=>b(f,w)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,f=>e.if((0,xi._)`${l()}(${r}, ${f})`,()=>e.assign(u,!0).break()))}function b(f,m){let w=o[m];return typeof w=="object"&&w!==null?(0,xi._)`${l()}(${r}, ${f}[${m}])`:(0,xi._)`${r} === ${w}`}}};Rf.default=Q1});var c$=B(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var eM=GS(),tM=JS(),rM=QS(),nM=e$(),oM=t$(),sM=r$(),iM=n$(),aM=s$(),cM=i$(),lM=a$(),uM=[eM.default,tM.default,rM.default,nM.default,oM.default,sM.default,iM.default,aM.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},cM.default,lM.default];Ef.default=uM});var Af=B(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.validateAdditionalItems=void 0;var eo=me(),Pf=$e(),dM={message:({params:{len:t}})=>(0,eo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,eo._)`{limit: ${t}}`},pM={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:dM,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Pf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}l$(t,n)}};function l$(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,eo._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,eo._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Pf.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,eo._)`${a} <= ${e.length}`);r.if((0,eo.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Pf.Type.Num},l),i.allErrors||r.if((0,eo.not)(l),()=>r.break())})}}Si.validateAdditionalItems=l$;Si.default=pM});var Cf=B($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.validateTuple=void 0;var u$=me(),tl=$e(),hM=Wt(),mM={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return d$(t,"additionalItems",e);r.items=!0,!(0,tl.alwaysValidSchema)(r,e)&&t.ok((0,hM.validateArray)(t))}};function d$(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=tl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,u$._)`${s}.length`);r.forEach((p,b)=>{(0,tl.alwaysValidSchema)(a,p)||(n.if((0,u$._)`${l} > ${b}`,()=>t.subschema({keyword:i,schemaProp:b,dataProp:b},c)),t.ok(c))});function u(p){let{opts:b,errSchemaPath:f}=a,m=r.length,w=m===p.minItems&&(m===p.maxItems||p[e]===!1);if(b.strictTuples&&!w){let $=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,tl.checkStrictMode)(a,$,b.strictTuples)}}}$i.validateTuple=d$;$i.default=mM});var p$=B(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var fM=Cf(),gM={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,fM.validateTuple)(t,"items")};If.default=gM});var m$=B(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var h$=me(),yM=$e(),bM=Wt(),wM=Af(),_M={message:({params:{len:t}})=>(0,h$.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,h$._)`{limit: ${t}}`},vM={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_M,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,yM.alwaysValidSchema)(n,e)&&(o?(0,wM.validateAdditionalItems)(t,o):t.ok((0,bM.validateArray)(t)))}};Of.default=vM});var f$=B(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var Jt=me(),rl=$e(),kM={message:({params:{min:t,max:e}})=>e===void 0?(0,Jt.str)`must contain at least ${t} valid item(s)`:(0,Jt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Jt._)`{minContains: ${t}}`:(0,Jt._)`{minContains: ${t}, maxContains: ${e}}`},xM={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:kM,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,Jt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,rl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,rl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,rl.alwaysValidSchema)(s,r)){let w=(0,Jt._)`${u} >= ${i}`;a!==void 0&&(w=(0,Jt._)`${w} && ${u} <= ${a}`),t.pass(w);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?f(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,Jt._)`${o}.length > 0`,b)):(e.let(p,!1),b()),t.result(p,()=>t.reset());function b(){let w=e.name("_valid"),$=e.let("count",0);f(w,()=>e.if(w,()=>m($)))}function f(w,$){e.forRange("i",0,u,R=>{t.subschema({keyword:"contains",dataProp:R,dataPropType:rl.Type.Num,compositeRule:!0},w),$()})}function m(w){e.code((0,Jt._)`${w}++`),a===void 0?e.if((0,Jt._)`${w} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,Jt._)`${w} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,Jt._)`${w} >= ${i}`,()=>e.assign(p,!0)))}}};Nf.default=xM});var b$=B(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateSchemaDeps=xr.validatePropertyDeps=xr.error=void 0;var Lf=me(),SM=$e(),Ti=Wt();xr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Lf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Lf._)`{property: ${t},
|
|
2355
2355
|
missingProperty: ${n},
|
|
2356
2356
|
depsCount: ${e},
|
|
2357
|
-
deps: ${r}}`};var bM={keyword:"dependencies",type:"object",schemaType:"object",error:xr.error,code(t){let[e,r]=wM(t);p$(t,e),h$(t,r)}};function wM({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function p$(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Si.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,Si.checkReportMissingProp)(t,l)}):(r.if((0,Nf._)`${c} && (${(0,Si.checkMissingProp)(t,a,s)})`),(0,Si.reportMissingProp)(t,s),r.else())}}xr.validatePropertyDeps=p$;function h$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,yM.alwaysValidSchema)(s,e[a])||(r.if((0,Si.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}xr.validateSchemaDeps=h$;xr.default=bM});var g$=B(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var f$=me(),_M=$e(),vM={message:"property name must be valid",params:({params:t})=>(0,f$._)`{propertyName: ${t.propertyName}}`},kM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:vM,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,_M.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,f$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Lf.default=kM});var jf=B(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var rl=Wt(),lr=me(),xM=Dr(),nl=$e(),SM={message:"must NOT have additional properties",params:({params:t})=>(0,lr._)`{additionalProperty: ${t.additionalProperty}}`},$M={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:SM,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,nl.alwaysValidSchema)(i,r))return;let l=(0,rl.allSchemaProperties)(n.properties),u=(0,rl.allSchemaProperties)(n.patternProperties);p(),t.ok((0,lr._)`${s} === ${xM.default.errors}`);function p(){e.forIn("key",o,S=>{!l.length&&!u.length?h(S):e.if(b(S),()=>h(S))})}function b(S){let R;if(l.length>8){let A=(0,nl.schemaRefOrVal)(i,n.properties,"properties");R=(0,rl.isOwnProperty)(e,A,S)}else l.length?R=(0,lr.or)(...l.map(A=>(0,lr._)`${S} === ${A}`)):R=lr.nil;return u.length&&(R=(0,lr.or)(R,...u.map(A=>(0,lr._)`${(0,rl.usePattern)(t,A)}.test(${S})`))),(0,lr.not)(R)}function f(S){e.code((0,lr._)`delete ${o}[${S}]`)}function h(S){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(S);return}if(r===!1){t.setParams({additionalProperty:S}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,nl.alwaysValidSchema)(i,r)){let R=e.name("valid");c.removeAdditional==="failing"?(w(S,R,!1),e.if((0,lr.not)(R),()=>{t.reset(),f(S)})):(w(S,R),a||e.if((0,lr.not)(R),()=>e.break()))}}function w(S,R,A){let L={keyword:"additionalProperties",dataProp:S,dataPropType:nl.Type.Str};A===!1&&Object.assign(L,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(L,R)}}};zf.default=$M});var w$=B(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var TM=ui(),y$=Wt(),Df=$e(),b$=jf(),RM={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&b$.default.code(new TM.KeywordCxt(s,b$.default,"additionalProperties"));let i=(0,y$.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Df.mergeEvaluated.props(e,(0,Df.toHash)(i),s.props));let a=i.filter(p=>!(0,Df.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,y$.propertyInData)(e,o,p,s.opts.ownProperties)),u(p),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function u(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Mf.default=RM});var x$=B(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var _$=Wt(),ol=me(),v$=$e(),k$=$e(),EM={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,_$.allSchemaProperties)(r),c=a.filter(w=>(0,v$.alwaysValidSchema)(s,r[w]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof ol.Name)&&(s.props=(0,k$.evaluatedPropsToName)(e,s.props));let{props:p}=s;b();function b(){for(let w of a)l&&f(w),s.allErrors?h(w):(e.var(u,!0),h(w),e.if(u))}function f(w){for(let S in l)new RegExp(w).test(S)&&(0,v$.checkStrictMode)(s,`property ${S} matches pattern ${w} (use allowMatchingProperties)`)}function h(w){e.forIn("key",n,S=>{e.if((0,ol._)`${(0,_$.usePattern)(t,w)}.test(${S})`,()=>{let R=c.includes(w);R||t.subschema({keyword:"patternProperties",schemaProp:w,dataProp:S,dataPropType:k$.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,ol._)`${p}[${S}]`,!0):!R&&!s.allErrors&&e.if((0,ol.not)(u),()=>e.break())})})}}};Uf.default=EM});var S$=B(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var PM=$e(),AM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,PM.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};qf.default=AM});var $$=B(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var CM=Wt(),IM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:CM.validateUnion,error:{message:"must match a schema in anyOf"}};Ff.default=IM});var T$=B(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var sl=me(),OM=$e(),NM={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,sl._)`{passingSchemas: ${t.passing}}`},LM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:NM,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){s.forEach((u,p)=>{let b;(0,OM.alwaysValidSchema)(o,u)?e.var(c,!0):b=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,sl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,sl._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),b&&t.mergeEvaluated(b,sl.Name)})})}}};Bf.default=LM});var R$=B(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var zM=$e(),jM={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,zM.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Zf.default=jM});var A$=B(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var il=me(),P$=$e(),DM={message:({params:t})=>(0,il.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,il._)`{failingKeyword: ${t.ifClause}}`},MM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:DM,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,P$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=E$(n,"then"),s=E$(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,il.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,p){return()=>{let b=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(b,i),p?e.assign(p,(0,il._)`${u}`):t.setParams({ifClause:u})}}}};function E$(t,e){let r=t.schema[e];return r!==void 0&&!(0,P$.alwaysValidSchema)(t,r)}Vf.default=MM});var C$=B(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var UM=$e(),qM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,UM.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Hf.default=qM});var I$=B(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var FM=Pf(),BM=c$(),ZM=Af(),VM=u$(),HM=d$(),KM=m$(),WM=g$(),GM=jf(),JM=w$(),YM=x$(),XM=S$(),QM=$$(),eU=T$(),tU=R$(),rU=A$(),nU=C$();function oU(t=!1){let e=[XM.default,QM.default,eU.default,tU.default,rU.default,nU.default,WM.default,GM.default,KM.default,JM.default,YM.default];return t?e.push(BM.default,VM.default):e.push(FM.default,ZM.default),e.push(HM.default),e}Kf.default=oU});var O$=B(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var Ye=me(),sU={message:({schemaCode:t})=>(0,Ye.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ye._)`{format: ${t}}`},iU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:sU,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;o?b():f();function b(){let h=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),w=r.const("fDef",(0,Ye._)`${h}[${i}]`),S=r.let("fType"),R=r.let("format");r.if((0,Ye._)`typeof ${w} == "object" && !(${w} instanceof RegExp)`,()=>r.assign(S,(0,Ye._)`${w}.type || "string"`).assign(R,(0,Ye._)`${w}.validate`),()=>r.assign(S,(0,Ye._)`"string"`).assign(R,w)),t.fail$data((0,Ye.or)(A(),L()));function A(){return c.strictSchema===!1?Ye.nil:(0,Ye._)`${i} && !${R}`}function L(){let F=u.$async?(0,Ye._)`(${w}.async ? await ${R}(${n}) : ${R}(${n}))`:(0,Ye._)`${R}(${n})`,W=(0,Ye._)`(typeof ${R} == "function" ? ${F} : ${R}.test(${n}))`;return(0,Ye._)`${R} && ${R} !== true && ${S} === ${e} && !${W}`}}function f(){let h=p.formats[s];if(!h){A();return}if(h===!0)return;let[w,S,R]=L(h);w===e&&t.pass(F());function A(){if(c.strictSchema===!1){p.logger.warn(W());return}throw new Error(W());function W(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function L(W){let Ke=W instanceof RegExp?(0,Ye.regexpCode)(W):c.code.formats?(0,Ye._)`${c.code.formats}${(0,Ye.getProperty)(s)}`:void 0,Je=r.scopeValue("formats",{key:s,ref:W,code:Ke});return typeof W=="object"&&!(W instanceof RegExp)?[W.type||"string",W.validate,(0,Ye._)`${Je}.validate`]:["string",W,Je]}function F(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ye._)`await ${R}(${n})`}return typeof S=="function"?(0,Ye._)`${R}(${n})`:(0,Ye._)`${R}.test(${n})`}}}};Wf.default=iU});var N$=B(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var aU=O$(),cU=[aU.default];Gf.default=cU});var L$=B(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.contentVocabulary=Ho.metadataVocabulary=void 0;Ho.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ho.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var j$=B(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var lU=ZS(),uU=o$(),dU=I$(),pU=N$(),z$=L$(),hU=[lU.default,uU.default,(0,dU.default)(),pU.default,z$.metadataVocabulary,z$.contentVocabulary];Jf.default=hU});var M$=B(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.DiscrError=void 0;var D$;(function(t){t.Tag="tag",t.Mapping="mapping"})(D$||(al.DiscrError=D$={}))});var q$=B(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var Ko=me(),Yf=M$(),U$=Fc(),mU=di(),fU=$e(),gU={message:({params:{discrError:t,tagName:e}})=>t===Yf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Ko._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},yU={keyword:"discriminator",type:"object",schemaType:"object",error:gU,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Ko._)`${r}${(0,Ko.getProperty)(a)}`);e.if((0,Ko._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Yf.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let f=b();e.if(!1);for(let h in f)e.elseIf((0,Ko._)`${l} === ${h}`),e.assign(c,p(f[h]));e.else(),t.error(!1,{discrError:Yf.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(f){let h=e.name("valid"),w=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(w,Ko.Name),h}function b(){var f;let h={},w=R(o),S=!0;for(let F=0;F<i.length;F++){let W=i[F];if(W?.$ref&&!(0,fU.schemaHasRulesButRef)(W,s.self.RULES)){let Je=W.$ref;if(W=U$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Je),W instanceof U$.SchemaEnv&&(W=W.schema),W===void 0)throw new mU.default(s.opts.uriResolver,s.baseId,Je)}let Ke=(f=W?.properties)===null||f===void 0?void 0:f[a];if(typeof Ke!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);S=S&&(w||R(W)),A(Ke,F)}if(!S)throw new Error(`discriminator: "${a}" must be required`);return h;function R({required:F}){return Array.isArray(F)&&F.includes(a)}function A(F,W){if(F.const)L(F.const,W);else if(F.enum)for(let Ke of F.enum)L(Ke,W);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function L(F,W){if(typeof F!="string"||F in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[F]=W}}}};Xf.default=yU});var F$=B((YW,bU)=>{bU.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var eg=B((qe,Qf)=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.MissingRefError=qe.ValidationError=qe.CodeGen=qe.Name=qe.nil=qe.stringify=qe.str=qe._=qe.KeywordCxt=qe.Ajv=void 0;var wU=DS(),_U=j$(),vU=q$(),B$=F$(),kU=["/properties"],cl="http://json-schema.org/draft-07/schema",Wo=class extends wU.default{_addVocabularies(){super._addVocabularies(),_U.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(vU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(B$,kU):B$;this.addMetaSchema(e,cl,!1),this.refs["http://json-schema.org/schema"]=cl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(cl)?cl:void 0)}};qe.Ajv=Wo;Qf.exports=qe=Wo;Qf.exports.Ajv=Wo;Object.defineProperty(qe,"__esModule",{value:!0});qe.default=Wo;var xU=ui();Object.defineProperty(qe,"KeywordCxt",{enumerable:!0,get:function(){return xU.KeywordCxt}});var Go=me();Object.defineProperty(qe,"_",{enumerable:!0,get:function(){return Go._}});Object.defineProperty(qe,"str",{enumerable:!0,get:function(){return Go.str}});Object.defineProperty(qe,"stringify",{enumerable:!0,get:function(){return Go.stringify}});Object.defineProperty(qe,"nil",{enumerable:!0,get:function(){return Go.nil}});Object.defineProperty(qe,"Name",{enumerable:!0,get:function(){return Go.Name}});Object.defineProperty(qe,"CodeGen",{enumerable:!0,get:function(){return Go.CodeGen}});var SU=Uc();Object.defineProperty(qe,"ValidationError",{enumerable:!0,get:function(){return SU.default}});var $U=di();Object.defineProperty(qe,"MissingRefError",{enumerable:!0,get:function(){return $U.default}})});var Y$=B($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.formatNames=$r.fastFormats=$r.fullFormats=void 0;function Sr(t,e){return{validate:t,compare:e}}$r.fullFormats={date:Sr(K$,og),time:Sr(rg(!0),sg),"date-time":Sr(Z$(!0),G$),"iso-time":Sr(rg(),W$),"iso-date-time":Sr(Z$(),J$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:CU,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:DU,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:IU,int32:{type:"number",validate:LU},int64:{type:"number",validate:zU},float:{type:"number",validate:H$},double:{type:"number",validate:H$},password:!0,binary:!0};$r.fastFormats={...$r.fullFormats,date:Sr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,og),time:Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,sg),"date-time":Sr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,G$),"iso-time":Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,W$),"iso-date-time":Sr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,J$),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};$r.formatNames=Object.keys($r.fullFormats);function TU(t){return t%4===0&&(t%100!==0||t%400===0)}var RU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,EU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function K$(t){let e=RU.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&TU(r)?29:EU[n])}function og(t,e){if(t&&e)return t>e?1:t<e?-1:0}var tg=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function rg(t){return function(r){let n=tg.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let p=s-u*c,b=o-l*c-(p<0?1:0);return(b===23||b===-1)&&(p===59||p===-1)&&i<61}}function sg(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function W$(t,e){if(!(t&&e))return;let r=tg.exec(t),n=tg.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var ng=/t|\s/i;function Z$(t){let e=rg(t);return function(n){let o=n.split(ng);return o.length===2&&K$(o[0])&&e(o[1])}}function G$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function J$(t,e){if(!(t&&e))return;let[r,n]=t.split(ng),[o,s]=e.split(ng),i=og(r,o);if(i!==void 0)return i||sg(n,s)}var PU=/\/|:/,AU=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function CU(t){return PU.test(t)&&AU.test(t)}var V$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function IU(t){return V$.lastIndex=0,V$.test(t)}var OU=-(2**31),NU=2**31-1;function LU(t){return Number.isInteger(t)&&t<=NU&&t>=OU}function zU(t){return Number.isInteger(t)}function H$(){return!0}var jU=/[^\\]\\Z/;function DU(t){if(jU.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var X$=B(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.formatLimitDefinition=void 0;var MU=eg(),ur=me(),pn=ur.operators,ll={formatMaximum:{okStr:"<=",ok:pn.LTE,fail:pn.GT},formatMinimum:{okStr:">=",ok:pn.GTE,fail:pn.LT},formatExclusiveMaximum:{okStr:"<",ok:pn.LT,fail:pn.GTE},formatExclusiveMinimum:{okStr:">",ok:pn.GT,fail:pn.LTE}},UU={message:({keyword:t,schemaCode:e})=>(0,ur.str)`should be ${ll[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ur._)`{comparison: ${ll[t].okStr}, limit: ${e}}`};Jo.formatLimitDefinition={keyword:Object.keys(ll),type:"string",schemaType:"string",$data:!0,error:UU,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new MU.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let b=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,ur._)`${b}[${c.schemaCode}]`);t.fail$data((0,ur.or)((0,ur._)`typeof ${f} != "object"`,(0,ur._)`${f} instanceof RegExp`,(0,ur._)`typeof ${f}.compare != "function"`,p(f)))}function u(){let b=c.schema,f=a.formats[b];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${b}" does not define "compare" function`);let h=e.scopeValue("formats",{key:b,ref:f,code:i.code.formats?(0,ur._)`${i.code.formats}${(0,ur.getProperty)(b)}`:void 0});t.fail$data(p(h))}function p(b){return(0,ur._)`${b}.compare(${r}, ${n}) ${ll[o].fail} 0`}},dependencies:["format"]};var qU=t=>(t.addKeyword(Jo.formatLimitDefinition),t);Jo.default=qU});var rT=B(($i,tT)=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});var Yo=Y$(),FU=X$(),ig=me(),Q$=new ig.Name("fullFormats"),BU=new ig.Name("fastFormats"),ag=(t,e={keywords:!0})=>{if(Array.isArray(e))return eT(t,e,Yo.fullFormats,Q$),t;let[r,n]=e.mode==="fast"?[Yo.fastFormats,BU]:[Yo.fullFormats,Q$],o=e.formats||Yo.formatNames;return eT(t,o,r,n),e.keywords&&(0,FU.default)(t),t};ag.get=(t,e="full")=>{let n=(e==="fast"?Yo.fastFormats:Yo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function eT(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,ig._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}tT.exports=$i=ag;Object.defineProperty($i,"__esModule",{value:!0});$i.default=ag});function ZU(){let t=new nT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,oT.default)(t),t}var nT,oT,ul,sT=O(()=>{nT=Sl(eg(),1),oT=Sl(rT(),1);ul=class{constructor(e){this._ajv=e??ZU()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var dl,iT=O(()=>{No();dl=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(b=>b.type==="tool_use").map(b=>b.id)),p=new Set(s.filter(b=>b.type==="tool_result").map(b=>b.toolUseId));if(u.size!==p.size||![...u].every(b=>p.has(b)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Gs,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Oo,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function aT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function cT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var lT=O(()=>{});var pl,uT=O(()=>{hx();No();sT();js();iT();lT();pl=class extends Rc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ws.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new ul,this.setRequestHandler(_h,n=>this._oninitialize(n)),this.setNotificationHandler(vh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Eh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ws.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new dl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=px(this._capabilities,e)}setRequestHandler(e,r){let o=en(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Eo(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,l)=>{let u=Qr(Io,c);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new J(ee.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:p}=u.data,b=await Promise.resolve(r(c,l));if(p.task){let h=Qr(Ao,b);if(!h.success){let w=h.error instanceof Error?h.error.message:String(h.error);throw new J(ee.InvalidParams,`Invalid task creation result: ${w}`)}return h.data}let f=Qr(fc,b);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new J(ee.InvalidParams,`Invalid tools/call result: ${h}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){cT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&aT(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:pk.includes(r)?r:fh,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Qa)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(l=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Ph,r):this.request({method:"sampling/createMessage",params:e},Gs,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Oo,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Oo,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new J(ee.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof J?i:new J(ee.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Ah,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function cg(t){return!!t&&typeof t=="object"&&pT in t}function hT(t){return t[pT]?.complete}var pT,dT,mT=O(()=>{pT=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(dT||(dT={}))});var fT=O(()=>{});function HU(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!VU.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function KU(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function lg(t){let e=HU(t);return KU(t,e.warnings),e.isValid}var VU,gT=O(()=>{VU=/^[A-Za-z0-9._-]{1,128}$/});var hl,yT=O(()=>{hl=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});function _T(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function vT(t){return"_def"in t||"_zod"in t||_T(t)}function ug(t){return typeof t!="object"||t===null||vT(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(_T)}function bT(t){if(t){if(ug(t))return Bn(t);if(!vT(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function GU(t){let e=en(t);return e?Object.entries(e).map(([r,n])=>{let o=jv(n),s=Dv(n);return{name:r,description:o,required:!s}}):[]}function hn(t){let r=en(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Eo(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function wT(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ml,WU,Ti,kT=O(()=>{uT();js();hm();No();mT();fT();gT();yT();On();ml=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new pl(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new hl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(hn(mc)),this.server.assertCanSetRequestHandler(hn(Io)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(mc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Ro(r.inputSchema);return o?um(o,{strictUnions:!0,pipeStrategy:"input"}):WU})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Ro(r.outputSchema);o&&(n.outputSchema=um(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Io,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new J(ee.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new J(ee.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new J(ee.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new J(ee.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof J&&n.code===ee.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Ro(e.inputSchema)??e.inputSchema,i=await Ha(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ka(a);throw new J(ee.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new J(ee.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Ro(e.outputSchema),s=await Ha(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ka(i);throw new J(ee.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(b=>setTimeout(b,u));let p=await n.taskStore.getTask(c);if(!p)throw new J(ee.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(hn(gc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(gc,async e=>{switch(e.params.ref.type){case"ref/prompt":return Ek(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Pk(e),this.handleResourceCompletion(e,e.params.ref);default:throw new J(ee.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new J(ee.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new J(ee.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ti;let s=en(n.argsSchema)?.[e.params.argument.name];if(!cg(s))return Ti;let i=hT(s);if(!i)return Ti;let a=await i(e.params.argument.value,e.params.context);return wT(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Ti;throw new J(ee.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Ti;let s=await o(e.params.argument.value,e.params.context);return wT(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(hn(lc)),this.server.assertCanSetRequestHandler(hn(uc)),this.server.assertCanSetRequestHandler(hn(dc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(lc,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(uc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(dc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new J(ee.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new J(ee.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(hn(pc)),this.server.assertCanSetRequestHandler(hn(hc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(pc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?GU(r.argsSchema):void 0}))})),this.server.setRequestHandler(hc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new J(ee.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new J(ee.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Ro(n.argsSchema),s=await Ha(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Ka(c);throw new J(ee.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Bn(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Bn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let l=c instanceof xt?c._def?.innerType:c;return cg(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){lg(e);let u={title:r,description:n,inputSchema:bT(o),outputSchema:bT(s),annotations:i,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&lg(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Bn(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Bn(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(ug(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!ug(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},WU={type:"object",properties:{}};Ti={completion:{values:[],hasMore:!1}}});function YU(t){return _k.parse(JSON.parse(t))}function xT(t){return JSON.stringify(t)+`
|
|
2358
|
-
`}var
|
|
2359
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
2357
|
+
deps: ${r}}`};var $M={keyword:"dependencies",type:"object",schemaType:"object",error:xr.error,code(t){let[e,r]=TM(t);g$(t,e),y$(t,r)}};function TM({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function g$(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ti.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,Ti.checkReportMissingProp)(t,l)}):(r.if((0,Lf._)`${c} && (${(0,Ti.checkMissingProp)(t,a,s)})`),(0,Ti.reportMissingProp)(t,s),r.else())}}xr.validatePropertyDeps=g$;function y$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,SM.alwaysValidSchema)(s,e[a])||(r.if((0,Ti.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}xr.validateSchemaDeps=y$;xr.default=$M});var _$=B(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var w$=me(),RM=$e(),EM={message:"property name must be valid",params:({params:t})=>(0,w$._)`{propertyName: ${t.propertyName}}`},PM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:EM,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,RM.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,w$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};jf.default=PM});var Df=B(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var nl=Wt(),lr=me(),AM=Dr(),ol=$e(),CM={message:"must NOT have additional properties",params:({params:t})=>(0,lr._)`{additionalProperty: ${t.additionalProperty}}`},IM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:CM,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,ol.alwaysValidSchema)(i,r))return;let l=(0,nl.allSchemaProperties)(n.properties),u=(0,nl.allSchemaProperties)(n.patternProperties);p(),t.ok((0,lr._)`${s} === ${AM.default.errors}`);function p(){e.forIn("key",o,$=>{!l.length&&!u.length?m($):e.if(b($),()=>m($))})}function b($){let R;if(l.length>8){let A=(0,ol.schemaRefOrVal)(i,n.properties,"properties");R=(0,nl.isOwnProperty)(e,A,$)}else l.length?R=(0,lr.or)(...l.map(A=>(0,lr._)`${$} === ${A}`)):R=lr.nil;return u.length&&(R=(0,lr.or)(R,...u.map(A=>(0,lr._)`${(0,nl.usePattern)(t,A)}.test(${$})`))),(0,lr.not)(R)}function f($){e.code((0,lr._)`delete ${o}[${$}]`)}function m($){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f($);return}if(r===!1){t.setParams({additionalProperty:$}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ol.alwaysValidSchema)(i,r)){let R=e.name("valid");c.removeAdditional==="failing"?(w($,R,!1),e.if((0,lr.not)(R),()=>{t.reset(),f($)})):(w($,R),a||e.if((0,lr.not)(R),()=>e.break()))}}function w($,R,A){let L={keyword:"additionalProperties",dataProp:$,dataPropType:ol.Type.Str};A===!1&&Object.assign(L,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(L,R)}}};zf.default=IM});var x$=B(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var OM=pi(),v$=Wt(),Mf=$e(),k$=Df(),NM={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&k$.default.code(new OM.KeywordCxt(s,k$.default,"additionalProperties"));let i=(0,v$.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Mf.mergeEvaluated.props(e,(0,Mf.toHash)(i),s.props));let a=i.filter(p=>!(0,Mf.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,v$.propertyInData)(e,o,p,s.opts.ownProperties)),u(p),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function u(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Uf.default=NM});var R$=B(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var S$=Wt(),sl=me(),$$=$e(),T$=$e(),LM={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,S$.allSchemaProperties)(r),c=a.filter(w=>(0,$$.alwaysValidSchema)(s,r[w]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof sl.Name)&&(s.props=(0,T$.evaluatedPropsToName)(e,s.props));let{props:p}=s;b();function b(){for(let w of a)l&&f(w),s.allErrors?m(w):(e.var(u,!0),m(w),e.if(u))}function f(w){for(let $ in l)new RegExp(w).test($)&&(0,$$.checkStrictMode)(s,`property ${$} matches pattern ${w} (use allowMatchingProperties)`)}function m(w){e.forIn("key",n,$=>{e.if((0,sl._)`${(0,S$.usePattern)(t,w)}.test(${$})`,()=>{let R=c.includes(w);R||t.subschema({keyword:"patternProperties",schemaProp:w,dataProp:$,dataPropType:T$.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,sl._)`${p}[${$}]`,!0):!R&&!s.allErrors&&e.if((0,sl.not)(u),()=>e.break())})})}}};qf.default=LM});var E$=B(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var jM=$e(),zM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,jM.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Ff.default=zM});var P$=B(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var DM=Wt(),MM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:DM.validateUnion,error:{message:"must match a schema in anyOf"}};Bf.default=MM});var A$=B(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var il=me(),UM=$e(),qM={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,il._)`{passingSchemas: ${t.passing}}`},FM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:qM,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){s.forEach((u,p)=>{let b;(0,UM.alwaysValidSchema)(o,u)?e.var(c,!0):b=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,il._)`${c} && ${i}`).assign(i,!1).assign(a,(0,il._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),b&&t.mergeEvaluated(b,il.Name)})})}}};Zf.default=FM});var C$=B(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var BM=$e(),ZM={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,BM.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Vf.default=ZM});var N$=B(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var al=me(),O$=$e(),VM={message:({params:t})=>(0,al.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,al._)`{failingKeyword: ${t.ifClause}}`},HM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:VM,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,O$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=I$(n,"then"),s=I$(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,al.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,p){return()=>{let b=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(b,i),p?e.assign(p,(0,al._)`${u}`):t.setParams({ifClause:u})}}}};function I$(t,e){let r=t.schema[e];return r!==void 0&&!(0,O$.alwaysValidSchema)(t,r)}Hf.default=HM});var L$=B(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var KM=$e(),WM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,KM.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Kf.default=WM});var j$=B(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var GM=Af(),JM=p$(),YM=Cf(),XM=m$(),QM=f$(),eU=b$(),tU=_$(),rU=Df(),nU=x$(),oU=R$(),sU=E$(),iU=P$(),aU=A$(),cU=C$(),lU=N$(),uU=L$();function dU(t=!1){let e=[sU.default,iU.default,aU.default,cU.default,lU.default,uU.default,tU.default,rU.default,eU.default,nU.default,oU.default];return t?e.push(JM.default,XM.default):e.push(GM.default,YM.default),e.push(QM.default),e}Wf.default=dU});var z$=B(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var Ye=me(),pU={message:({schemaCode:t})=>(0,Ye.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ye._)`{format: ${t}}`},hU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:pU,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;o?b():f();function b(){let m=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),w=r.const("fDef",(0,Ye._)`${m}[${i}]`),$=r.let("fType"),R=r.let("format");r.if((0,Ye._)`typeof ${w} == "object" && !(${w} instanceof RegExp)`,()=>r.assign($,(0,Ye._)`${w}.type || "string"`).assign(R,(0,Ye._)`${w}.validate`),()=>r.assign($,(0,Ye._)`"string"`).assign(R,w)),t.fail$data((0,Ye.or)(A(),L()));function A(){return c.strictSchema===!1?Ye.nil:(0,Ye._)`${i} && !${R}`}function L(){let F=u.$async?(0,Ye._)`(${w}.async ? await ${R}(${n}) : ${R}(${n}))`:(0,Ye._)`${R}(${n})`,W=(0,Ye._)`(typeof ${R} == "function" ? ${F} : ${R}.test(${n}))`;return(0,Ye._)`${R} && ${R} !== true && ${$} === ${e} && !${W}`}}function f(){let m=p.formats[s];if(!m){A();return}if(m===!0)return;let[w,$,R]=L(m);w===e&&t.pass(F());function A(){if(c.strictSchema===!1){p.logger.warn(W());return}throw new Error(W());function W(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function L(W){let Ke=W instanceof RegExp?(0,Ye.regexpCode)(W):c.code.formats?(0,Ye._)`${c.code.formats}${(0,Ye.getProperty)(s)}`:void 0,Je=r.scopeValue("formats",{key:s,ref:W,code:Ke});return typeof W=="object"&&!(W instanceof RegExp)?[W.type||"string",W.validate,(0,Ye._)`${Je}.validate`]:["string",W,Je]}function F(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ye._)`await ${R}(${n})`}return typeof $=="function"?(0,Ye._)`${R}(${n})`:(0,Ye._)`${R}.test(${n})`}}}};Gf.default=hU});var D$=B(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var mU=z$(),fU=[mU.default];Jf.default=fU});var M$=B(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.contentVocabulary=Wo.metadataVocabulary=void 0;Wo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Wo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var q$=B(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var gU=WS(),yU=c$(),bU=j$(),wU=D$(),U$=M$(),_U=[gU.default,yU.default,(0,bU.default)(),wU.default,U$.metadataVocabulary,U$.contentVocabulary];Yf.default=_U});var B$=B(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.DiscrError=void 0;var F$;(function(t){t.Tag="tag",t.Mapping="mapping"})(F$||(cl.DiscrError=F$={}))});var V$=B(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var Go=me(),Xf=B$(),Z$=Bc(),vU=hi(),kU=$e(),xU={message:({params:{discrError:t,tagName:e}})=>t===Xf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Go._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},SU={keyword:"discriminator",type:"object",schemaType:"object",error:xU,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Go._)`${r}${(0,Go.getProperty)(a)}`);e.if((0,Go._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Xf.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let f=b();e.if(!1);for(let m in f)e.elseIf((0,Go._)`${l} === ${m}`),e.assign(c,p(f[m]));e.else(),t.error(!1,{discrError:Xf.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(f){let m=e.name("valid"),w=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(w,Go.Name),m}function b(){var f;let m={},w=R(o),$=!0;for(let F=0;F<i.length;F++){let W=i[F];if(W?.$ref&&!(0,kU.schemaHasRulesButRef)(W,s.self.RULES)){let Je=W.$ref;if(W=Z$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Je),W instanceof Z$.SchemaEnv&&(W=W.schema),W===void 0)throw new vU.default(s.opts.uriResolver,s.baseId,Je)}let Ke=(f=W?.properties)===null||f===void 0?void 0:f[a];if(typeof Ke!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(w||R(W)),A(Ke,F)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return m;function R({required:F}){return Array.isArray(F)&&F.includes(a)}function A(F,W){if(F.const)L(F.const,W);else if(F.enum)for(let Ke of F.enum)L(Ke,W);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function L(F,W){if(typeof F!="string"||F in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[F]=W}}}};Qf.default=SU});var H$=B((sG,$U)=>{$U.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var tg=B((qe,eg)=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.MissingRefError=qe.ValidationError=qe.CodeGen=qe.Name=qe.nil=qe.stringify=qe.str=qe._=qe.KeywordCxt=qe.Ajv=void 0;var TU=FS(),RU=q$(),EU=V$(),K$=H$(),PU=["/properties"],ll="http://json-schema.org/draft-07/schema",Jo=class extends TU.default{_addVocabularies(){super._addVocabularies(),RU.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(EU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(K$,PU):K$;this.addMetaSchema(e,ll,!1),this.refs["http://json-schema.org/schema"]=ll}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ll)?ll:void 0)}};qe.Ajv=Jo;eg.exports=qe=Jo;eg.exports.Ajv=Jo;Object.defineProperty(qe,"__esModule",{value:!0});qe.default=Jo;var AU=pi();Object.defineProperty(qe,"KeywordCxt",{enumerable:!0,get:function(){return AU.KeywordCxt}});var Yo=me();Object.defineProperty(qe,"_",{enumerable:!0,get:function(){return Yo._}});Object.defineProperty(qe,"str",{enumerable:!0,get:function(){return Yo.str}});Object.defineProperty(qe,"stringify",{enumerable:!0,get:function(){return Yo.stringify}});Object.defineProperty(qe,"nil",{enumerable:!0,get:function(){return Yo.nil}});Object.defineProperty(qe,"Name",{enumerable:!0,get:function(){return Yo.Name}});Object.defineProperty(qe,"CodeGen",{enumerable:!0,get:function(){return Yo.CodeGen}});var CU=qc();Object.defineProperty(qe,"ValidationError",{enumerable:!0,get:function(){return CU.default}});var IU=hi();Object.defineProperty(qe,"MissingRefError",{enumerable:!0,get:function(){return IU.default}})});var tT=B($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.formatNames=$r.fastFormats=$r.fullFormats=void 0;function Sr(t,e){return{validate:t,compare:e}}$r.fullFormats={date:Sr(Y$,sg),time:Sr(ng(!0),ig),"date-time":Sr(W$(!0),Q$),"iso-time":Sr(ng(),X$),"iso-date-time":Sr(W$(),eT),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:DU,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:VU,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:MU,int32:{type:"number",validate:FU},int64:{type:"number",validate:BU},float:{type:"number",validate:J$},double:{type:"number",validate:J$},password:!0,binary:!0};$r.fastFormats={...$r.fullFormats,date:Sr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,sg),time:Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ig),"date-time":Sr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Q$),"iso-time":Sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,X$),"iso-date-time":Sr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,eT),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};$r.formatNames=Object.keys($r.fullFormats);function OU(t){return t%4===0&&(t%100!==0||t%400===0)}var NU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,LU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Y$(t){let e=NU.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&OU(r)?29:LU[n])}function sg(t,e){if(t&&e)return t>e?1:t<e?-1:0}var rg=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ng(t){return function(r){let n=rg.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let p=s-u*c,b=o-l*c-(p<0?1:0);return(b===23||b===-1)&&(p===59||p===-1)&&i<61}}function ig(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function X$(t,e){if(!(t&&e))return;let r=rg.exec(t),n=rg.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var og=/t|\s/i;function W$(t){let e=ng(t);return function(n){let o=n.split(og);return o.length===2&&Y$(o[0])&&e(o[1])}}function Q$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function eT(t,e){if(!(t&&e))return;let[r,n]=t.split(og),[o,s]=e.split(og),i=sg(r,o);if(i!==void 0)return i||ig(n,s)}var jU=/\/|:/,zU=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function DU(t){return jU.test(t)&&zU.test(t)}var G$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function MU(t){return G$.lastIndex=0,G$.test(t)}var UU=-(2**31),qU=2**31-1;function FU(t){return Number.isInteger(t)&&t<=qU&&t>=UU}function BU(t){return Number.isInteger(t)}function J$(){return!0}var ZU=/[^\\]\\Z/;function VU(t){if(ZU.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var rT=B(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.formatLimitDefinition=void 0;var HU=tg(),ur=me(),pn=ur.operators,ul={formatMaximum:{okStr:"<=",ok:pn.LTE,fail:pn.GT},formatMinimum:{okStr:">=",ok:pn.GTE,fail:pn.LT},formatExclusiveMaximum:{okStr:"<",ok:pn.LT,fail:pn.GTE},formatExclusiveMinimum:{okStr:">",ok:pn.GT,fail:pn.LTE}},KU={message:({keyword:t,schemaCode:e})=>(0,ur.str)`should be ${ul[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ur._)`{comparison: ${ul[t].okStr}, limit: ${e}}`};Xo.formatLimitDefinition={keyword:Object.keys(ul),type:"string",schemaType:"string",$data:!0,error:KU,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new HU.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let b=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,ur._)`${b}[${c.schemaCode}]`);t.fail$data((0,ur.or)((0,ur._)`typeof ${f} != "object"`,(0,ur._)`${f} instanceof RegExp`,(0,ur._)`typeof ${f}.compare != "function"`,p(f)))}function u(){let b=c.schema,f=a.formats[b];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${b}" does not define "compare" function`);let m=e.scopeValue("formats",{key:b,ref:f,code:i.code.formats?(0,ur._)`${i.code.formats}${(0,ur.getProperty)(b)}`:void 0});t.fail$data(p(m))}function p(b){return(0,ur._)`${b}.compare(${r}, ${n}) ${ul[o].fail} 0`}},dependencies:["format"]};var WU=t=>(t.addKeyword(Xo.formatLimitDefinition),t);Xo.default=WU});var iT=B((Ri,sT)=>{"use strict";Object.defineProperty(Ri,"__esModule",{value:!0});var Qo=tT(),GU=rT(),ag=me(),nT=new ag.Name("fullFormats"),JU=new ag.Name("fastFormats"),cg=(t,e={keywords:!0})=>{if(Array.isArray(e))return oT(t,e,Qo.fullFormats,nT),t;let[r,n]=e.mode==="fast"?[Qo.fastFormats,JU]:[Qo.fullFormats,nT],o=e.formats||Qo.formatNames;return oT(t,o,r,n),e.keywords&&(0,GU.default)(t),t};cg.get=(t,e="full")=>{let n=(e==="fast"?Qo.fastFormats:Qo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function oT(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,ag._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}sT.exports=Ri=cg;Object.defineProperty(Ri,"__esModule",{value:!0});Ri.default=cg});function YU(){let t=new aT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,cT.default)(t),t}var aT,cT,dl,lT=N(()=>{aT=$l(tg(),1),cT=$l(iT(),1);dl=class{constructor(e){this._ajv=e??YU()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var pl,uT=N(()=>{jo();pl=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(b=>b.type==="tool_use").map(b=>b.id)),p=new Set(s.filter(b=>b.type==="tool_result").map(b=>b.toolUseId));if(u.size!==p.size||![...u].every(b=>p.has(b)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ys,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Lo,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function dT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function pT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var hT=N(()=>{});var hl,mT=N(()=>{yx();jo();lT();Ms();uT();hT();hl=class extends Ec{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Js.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new dl,this.setRequestHandler(vh,n=>this._oninitialize(n)),this.setNotificationHandler(kh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ph,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Js.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new pl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=gx(this._capabilities,e)}setRequestHandler(e,r){let o=en(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Ao(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,l)=>{let u=Qr(No,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new Y(te.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,b=await Promise.resolve(r(c,l));if(p.task){let m=Qr(Io,b);if(!m.success){let w=m.error instanceof Error?m.error.message:String(m.error);throw new Y(te.InvalidParams,`Invalid task creation result: ${w}`)}return m.data}let f=Qr(gc,b);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new Y(te.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){pT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&dT(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:gk.includes(r)?r:gh,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ec)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(l=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Ah,r):this.request({method:"sampling/createMessage",params:e},Ys,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Lo,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Lo,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Y(te.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Y?i:new Y(te.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Ch,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function lg(t){return!!t&&typeof t=="object"&&gT in t}function yT(t){return t[gT]?.complete}var gT,fT,bT=N(()=>{gT=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(fT||(fT={}))});var wT=N(()=>{});function QU(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!XU.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function eq(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function ug(t){let e=QU(t);return eq(t,e.warnings),e.isValid}var XU,_T=N(()=>{XU=/^[A-Za-z0-9._-]{1,128}$/});var ml,vT=N(()=>{ml=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});function ST(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function $T(t){return"_def"in t||"_zod"in t||ST(t)}function dg(t){return typeof t!="object"||t===null||$T(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(ST)}function kT(t){if(t){if(dg(t))return Bn(t);if(!$T(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function rq(t){let e=en(t);return e?Object.entries(e).map(([r,n])=>{let o=qv(n),s=Fv(n);return{name:r,description:o,required:!s}}):[]}function hn(t){let r=en(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ao(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function xT(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var fl,tq,Ei,TT=N(()=>{mT();Ms();mm();jo();bT();wT();_T();vT();On();fl=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new hl(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ml(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(hn(fc)),this.server.assertCanSetRequestHandler(hn(No)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(fc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Po(r.inputSchema);return o?dm(o,{strictUnions:!0,pipeStrategy:"input"}):tq})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Po(r.outputSchema);o&&(n.outputSchema=dm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(No,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Y(te.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Y(te.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new Y(te.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Y(te.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof Y&&n.code===te.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Po(e.inputSchema)??e.inputSchema,i=await Ka(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Wa(a);throw new Y(te.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Y(te.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Po(e.outputSchema),s=await Ka(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Wa(i);throw new Y(te.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(b=>setTimeout(b,u));let p=await n.taskStore.getTask(c);if(!p)throw new Y(te.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(hn(yc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(yc,async e=>{switch(e.params.ref.type){case"ref/prompt":return Ik(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Ok(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Y(te.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new Y(te.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Y(te.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ei;let s=en(n.argsSchema)?.[e.params.argument.name];if(!lg(s))return Ei;let i=yT(s);if(!i)return Ei;let a=await i(e.params.argument.value,e.params.context);return xT(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Ei;throw new Y(te.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Ei;let s=await o(e.params.argument.value,e.params.context);return xT(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(hn(uc)),this.server.assertCanSetRequestHandler(hn(dc)),this.server.assertCanSetRequestHandler(hn(pc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(uc,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(dc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(pc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Y(te.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new Y(te.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(hn(hc)),this.server.assertCanSetRequestHandler(hn(mc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(hc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?rq(r.argsSchema):void 0}))})),this.server.setRequestHandler(mc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Y(te.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Y(te.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Po(n.argsSchema),s=await Ka(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Wa(c);throw new Y(te.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Bn(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Bn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let l=c instanceof xt?c._def?.innerType:c;return lg(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){ug(e);let u={title:r,description:n,inputSchema:kT(o),outputSchema:kT(s),annotations:i,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&ug(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Bn(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Bn(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(dg(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!dg(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},tq={type:"object",properties:{}};Ei={completion:{values:[],hasMore:!1}}});function oq(t){return Sk.parse(JSON.parse(t))}function RT(t){return JSON.stringify(t)+`
|
|
2358
|
+
`}var nq,gl,ET=N(()=>{jo();nq=10*1024*1024,gl=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??nq}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
2359
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),oq(r)}clear(){this._buffer=void 0}}});import PT from"node:process";var yl,AT=N(()=>{ET();yl=class{constructor(e=PT.stdin,r=PT.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new gl({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=RT(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var CT,IT=N(()=>{CT=[]});var qT={};rs(qT,{AUTHORING_MCP_SERVER_NAME:()=>jT,AUTHORING_MCP_SERVER_VERSION:()=>zT,AUTHORING_RESOURCES:()=>dq,AUTHORING_TOOLS:()=>uq,AUTHORING_TOOLS_PUBLIC:()=>UT,buildAuthoringMcpServer:()=>MT,resolveSamplesDir:()=>DT,runAuthoringMcpServer:()=>pq});import{promises as sq}from"node:fs";import{isAbsolute as iq,resolve as bl,sep as aq}from"node:path";function LT(){return NT??=import("../mcp/grounding.js").then(e=>e,()=>null),NT}function DT(t,e){if(e===void 0)return bl(process.cwd(),t??"samples");let r=bl(e);if(t===void 0)return r;if(iq(t))return null;let n=bl(r,t);return n===r||n.startsWith(r+aq)?n:null}function Ge(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function lq(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function MT(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let f=await Qt(t.baseUrl);if(!f)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:f.baseUrl,token:f.token}}let r=t.grounding??{},n=await LT(),o=null;if(n)try{let f=await e();o={surface:"mcp-authoring",baseUrl:f.baseUrl,token:f.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],c=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{c=(await n.listRecipesForSurface(o,i)).map(f=>({id:f.id,record_type:f.record_type,intent:f.intent}))}catch{c=[]}}let l=o?await lq(o,r):null,u=new fl({name:jT,version:zT},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(f=>f.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let f=o;for(let m of a)u.registerPrompt(m.id,{title:m.name,description:m.description},async()=>{let w=await n.getMcpPromptSkill(f,m.id,r);if(!w)throw new Error(`unknown prompt: ${m.id}`);return{description:w.description,messages:[{role:"user",content:{type:"text",text:(w.prompts??[]).join(`
|
|
2360
2360
|
|
|
2361
|
-
`)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:f,token:h}=await e(),w=await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!w.ok)throw new Error(`catalog fetch failed: ${w.status}`);return Ge(await w.json())}),u.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:E.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:E.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:f,source:h})=>{let{baseUrl:w,token:S}=await e(),R=h?`?source=${encodeURIComponent(h)}`:"",A=await fetch(`${w}/v1/catalog/records/${encodeURIComponent(f)}${R}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(A.status===404)throw new Error(`unknown record type "${f}" \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`record anatomy fetch failed: ${A.status}`);return Ge(await A.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:E.array(E.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:E.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:f,source:h})=>{let{baseUrl:w,token:S}=await e(),R=new URLSearchParams({types:f.join(",")});h&&R.set("source",h);let A=await fetch(`${w}/v1/catalog/columns?${R}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(A.status===404)throw new Error(`none of those record types resolved: ${f.join(", ")} \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`common columns fetch failed: ${A.status}`);return Ge(await A.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:f,token:h}=await e(),w=await fetch(`${f}/v1/catalog/census`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!w.ok)throw new Error(`catalog census failed: ${w.status}`);return Ge(await w.json())}),u.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:E.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:E.enum(PT).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:E.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:f,kind:h,limit:w})=>{let{baseUrl:S,token:R}=await e(),A=new URLSearchParams({q:f});h&&A.set("kind",h),w!==void 0&&A.set("limit",String(w));let L=await fetch(`${S}/v1/catalog/objects?${A}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!L.ok)throw new Error(`catalog object search failed: ${L.status}`);return Ge(await L.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:E.enum(PT),externalId:E.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:f,externalId:h})=>{let{baseUrl:w,token:S}=await e(),R=await fetch(`${w}/v1/catalog/objects/${encodeURIComponent(f)}/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown object ${f}:${h} \u2014 find it with search_catalog.`);if(!R.ok)throw new Error(`catalog object fetch failed: ${R.status}`);return Ge(await R.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:E.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:E.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:f,limit:h})=>{let{baseUrl:w,token:S}=await e(),R=new URLSearchParams({q:f});h!==void 0&&R.set("limit",String(h));let A=await fetch(`${w}/v1/kb/search?${R}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!A.ok)throw new Error(`kb search failed: ${A.status}`);return Ge(await A.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:E.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:f})=>{let{baseUrl:h,token:w}=await e(),S=await fetch(`${h}/v1/kb/document/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!S.ok&&S.status!==404)throw new Error(`kb document fetch failed: ${S.status}`);return Ge(await S.json())}),u.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:E.boolean().optional()}},async({recordsOnly:f})=>{let{baseUrl:h,token:w}=await e();return{content:[{type:"text",text:await Nn({baseUrl:h,token:w,recordsOnly:f})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:E.string(),event:E.string().optional(),template:E.enum(["require-field","enforce-format","blank"]).optional(),field:E.string().optional(),regex:E.string().optional(),source:E.string().optional(),id:E.string().optional()}},async f=>{let h=yr("hook",{recordType:f.recordType,event:f.event,template:f.template,field:f.field,regex:f.regex,source:f.source,id:f.id});return Ge({path:h.relativePath,content:h.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:E.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:E.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:E.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:E.string().optional().describe("Target record type (defaults to the trigger record type)."),event:E.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:E.string().optional()}},async f=>{let h=yr("conduit",{recordType:f.recordType,source:f.source,to:f.to,toRecordType:f.toRecordType,event:f.event,id:f.id});return Ge({path:h.relativePath,content:h.content})}),u.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:E.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:E.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:E.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:E.string().optional()}},async f=>{let h=yr("process",{recordType:f.recordType,then:f.then,onFailure:f.onFailure,id:f.id});return Ge({path:h.relativePath,content:h.content})}),u.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:E.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:E.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:E.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:E.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:E.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:E.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:E.array(E.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async f=>{let{baseUrl:h,token:w}=await e(),S=new K({baseUrl:h,token:w});return Ge(await S.authorConduit({intent:f.intent,from:{source:f.fromSource,recordType:f.fromRecordType},to:{source:f.toSource,recordType:f.toRecordType},...f.intentId?{intentId:f.intentId}:{},...f.columns?.length?{columns:f.columns}:{}}))}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:E.string().describe("The extension TS source."),samplesDir:E.string().optional().describe('Samples directory (default "samples").')}},async({source:f,samplesDir:h})=>{let w=NT(h,t.samplesRoot);if(w===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:tq})}],isError:!0};let S;try{S=await ds(w)}catch(L){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw L}let R=await sa(f,S.map(L=>L.fixture)),A=R.filter(L=>!L.pass).length;return Ge({total:R.length,passed:R.length-A,results:R})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:E.string(),recordType:E.string(),event:E.string(),source:E.string().describe('Adapter id or "standalone".'),sourceCode:E.string().describe("The verbatim extension TS."),extensionKind:E.string().optional()}},async f=>{let{baseUrl:h,token:w}=await e(),R=await new K({baseUrl:h,token:w}).deploy({id:f.id,recordType:f.recordType,event:f.event,source:f.source,sourceCode:f.sourceCode,extensionKind:f.extensionKind});return Ge(R)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:E.string(),limit:E.number().int().positive().optional()}},async({id:f,limit:h})=>{let{baseUrl:w,token:S}=await e(),R=new K({baseUrl:w,token:S});return Ge({id:f,logs:await R.logs(f,h)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:f,token:h}=await e(),w=new K({baseUrl:f,token:h});return Ge(await w.appsList())}),u.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:E.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:E.string().optional().describe("Display name (defaults to the slug)."),description:E.string().optional().describe("Short description.")}},async({slug:f,name:h,description:w})=>{let{baseUrl:S,token:R}=await e(),A=new K({baseUrl:S,token:R});return Ge(await A.appsCreate({slug:f,name:h,description:w}))}),u.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:E.string().describe("App slug or id.")}},async({app:f})=>{let{baseUrl:h,token:w}=await e(),S=new K({baseUrl:h,token:w});return Ge(await S.appsPull(f))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:E.string().describe("App slug or id."),files:E.record(E.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:E.string().optional().describe("Short note stored with the revision.")}},async({app:f,files:h,note:w})=>{let{baseUrl:S,token:R}=await e(),A=new K({baseUrl:S,token:R});return Ge(await A.appsPush(f,h,{note:w}))});let p=E.object({name:E.string().describe("Field name (lowercase identifier)."),type:E.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:E.boolean().optional()}),b=E.object({slug:E.string().describe("Table slug; the physical table is cr_<slug>."),displayName:E.string().optional(),fields:E.array(p).describe("At least one field."),rowLevelOwner:E.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:f,token:h}=await e(),w=new K({baseUrl:f,token:h});return Ge(await w.tablesList())}),u.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:E.array(b),claimedBy:E.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:h})=>{let{baseUrl:w,token:S}=await e(),R=new K({baseUrl:w,token:S});return Ge(await R.tablesPlan({tables:f,claimedBy:h}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:E.array(b),claimedBy:E.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:h})=>{let{baseUrl:w,token:S}=await e(),R=new K({baseUrl:w,token:S});return Ge(await R.tablesApply({tables:f,claimedBy:h}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async f=>{let{baseUrl:h,token:w}=await e(),R=await(await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}})).text();return{contents:[{uri:f.href,mimeType:"application/json",text:R}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async f=>{let{baseUrl:h,token:w}=await e(),S=await Nn({baseUrl:h,token:w});return{contents:[{uri:f.href,mimeType:"text/plain",text:S}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async f=>{let h=yl(process.cwd(),"samples"),w=[];try{w=(await XU.readdir(h)).filter(R=>R.endsWith(".json"))}catch{w=[]}let S=await ds(h);return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({files:w,samples:S.map(R=>R.fixture)},null,2)}]}}),u.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async f=>{let h=await CT(),w=[];if(h){let{baseUrl:S,token:R}=await e();w=await h.listRecipesForSurface({surface:"mcp-authoring",baseUrl:S,token:R},r)}return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({recipes:w})}]}}),u}async function sq(t={}){let e=await LT(t),r=new gl;await e.connect(r)}var PT,AT,IT,OT,tq,zT,nq,oq,DT=O(()=>{kT();TT();On();nu();cs();er();mu();da();ET();PT=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];IT="turbobase-authoring",OT="0.1.0";tq="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";zT=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],nq=[...zT,...RT],oq=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as gg}from"node:child_process";import{promises as _e}from"node:fs";import{homedir as iq}from"node:os";import{basename as qT,dirname as Ur,join as Ot,relative as wl,resolve as ye,sep as fg}from"node:path";var Lg=Sl(Ng(),1),{program:Pq,createCommand:Aq,createArgument:Cq,createOption:Iq,CommanderError:Oq,InvalidArgumentError:Nq,InvalidOptionArgumentError:Lq,Command:zg,Argument:zq,Option:jq,Help:Dq}=Lg.default;nu();cs();er();mu();oa();import{promises as Dy}from"node:fs";var _0=/^[a-z][a-z0-9_]+$/;function Oy(t,e){if(typeof t!="string"||!_0.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var v0="customrecord",k0="customlist";function x0(t){return t.startsWith("customrecord_")?t.slice(13):t}function S0(t){return t.startsWith("customlist_")?t.slice(11):t}function $0(t){return Oy(t,"custom_record scriptId"),`cr_${x0(t)}`}function T0(t){return Oy(t,"custom_list scriptId"),`cl_${S0(t)}`}function Ny(t){return t.startsWith(v0)?$0(t):t.startsWith(k0)?T0(t):null}var R0={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},request:{table:"request"}};function Ly(t,e){let r=e?P0[`${e}:${t}`]:void 0;if(r)return r;let n=R0[t];if(n)return n;let o=Ny(t);return o?{table:o}:void 0}var E0={accountingPeriod:"accounting_period",printer:"printer"};var P0={...Object.fromEntries(Object.entries(E0).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"azure_blob:file":{table:"source_file"}};function zy(t,e){let r=Ly(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function jy(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=zy(t,n),i=zy(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var My=4;function fu(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=ho(t,"id"),r=ho(t,"on"),n=ho(t,"source"),o=ho(t,"recordType"),s=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let u=ho(l[1]??"","source"),p=ho(l[1]??"","recordType");u&&p&&s.push({source:u,recordType:p})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t),c=/^[ \t]*reads\s*:\s*\[\s*\{/m.test(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):My,declaresReads:c}}function ho(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function A0(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}function C0(t,e){let r=t.queryRows;if(!(!r||!Object.prototype.hasOwnProperty.call(r,e)))return r[e]}async function Uy(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=fu(t)}catch(p){return{fixtureName:o,conduit:O0(),guards:s,whenPassed:!1,atlasResolutions:[],queryReads:[],wouldWriteBindings:[],targets:[],logs:[],error:p instanceof Error?p.message:String(p)}}let a=A0(e),c=Object.entries(e.atlasLinks??{}).map(([p,b])=>({key:p,resolved:b})),l=[],u=i.declaresReads?async p=>{let b=C0(e,p);return l.push({query:p,served:b!==void 0,rowCount:b?.length??0}),b??[]}:void 0;try{for(let[L,F]of Object.entries(e.queryRows??{}))if(!Array.isArray(F))throw new Error(`fixture queryRows['${L}'] must be an array of rows \u2014 ctx.query answers a row list, and a ${F===null?"null":typeof F} reaches the conduit as one`);let p=await na(t,{resolveDir:n.resolveDir}),f=!!(await us(p,a,{member:"when",timeoutMs:ra,query:u})).whenResult;s.push({name:"from.when",status:f?"passed":"failed",detail:f?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let h=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${h} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!f)return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:c,queryReads:l,wouldWriteBindings:[],targets:[],logs:[]};let w=[],S=[],R=[];for(let L=0;L<i.targets.length;L+=1){let F=i.targets[L],W=await us(p,{...a,materialized:R.map(mn=>({...mn}))},{member:"transform",stepIndex:L,timeoutMs:ra,query:u});w.push(...W.effects.logs);let Ke=W.effects.result;if(!Ke||typeof Ke!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${L+1})`:""} returned no result (expected { patch, createdFrom? })`);let Je=Ke,jt=jy(i.fromRecordType,F.recordType,{fromSource:i.fromSource,toSource:F.source}),{wouldWriteBindings:qr,masterAction:dr}=I0(i,F,jt,e);S.push({to:F,transformResult:Je,applyBranch:jt,wouldWriteBindings:qr,masterAction:dr}),R.push({source:F.source,recordType:F.recordType,masterTable:`<${F.recordType} master, dry-run>`,masterRowId:`<dry-run target ${L+1}>`,externalId:null})}let A=S[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:c,queryReads:l,transformResult:A.transformResult,applyBranch:A.applyBranch,wouldWriteBindings:A.wouldWriteBindings,masterAction:A.masterAction,targets:S,logs:w}}catch(p){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,queryReads:l,wouldWriteBindings:[],targets:[],logs:[],error:p instanceof Error?p.message:String(p)}}}function I0(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function O0(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:My,declaresReads:!1}}async function qy(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function Fy(t){let e=await Dy.readFile(t,"utf8");return JSON.parse(e)}function By(t){return Dy.readFile(t,"utf8")}function Zy(t,e){let r=t.conduit,n=`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`,o=t.targets.length>1;if(!e){if(t.error)return n;if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(o){let c=t.targets.reduce((l,u)=>l+u.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${c} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}if(t.error&&!r.id)return n;let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${r.id}`);let i=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(c=>`${c.source}.${c.recordType}`).join(" \u2192 ");s.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${i}${r.on?` on=${r.on}`:""}`),s.push(""),s.push("guards (dispatch order):"),t.guards.length===0&&s.push(" (none ran \u2014 the replay stopped before dispatch)");for(let c of t.guards){let l=c.status==="passed"?"\u2713":c.status==="failed"?"\u2717":"\u2298";s.push(` ${l} ${c.name} [${c.status}] \u2014 ${c.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let c of t.atlasResolutions)s.push(` ${c.key} \u2192 ${c.resolved===null?"null (no Atlas link \u2014 noted)":c.resolved}`);if(s.push(""),s.push("ctx.query (declared reads):"),!r.declaresReads)s.push(" (no `reads` declared \u2014 ctx.query is not defined in the isolate, exactly as in production)");else if(t.queryReads.length===0)s.push(" (declared, but this replay made no read)");else for(let c of t.queryReads)s.push(` ${c.query} \u2192 ${c.served?"served":"not served by the fixture"}, ${c.rowCount} row(s)`);if(t.error)return s.push(""),s.push(`ERROR \u2014 ${t.error}`),s.join(`
|
|
2361
|
+
`)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:f,token:m}=await e(),w=await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${m}`,Accept:"application/json"}});if(!w.ok)throw new Error(`catalog fetch failed: ${w.status}`);return Ge(await w.json())}),u.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:P.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:P.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:f,source:m})=>{let{baseUrl:w,token:$}=await e(),R=m?`?source=${encodeURIComponent(m)}`:"",A=await fetch(`${w}/v1/catalog/records/${encodeURIComponent(f)}${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(A.status===404)throw new Error(`unknown record type "${f}" \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`record anatomy fetch failed: ${A.status}`);return Ge(await A.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:P.array(P.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:P.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:f,source:m})=>{let{baseUrl:w,token:$}=await e(),R=new URLSearchParams({types:f.join(",")});m&&R.set("source",m);let A=await fetch(`${w}/v1/catalog/columns?${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(A.status===404)throw new Error(`none of those record types resolved: ${f.join(", ")} \u2014 list them with catalog_get.`);if(!A.ok)throw new Error(`common columns fetch failed: ${A.status}`);return Ge(await A.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:f,token:m}=await e(),w=await fetch(`${f}/v1/catalog/census`,{headers:{Authorization:`Bearer ${m}`,Accept:"application/json"}});if(!w.ok)throw new Error(`catalog census failed: ${w.status}`);return Ge(await w.json())}),u.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:P.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:P.enum(OT).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:P.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:f,kind:m,limit:w})=>{let{baseUrl:$,token:R}=await e(),A=new URLSearchParams({q:f});m&&A.set("kind",m),w!==void 0&&A.set("limit",String(w));let L=await fetch(`${$}/v1/catalog/objects?${A}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!L.ok)throw new Error(`catalog object search failed: ${L.status}`);return Ge(await L.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:P.enum(OT),externalId:P.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:f,externalId:m})=>{let{baseUrl:w,token:$}=await e(),R=await fetch(`${w}/v1/catalog/objects/${encodeURIComponent(f)}/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown object ${f}:${m} \u2014 find it with search_catalog.`);if(!R.ok)throw new Error(`catalog object fetch failed: ${R.status}`);return Ge(await R.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:P.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:P.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:f,limit:m})=>{let{baseUrl:w,token:$}=await e(),R=new URLSearchParams({q:f});m!==void 0&&R.set("limit",String(m));let A=await fetch(`${w}/v1/kb/search?${R}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!A.ok)throw new Error(`kb search failed: ${A.status}`);return Ge(await A.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:P.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:f})=>{let{baseUrl:m,token:w}=await e(),$=await fetch(`${m}/v1/kb/document/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return Ge(await $.json())}),u.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:P.boolean().optional()}},async({recordsOnly:f})=>{let{baseUrl:m,token:w}=await e();return{content:[{type:"text",text:await Nn({baseUrl:m,token:w,recordsOnly:f})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:P.string(),event:P.string().optional(),template:P.enum(["require-field","enforce-format","blank"]).optional(),field:P.string().optional(),regex:P.string().optional(),source:P.string().optional(),id:P.string().optional()}},async f=>{let m=yr("hook",{recordType:f.recordType,event:f.event,template:f.template,field:f.field,regex:f.regex,source:f.source,id:f.id});return Ge({path:m.relativePath,content:m.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:P.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:P.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:P.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:P.string().optional().describe("Target record type (defaults to the trigger record type)."),event:P.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:P.string().optional()}},async f=>{let m=yr("conduit",{recordType:f.recordType,source:f.source,to:f.to,toRecordType:f.toRecordType,event:f.event,id:f.id});return Ge({path:m.relativePath,content:m.content})}),u.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:P.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:P.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:P.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:P.string().optional()}},async f=>{let m=yr("process",{recordType:f.recordType,then:f.then,onFailure:f.onFailure,id:f.id});return Ge({path:m.relativePath,content:m.content})}),u.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:P.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:P.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:P.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:P.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:P.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:P.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:P.array(P.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async f=>{let{baseUrl:m,token:w}=await e(),$=new K({baseUrl:m,token:w});return Ge(await $.authorConduit({intent:f.intent,from:{source:f.fromSource,recordType:f.fromRecordType},to:{source:f.toSource,recordType:f.toRecordType},...f.intentId?{intentId:f.intentId}:{},...f.columns?.length?{columns:f.columns}:{}}))}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:P.string().describe("The extension TS source."),samplesDir:P.string().optional().describe('Samples directory (default "samples").')}},async({source:f,samplesDir:m})=>{let w=DT(m,t.samplesRoot);if(w===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:cq})}],isError:!0};let $;try{$=await hs(w)}catch(L){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw L}let R=await ia(f,$.map(L=>L.fixture)),A=R.filter(L=>!L.pass).length;return Ge({total:R.length,passed:R.length-A,results:R})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:P.string(),recordType:P.string(),event:P.string(),source:P.string().describe('Adapter id or "standalone".'),sourceCode:P.string().describe("The verbatim extension TS."),extensionKind:P.string().optional()}},async f=>{let{baseUrl:m,token:w}=await e(),R=await new K({baseUrl:m,token:w}).deploy({id:f.id,recordType:f.recordType,event:f.event,source:f.source,sourceCode:f.sourceCode,extensionKind:f.extensionKind});return Ge(R)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:P.string(),limit:P.number().int().positive().optional()}},async({id:f,limit:m})=>{let{baseUrl:w,token:$}=await e(),R=new K({baseUrl:w,token:$});return Ge({id:f,logs:await R.logs(f,m)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:f,token:m}=await e(),w=new K({baseUrl:f,token:m});return Ge(await w.appsList())}),u.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:P.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:P.string().optional().describe("Display name (defaults to the slug)."),description:P.string().optional().describe("Short description.")}},async({slug:f,name:m,description:w})=>{let{baseUrl:$,token:R}=await e(),A=new K({baseUrl:$,token:R});return Ge(await A.appsCreate({slug:f,name:m,description:w}))}),u.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:P.string().describe("App slug or id.")}},async({app:f})=>{let{baseUrl:m,token:w}=await e(),$=new K({baseUrl:m,token:w});return Ge(await $.appsPull(f))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:P.string().describe("App slug or id."),files:P.record(P.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:P.string().optional().describe("Short note stored with the revision.")}},async({app:f,files:m,note:w})=>{let{baseUrl:$,token:R}=await e(),A=new K({baseUrl:$,token:R});return Ge(await A.appsPush(f,m,{note:w}))});let p=P.object({name:P.string().describe("Field name (lowercase identifier)."),type:P.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:P.boolean().optional()}),b=P.object({slug:P.string().describe("Table slug; the physical table is cr_<slug>."),displayName:P.string().optional(),fields:P.array(p).describe("At least one field."),rowLevelOwner:P.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:f,token:m}=await e(),w=new K({baseUrl:f,token:m});return Ge(await w.tablesList())}),u.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:P.array(b),claimedBy:P.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:m})=>{let{baseUrl:w,token:$}=await e(),R=new K({baseUrl:w,token:$});return Ge(await R.tablesPlan({tables:f,claimedBy:m}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:P.array(b),claimedBy:P.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:f,claimedBy:m})=>{let{baseUrl:w,token:$}=await e(),R=new K({baseUrl:w,token:$});return Ge(await R.tablesApply({tables:f,claimedBy:m}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async f=>{let{baseUrl:m,token:w}=await e(),R=await(await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}})).text();return{contents:[{uri:f.href,mimeType:"application/json",text:R}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async f=>{let{baseUrl:m,token:w}=await e(),$=await Nn({baseUrl:m,token:w});return{contents:[{uri:f.href,mimeType:"text/plain",text:$}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async f=>{let m=bl(process.cwd(),"samples"),w=[];try{w=(await sq.readdir(m)).filter(R=>R.endsWith(".json"))}catch{w=[]}let $=await hs(m);return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({files:w,samples:$.map(R=>R.fixture)},null,2)}]}}),u.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async f=>{let m=await LT(),w=[];if(m){let{baseUrl:$,token:R}=await e();w=await m.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:R},r)}return{contents:[{uri:f.href,mimeType:"application/json",text:JSON.stringify({recipes:w})}]}}),u}async function pq(t={}){let e=await MT(t),r=new yl;await e.connect(r)}var OT,NT,jT,zT,cq,UT,uq,dq,FT=N(()=>{TT();AT();On();ou();us();er();fu();pa();IT();OT=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];jT="turbobase-authoring",zT="0.1.0";cq="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";UT=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],uq=[...UT,...CT],dq=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as yg}from"node:child_process";import{promises as be}from"node:fs";import{homedir as hq}from"node:os";import{basename as VT,dirname as Ur,join as Ot,relative as _l,resolve as ge,sep as gg}from"node:path";var jg=$l(Lg(),1),{program:zq,createCommand:Dq,createArgument:Mq,createOption:Uq,CommanderError:qq,InvalidArgumentError:Fq,InvalidOptionArgumentError:Bq,Command:zg,Argument:Zq,Option:Vq,Help:Hq}=jg.default;ou();us();er();fu();sa();import{promises as My}from"node:fs";var S0=/^[a-z][a-z0-9_]+$/;function Ny(t,e){if(typeof t!="string"||!S0.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var $0="customrecord",T0="customlist";function R0(t){return t.startsWith("customrecord_")?t.slice(13):t}function E0(t){return t.startsWith("customlist_")?t.slice(11):t}function P0(t){return Ny(t,"custom_record scriptId"),`cr_${R0(t)}`}function A0(t){return Ny(t,"custom_list scriptId"),`cl_${E0(t)}`}function Ly(t){return t.startsWith($0)?P0(t):t.startsWith(T0)?A0(t):null}var C0={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},request:{table:"request"}};function jy(t,e){let r=e?O0[`${e}:${t}`]:void 0;if(r)return r;let n=C0[t];if(n)return n;let o=Ly(t);return o?{table:o}:void 0}var I0={accountingPeriod:"accounting_period",printer:"printer"};var O0={...Object.fromEntries(Object.entries(I0).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"azure_blob:file":{table:"source_file"}};function zy(t,e){let r=jy(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function Dy(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=zy(t,n),i=zy(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Uy=4;function gu(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=mo(t,"id"),r=mo(t,"on"),n=mo(t,"source"),o=mo(t,"recordType"),s=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let u=mo(l[1]??"","source"),p=mo(l[1]??"","recordType");u&&p&&s.push({source:u,recordType:p})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t),c=/^[ \t]*reads\s*:\s*\[\s*\{/m.test(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):Uy,declaresReads:c}}function mo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function N0(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}function L0(t,e){let r=t.queryRows;if(!(!r||!Object.prototype.hasOwnProperty.call(r,e)))return r[e]}async function qy(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=gu(t)}catch(p){return{fixtureName:o,conduit:z0(),guards:s,whenPassed:!1,atlasResolutions:[],queryReads:[],wouldWriteBindings:[],targets:[],logs:[],error:p instanceof Error?p.message:String(p)}}let a=N0(e),c=Object.entries(e.atlasLinks??{}).map(([p,b])=>({key:p,resolved:b})),l=[],u=i.declaresReads?async p=>{let b=L0(e,p);return l.push({query:p,served:b!==void 0,rowCount:b?.length??0}),b??[]}:void 0;try{for(let[L,F]of Object.entries(e.queryRows??{}))if(!Array.isArray(F))throw new Error(`fixture queryRows['${L}'] must be an array of rows \u2014 ctx.query answers a row list, and a ${F===null?"null":typeof F} reaches the conduit as one`);let p=await oa(t,{resolveDir:n.resolveDir}),f=!!(await ps(p,a,{member:"when",timeoutMs:na,query:u})).whenResult;s.push({name:"from.when",status:f?"passed":"failed",detail:f?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let m=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${m} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!f)return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:c,queryReads:l,wouldWriteBindings:[],targets:[],logs:[]};let w=[],$=[],R=[];for(let L=0;L<i.targets.length;L+=1){let F=i.targets[L],W=await ps(p,{...a,materialized:R.map(mn=>({...mn}))},{member:"transform",stepIndex:L,timeoutMs:na,query:u});w.push(...W.effects.logs);let Ke=W.effects.result;if(!Ke||typeof Ke!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${L+1})`:""} returned no result (expected { patch, createdFrom? })`);let Je=Ke,zt=Dy(i.fromRecordType,F.recordType,{fromSource:i.fromSource,toSource:F.source}),{wouldWriteBindings:qr,masterAction:dr}=j0(i,F,zt,e);$.push({to:F,transformResult:Je,applyBranch:zt,wouldWriteBindings:qr,masterAction:dr}),R.push({source:F.source,recordType:F.recordType,masterTable:`<${F.recordType} master, dry-run>`,masterRowId:`<dry-run target ${L+1}>`,externalId:null})}let A=$[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:c,queryReads:l,transformResult:A.transformResult,applyBranch:A.applyBranch,wouldWriteBindings:A.wouldWriteBindings,masterAction:A.masterAction,targets:$,logs:w}}catch(p){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,queryReads:l,wouldWriteBindings:[],targets:[],logs:[],error:p instanceof Error?p.message:String(p)}}}function j0(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function z0(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Uy,declaresReads:!1}}async function Fy(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function By(t){let e=await My.readFile(t,"utf8");return JSON.parse(e)}function Zy(t){return My.readFile(t,"utf8")}function Vy(t,e){let r=t.conduit,n=`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`,o=t.targets.length>1;if(!e){if(t.error)return n;if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(o){let c=t.targets.reduce((l,u)=>l+u.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${c} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}if(t.error&&!r.id)return n;let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${r.id}`);let i=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(c=>`${c.source}.${c.recordType}`).join(" \u2192 ");s.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${i}${r.on?` on=${r.on}`:""}`),s.push(""),s.push("guards (dispatch order):"),t.guards.length===0&&s.push(" (none ran \u2014 the replay stopped before dispatch)");for(let c of t.guards){let l=c.status==="passed"?"\u2713":c.status==="failed"?"\u2717":"\u2298";s.push(` ${l} ${c.name} [${c.status}] \u2014 ${c.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let c of t.atlasResolutions)s.push(` ${c.key} \u2192 ${c.resolved===null?"null (no Atlas link \u2014 noted)":c.resolved}`);if(s.push(""),s.push("ctx.query (declared reads):"),!r.declaresReads)s.push(" (no `reads` declared \u2014 ctx.query is not defined in the isolate, exactly as in production)");else if(t.queryReads.length===0)s.push(" (declared, but this replay made no read)");else for(let c of t.queryReads)s.push(` ${c.query} \u2192 ${c.served?"served":"not served by the fixture"}, ${c.rowCount} row(s)`);if(t.error)return s.push(""),s.push(`ERROR \u2014 ${t.error}`),s.join(`
|
|
2362
2362
|
`);if(!t.whenPassed)return s.push(""),s.push("transform: SKIPPED (from.when gate did not fire)."),s.join(`
|
|
2363
|
-
`);let a=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(a.forEach((c,l)=>{let u=o?` (target ${l+1}/${a.length}: ${c.to.source}.${c.to.recordType})`:"";s.push(""),s.push(`transform${u} \u2192 patch:`),s.push(
|
|
2364
|
-
`)}function
|
|
2363
|
+
`);let a=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(a.forEach((c,l)=>{let u=o?` (target ${l+1}/${a.length}: ${c.to.source}.${c.to.recordType})`:"";s.push(""),s.push(`transform${u} \u2192 patch:`),s.push(D0(JSON.stringify(c.transformResult.patch??{},null,2)," ")),c.transformResult.createdFrom&&s.push(` createdFrom: ${JSON.stringify(c.transformResult.createdFrom)}`),s.push(""),s.push(`apply-branch${u}: ${c.applyBranch}`),s.push(` ${c.masterAction}`),s.push(""),s.push(`bindings that WOULD be written (txn_source_link)${u}:`);for(let p of c.wouldWriteBindings)s.push(` ${p.source} role=${p.role} external_id=${p.externalId??"null"} \u2014 ${p.why}`)}),t.logs.length>0){s.push(""),s.push("conduit logs:");for(let c of t.logs)s.push(` [${c.level}] ${c.message}${c.meta?` ${JSON.stringify(c.meta)}`:""}`)}return s.join(`
|
|
2364
|
+
`)}function D0(t,e){return t.split(`
|
|
2365
2365
|
`).map(r=>e+r).join(`
|
|
2366
|
-
`)}var
|
|
2366
|
+
`)}var M0="2026-01-01",Hy="2026-01-01T00:00:00.000Z";function U0(t,e){let r=t.trim().toLowerCase();return r==="boolean"||r==="bool"?!1:r==="smallint"||r==="integer"||r==="int"||r==="int2"||r==="int4"||r==="int8"||r==="bigint"||r==="serial"||r==="bigserial"?1:r==="numeric"||r==="decimal"||r==="real"||r==="double precision"||r==="float4"||r==="float8"||r==="money"?0:r==="date"?M0:r.startsWith("timestamp")?Hy:r.startsWith("time")?"00:00:00":r==="json"||r==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:Hy}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function q0(t){let e={};for(let r of t.columns)e[r.name]=U0(r.pgType,r.name);return e}function F0(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:q0(t)},expect:e.expect??"pass"}}function Ky(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:F0(r,e)}))}import{promises as Wy}from"node:fs";import{join as Gy,relative as B0,sep as Z0}from"node:path";var V0=67324752,H0=33639248,K0=101010256,W0=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function G0(t){let e=4294967295;for(let r=0;r<t.length;r++)e=W0[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function J0(t){let e=[];async function r(n){let o=await Wy.readdir(n,{withFileTypes:!0});for(let s of o){let i=Gy(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(B0(t,i).split(Z0).join("/"))}}return await r(t),e.sort(),e}async function Jy(t){let e=await J0(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await Wy.readFile(Gy(t,a)),u=G0(l),p=Buffer.alloc(30+c.length);p.writeUInt32LE(V0,0),p.writeUInt16LE(20,4),p.writeUInt16LE(0,6),p.writeUInt16LE(0,8),p.writeUInt32LE(u,14),p.writeUInt32LE(l.length,18),p.writeUInt32LE(l.length,22),p.writeUInt16LE(c.length,26),c.copy(p,30),r.push(p,l);let b=Buffer.alloc(46+c.length);b.writeUInt32LE(H0,0),b.writeUInt16LE(20,4),b.writeUInt16LE(20,6),b.writeUInt16LE(0,10),b.writeUInt32LE(u,16),b.writeUInt32LE(l.length,20),b.writeUInt32LE(l.length,24),b.writeUInt16LE(c.length,28),b.writeUInt32LE(o,42),c.copy(b,46),n.push(b),o+=p.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(K0,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}uu();function Y0(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function aa(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function X0(t){let e=Q0(t,"from"),n=Yy(t,"to").map(o=>({source:aa(o,"source"),recordType:aa(o,"recordType")}));return{fromSource:e?aa(e,"source"):void 0,fromRecordType:e?aa(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function Q0(t,e){return Yy(t,e)[0]??null}function Yy(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let c=t[a];if(c==="{")s+=1;else if(c==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function eP(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,o=null,s=r;for(;s<t.length;s+=1){let c=t[s];if(o){c==="\\"?s+=1:c===o&&(o=null);continue}if(c==="'"||c==='"'||c==="`"){o=c;continue}if(c==="("||c==="{"||c==="[")n+=1;else if(c===")"||c==="}"||c==="]"){if(n===0)break;n-=1}else if(c===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function tP(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function rP(t){return/\bcreatedFrom\b/.test(t)}function nP(t){let e=/\bdefine(?:Hook|Conduit|Process)\s*(?:<[^>]*>)?\s*\(\s*\{/.exec(t);if(!e)return null;let r=0,n=null,o=!1;for(let s=e.index+e[0].length-1;s<t.length;s+=1){let i=t[s];if(n){i==="\\"?s+=1:i===n&&(n=null);continue}if(i==="/"&&t[s+1]==="/"){let a=t.indexOf(`
|
|
2367
|
+
`,s);s=a<0?t.length:a;continue}if(i==="/"&&t[s+1]==="*"){let a=t.indexOf("*/",s+2);s=a<0?t.length:a+1;continue}if(i==="'"||i==='"'||i==="`"){n=i,o=!1;continue}if(i==="{"||i==="("||i==="["){r+=1,o=r===1;continue}if(i==="}"||i===")"||i==="]"){if(r-=1,r===0)return{};continue}if(r===1&&i===","){o=!0;continue}if(!(r===1&&o&&/\s/.test(i))&&r===1&&o){o=!1;let a=/^id\s*:\s*/.exec(t.slice(s));if(!a)continue;let c=/^(['"`])([^'"`]+)\1/.exec(t.slice(s+a[0].length));return c?{literal:c[2],index:s}:{}}}return{}}function oP(t){let e=/id\s*:\s*(['"`])([^'"`]+)\1/.exec(t),r=nP(t);if(!e||!r||r.index===e.index)return null;let n=e[2];return{rule:"id-not-first-literal",message:r.literal===void 0?`the define call's own \`id\` is not a string literal, so the deploy keys this file on the first \`id:\` literal it finds, '${n}' \u2014 the deploy will refuse it with extension_id_mismatch unless that is the module's id.`:`the first \`id:\` literal in the file is '${n}', not the define call's own '${r.literal}' \u2014 the deploy keys the file on the first one and refuses the mismatch (extension_id_mismatch).`,fix:"Write the extension's own id as a string literal on the define call (`id: '<your-id>'`), and keep any comment, constant, step or helper that carries an `id:` literal below it."}}function Xy(t){let e=Y0(t),r=[],n=oP(t);if(n&&r.push(n),e==="hook")return{kind:e,warnings:r};let{fromSource:o,fromRecordType:s,toRecordType:i,targets:a}=X0(t);for(let p of a)if(o&&p.source&&o===p.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${o}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let c=eP(t);if(c!==null){let p=/\bexternalId\b/.test(c),b=/\bfromSource\b/.test(c);!p&&!b&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}let l=a.find(p=>p.recordType&&s&&p.recordType!==s)?.recordType??(s!==i?i:void 0);s&&l&&!rP(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${l}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${l} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let u=tP(t,"cycleBudget");return u!==void 0&&(u<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${u} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):u>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${u} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:r}}function Qy(t,e,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
|
|
2367
2368
|
`);for(let a of e.warnings)i.push(` ${n("WARN")} ${s(`[${a.rule}]`)} ${a.message}`),i.push(` ${s("\u2192 fix:")} ${a.fix}`);return i.push(`
|
|
2368
2369
|
lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
|
|
2369
|
-
`)}function
|
|
2370
|
+
`)}function eb(t){return t.cases.filter(e=>e.status==="failed").length}function fs(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function sP(t){let e=eb(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${fs(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${fs(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${fs(n.type)}"`:"";r.push(` <failure${i} message="${fs(s)}">${fs(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
|
|
2370
2371
|
`)}
|
|
2371
|
-
`}function
|
|
2372
|
-
`}function
|
|
2372
|
+
`}function iP(t){let e={suite:t.name,tests:t.cases.length,failures:eb(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
|
|
2373
|
+
`}function ca(t,e){return e==="junit"?sP(t):iP(t)}var $t={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",invert:"\x1B[7m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",grey:"\x1B[90m"},Qe={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},fo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],qt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},tb=/\x1b\[[0-9;]*m/g;function Ir(t){return t.replace(tb,"").length}function yu(t,e){return e<=0?1:Math.max(1,Math.ceil(Ir(t)/e))}function aP(){return process.env.NO_COLOR!=null&&process.env.NO_COLOR!==""?!1:process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0"?!0:process.env.TERM==="dumb"?!1:process.stdout.isTTY===!0}var bu=aP();function nt(){return bu}function wu(t){bu=t}function it(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Ft(t,e){return bu?`${t}${e}${$t.reset}`:e}var g={bold:t=>Ft($t.bold,t),dim:t=>Ft($t.dim,t),red:t=>Ft($t.red,t),green:t=>Ft($t.green,t),yellow:t=>Ft($t.yellow,t),blue:t=>Ft($t.blue,t),magenta:t=>Ft($t.magenta,t),cyan:t=>Ft($t.cyan,t),grey:t=>Ft($t.grey,t)};var Le={success:t=>`${g.green("\u2713")} ${t}`,error:t=>`${g.red("\u2716")} ${t}`,warn:t=>`${g.yellow("\u26A0")} ${t}`,info:t=>`${g.dim("\xB7")} ${t}`,step:t=>`${g.cyan("\u25B8")} ${t}`},Kr={add:t=>g.green(`+ ${t}`),change:t=>g.yellow(`~ ${t}`),destroy:t=>g.red(`- ${t}`)},cP=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),lP=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),uP=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function go(t){let e=t.toLowerCase();return cP.has(e)?g.green(t):lP.has(e)?g.red(t):uP.has(e)?g.yellow(t):t}function Wr(t,e=[]){let r=Math.max(Ir(t),...e.map(Ir),0),n=r+2,o=g.cyan(qt.v),s=a=>` ${a}${" ".repeat(r-Ir(a))} `,i=[g.cyan(`${qt.tl}${qt.h.repeat(n)}${qt.tr}`),`${o}${g.bold(s(t))}${o}`];if(e.length){i.push(`${g.cyan(qt.ml)}${g.dim(qt.h.repeat(n))}${g.cyan(qt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(g.cyan(`${qt.bl}${qt.h.repeat(n)}${qt.br}`)),i.join(`
|
|
2373
2374
|
`)}function tr(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(l=>l.length)),i=[];for(let l=0;l<s;l+=1)i[l]=Math.max(0,...o.map(u=>Ir(u[l]??"")));let a=l=>{let u=l.map((p,b)=>{let f=p??"";return b===l.length-1?f:f+" ".repeat(Math.max(0,i[b]-Ir(f)))});return r+u.join(n)},c=[];e.head&&(c.push(a(e.head.map(l=>g.bold(l)))),c.push(a(e.head.map((l,u)=>g.dim("\u2500".repeat(i[u]??Ir(l)))))));for(let l of t)c.push(a(l));return c.join(`
|
|
2374
|
-
`)}function
|
|
2375
|
+
`)}function _u(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${nt()?e.map(n=>Ft($t.cyan,n)).join(`
|
|
2375
2376
|
`):e.join(`
|
|
2376
2377
|
`)}
|
|
2377
|
-
${g.dim(` ${t}`)}`}var Bt=t=>{process.stderr.write(t)};function
|
|
2378
|
+
${g.dim(` ${t}`)}`}var Bt=t=>{process.stderr.write(t)};function la(){return nt()&&process.stderr.isTTY===!0}function rb(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${g.dim("\u2591".repeat(e-n))}`}async function ie(t,e){let r=la(),n=0,o;r&&(Bt(Qe.hideCursor),o=setInterval(()=>{Bt(`${Qe.col0}${Qe.clearLine}${g.magenta(fo[n++%fo.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Bt(`${Qe.col0}${Qe.clearLine}${Qe.showCursor}`)};try{let i=await e();return s(),r&&Bt(`${Le.success(t)}
|
|
2378
2379
|
`),i}catch(i){throw s(),r&&Bt(`${Le.error(t)}
|
|
2379
|
-
`),i}}function
|
|
2380
|
-
`),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Bt(Qe.showCursor);let l=c.stage!=="failed",u=`${t} ${g.dim("\u25B8")} ${
|
|
2381
|
-
`)},stop(){clearInterval(a),i(),Bt(Qe.showCursor)}}}function
|
|
2380
|
+
`),i}}function vu(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=g.magenta(fo[e%fo.length]),l=g.cyan(r.stage),u=r.runStatus?` ${g.dim(`(${r.runStatus})`)}`:"",p=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${g.dim("\u25B8")} ${l}${u} ${rb(r.percent)} ${p}`},s=()=>{Bt(`${Qe.col0}${Qe.clearLine}${o()}`),n=!0},i=()=>{n&&Bt(`${Qe.col0}${Qe.clearLine}`),n=!1};Bt(Qe.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Bt(`${c}
|
|
2381
|
+
`),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Bt(Qe.showCursor);let l=c.stage!=="failed",u=`${t} ${g.dim("\u25B8")} ${dP(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Bt(`${l?Le.success(u):Le.error(u)}
|
|
2382
|
+
`)},stop(){clearInterval(a),i(),Bt(Qe.showCursor)}}}function dP(t){return t==="completed"?g.green(t):t==="failed"?g.red(t):g.cyan(t)}function at(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(w=>!w.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:s,a=w=>{process.stderr.write(w)},c=process.stdin,l=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${g.bold(g.cyan("?"))} ${g.bold(t)}
|
|
2382
2383
|
`),a(`${g.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
2383
|
-
`),a(Qe.hideCursor);let u=0,p=()=>{let w=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Qe.cursorUp(u)),a(Qe.clearToEnd));let
|
|
2384
|
-
`)
|
|
2385
|
-
`),o(new Error("aborted"));return}if(
|
|
2386
|
-
`){let A=e[i];if(A.disabled)return;b(),n(A.value);return}if(
|
|
2387
|
-
`)}),o=r.sleep??
|
|
2388
|
-
`)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(
|
|
2389
|
-
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function
|
|
2390
|
-
`)}),n=e.sleep??
|
|
2391
|
-
`)},
|
|
2392
|
-
${e.length} run(s).`)}function
|
|
2384
|
+
`),a(Qe.hideCursor);let u=0,p=()=>{let w=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Qe.cursorUp(u)),a(Qe.clearToEnd));let $=0;for(let R=0;R<e.length;R+=1){let A=e[R],L=R===i,F=L?g.cyan("\u25B6"):" ",W=A.disabled?g.grey(A.label):L?g.bold(g.cyan(A.label)):A.label,Ke=A.description?` ${g.dim(A.description)}`:"",Je=` ${F} ${W}${Ke}`;a(`\r${Je}
|
|
2385
|
+
`),$+=yu(Je,w)}u=$},b=()=>{c.removeListener("data",m),c.setRawMode?.(l??!1),c.pause(),a(Qe.showCursor)},f=w=>{let $=i;for(let R=0;R<e.length;R+=1)if($=($+w+e.length)%e.length,!e[$].disabled){i=$;return}},m=w=>{let $=w.toString("utf8");if($===""||$==="q"){b(),a(`
|
|
2386
|
+
`),o(new Error("aborted"));return}if($==="\r"||$===`
|
|
2387
|
+
`){let A=e[i];if(A.disabled)return;b(),n(A.value);return}if($==="\x1B[A"||$==="k"){f(-1),p();return}if($==="\x1B[B"||$==="j"){f(1),p();return}let R=Number($);Number.isFinite(R)&&R>=1&&R<=e.length&&!e[R-1].disabled&&(i=R-1,p())};c.on("data",m),p()})}function ua(t,e){return`${go(t)}${" ".repeat(Math.max(0,e-t.length))}`}var ob=t=>new Promise(e=>setTimeout(e,t));function nb(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${ua(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function sb(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
|
|
2388
|
+
`)}),o=r.sleep??ob,s=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,c="";for(let u of[...i].reverse())n(nb(u)),a+=1,u.updatedAt>c&&(c=u.updatedAt);if(!r.follow)return a;let l=r.maxPolls??Number.POSITIVE_INFINITY;for(let u=0;u<l;u+=1){await o(s);let p=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let b of[...p].reverse())n(nb(b)),a+=1,b.updatedAt>c&&(c=b.updatedAt)}return a}function pP(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${ua(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function ib(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
|
|
2389
|
+
`)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(pP(o));return r(`
|
|
2390
|
+
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function hP(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),n=t.occurrences>1?` x${t.occurrences}`:"",o=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",s=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${ua(t.severity,5)} ${ua(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function ab(t,e={}){let r=e.sink??(R=>{process.stdout.write(`${R}
|
|
2391
|
+
`)}),n=e.sleep??ob,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:c,sleep:l,intervalMs:u,...p}=e,b=R=>{r(a?JSON.stringify(R):hP(R))},f=await t.platformEvents({...p,limit:p.limit??100});if(f.length===0&&!s)return r("logs: no events matched."),0;let m=0,w="";for(let R of[...f].reverse())b(R),m+=1,R.ts>w&&(w=R.ts);if(!s)return m;let $=i??Number.POSITIVE_INFINITY;for(let R=0;R<$;R+=1){await n(o);let A=await t.platformEvents({...p,...w?{after:w,since:void 0}:{},limit:200});for(let L of[...A].reverse())b(L),m+=1,L.ts>w&&(w=L.ts)}return m}var cb=new Set(["committed","failed","rolled_back","cancelled"]),gs=t=>{process.stdout.write(`${t}
|
|
2392
|
+
`)},mP=t=>new Promise(e=>setTimeout(e,t));function fP(t){return t==null?"\u2014":t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}m${Math.round(t%6e4/1e3)}s`}function lb(t){let e=t.startedAt??"not started",r=t.outcome&&t.outcome!==t.state?` ${t.outcome}`:"",n=t.scheduleId?" (scheduled)":"";return` ${t.runId} ${t.state.padEnd(11)} ${e} ${fP(t.durationMs)}${n}${r}`}function gP(t){if(t.trigger.kind!=="scheduled")return"manual";let e=t.trigger.timezone?` ${t.trigger.timezone}`:"",r=t.trigger.status&&t.trigger.status!=="active"?` (${t.trigger.status})`:"";return`scheduled ${t.trigger.cron??"?"}${e}${r}`}function ub(t,e=gs){if(t.length===0){e("No processes are deployed on this instance."),e("Author one with `turbobase ext new process` and ship it with `turbobase ext deploy`.");return}for(let r of t){if(e(`${r.id}${r.enabled?"":" [off]"}`),e(` trigger: ${gP(r)}`),r.runs.length===0)e(" never run");else for(let n of r.runs)e(lb(n));e("")}e(`${t.length} process(es).`)}function db(t,e,r=gs){if(r(t),e.length===0){r(" no runs yet.");return}for(let n of e)r(lb(n));r(`
|
|
2393
|
+
${e.length} run(s).`)}function da(t,e=gs){let r=t.run?.runId??t.runId??"(unknown run)",n=t.run?.processId??t.processId??"",o=t.run?.state??t.state??"",s=t.run?.reason??t.reason??null,i=t.run?.outstanding??t.outstanding??null;e(`${r} ${o}${n?` ${n}`:""}`),s&&e(` ${s}`),i!==null&&i>0&&e(` ${i} still outstanding`);let a=t.steps??[];if(a.length===0){e(" no steps recorded yet.");return}for(let c of a){let l=c.externalId??c.pgRowId??"\u2014",u=c.refusal?.message?` ${c.refusal.message}`:"";e(` ${String(c.sequence).padStart(3)} ${c.stepId.padEnd(16)} ${c.disposition.padEnd(12)} ${c.recordType}/${l}${u}`)}}async function pb(t,e,r={}){let n=r.sink??gs,o=r.sleep??mP,s=r.intervalMs??2e3,i=r.maxPolls??Number.POSITIVE_INFINITY,a=new Set,c=u=>{let p=[];da(u,b=>p.push(b));for(let b of p)a.has(b)||(a.add(b),n(b));return u.run?.state??u.state??""},l=c(await t.processRun(e));if(!r.follow)return l;for(let u=0;u<i;u+=1){if(cb.has(l))return l;await o(s),l=c(await t.processRun(e))}return cb.has(l)?l:null}function hb(t,e){let r;try{r=JSON.parse(t)}catch(n){return{ok:!1,message:`${e} must be valid JSON: ${n instanceof Error?n.message:String(n)}`}}return typeof r!="object"||r===null||Array.isArray(r)?{ok:!1,message:`${e} must be a JSON object (the process input), e.g. '{"customerId":"42"}'.`}:{ok:!0,input:r}}function mb(t,e,r,n=gs){let o=t.runId??"(unknown run)",s=`${r} logs --process-run ${o} --follow`;if(t.error==="sync_budget_exceeded"){n(`${o} still running ${t.processId??e}`),n(" It did not settle within the instance's synchronous budget. It has not failed \u2014 it is still going."),n(` Watch it: ${s}`);return}if(t.steps!==void 0){da(t,n);return}n(`${o} ${t.state??"queued"} ${t.processId??e}`),n(` Watch it: ${s}`)}pa();sa();function gb(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var wb=9,ys=" ".repeat(2+wb);function yo(t,e=r=>r){return e(t)+" ".repeat(Math.max(1,wb-t.length))}function vP(t,e,r){return t===1?e:r}function _b(t){return t?g.dim(` (${t} holder${t===1?"":"s"} re-stamped)`):""}function vb(t){return t.length>0?`[${t.join(", ")}]`:"unrestricted"}function kP(t){if(!t)return[];let e=[],r=t.addedGrants??[],n=t.removedGrants??[];if(r.length>0||n.length>0){let s=[...r.map(i=>`+${i}`),...n.map(i=>`\u2212${i}`)];e.push(`content ${s.join(" ")}`)}let o=t.setRestrictions??{};for(let s of Object.keys(o).sort())e.push(`${s} \u2192 ${vb(o[s]??[])}`);return e}function yb(t){let e=[],r=t.scopeChanges?.adoptedGrants??[];r.length>0&&e.push({stream:"out",text:g.dim(`${ys}adopted (already on the role \u2014 the admin's, never retired by this app): ${r.join(", ")}`)});let n=t.scopeChanges?.adoptedRestrictions??{};for(let s of Object.keys(n).sort())e.push({stream:"out",text:g.dim(`${ys}adopted ${s} ${vb(n[s]??[])} (already on the role \u2014 the admin's, never cleared or widened by this app)`)});let o=[...t.keptRemovedCapabilities??[],...t.scopeChanges?.keptRemovedGrants??[]];o.length>0&&e.push({stream:"out",text:g.dim(`${ys}kept (admin removed): ${o.join(", ")}`)});for(let s of t.scopeChanges?.keptAdminRestrictions??[])e.push({stream:"out",text:g.dim(`${ys}kept admin value for ${s}`)});for(let s of t.warnings??[])e.push({stream:"out",text:g.yellow(`${ys}! ${s}`)});return e}function kb(t){return(t.warnings?.length??0)>0||(t.keptRemovedCapabilities?.length??0)>0||(t.scopeChanges?.keptRemovedGrants?.length??0)>0||(t.scopeChanges?.keptAdminRestrictions?.length??0)>0}function bb(t){return kb(t)||(t.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(t.scopeChanges?.adoptedRestrictions??{}).length>0}function xP(t,e,r){let n=r==="applied",o=kP(t.scopeChanges),s=n?_b(t.holdersRestamped):"",i=c=>{let l=[...c,...o];return l.length>0?` ${g.dim(l.join(" "))}`:""};if(t.action==="error")return[{stream:"err",text:` ${yo("ERROR",g.bold)}${e} \u2014 ${t.message??"cannot be created"}`},...yb(t)];let a;if(t.action==="create"){let c=t.addCapabilities?.length??0;a=` ${yo(n?"created":"create")}${e}${i([`${c} ${vP(c,"capability","capabilities")}`])}${s}`}else if(t.action==="add_capabilities"){let c=(t.addCapabilities??[]).map(l=>`+${l}`).join(", ");a=` ${yo(n?"updated":"add")}${e}${i([c])}${s}`}else t.action==="update_scopes"?a=` ${yo(n?"updated":"update")}${e}${o.length>0?i([]):` ${g.dim("scopes changed")}`}${s}`:t.action==="noop"?a=` ${yo("ok",g.dim)}${e} ${g.dim("already up to date")}`:a=` ${yo(n?"changed":"change")}${e}${i([])} ${g.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},...yb(t)]}function SP(t,e){let r=[];for(let n of t){if(!n.removedGrants||n.removedGrants.length===0)continue;let o=n.removedGrants.map(i=>`\u2212${i}`).join(" "),s=e==="applied"?"retired":"retire";r.push({stream:"out",text:` ${s} grants on ${n.name}: ${g.dim(o)}${e==="applied"?_b(n.holdersRestamped):""}`})}return r}function xb(t){let{mode:e}=t,r=t.verdicts??[],n=e==="plan"?r:r.filter(l=>l.action!=="noop"||bb(l)),o=SP(t.retired??[],e);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:g.bold(e==="preview"?"roles (preview \u2014 not applied)":"roles")}],i=n.length>0?Math.max(...n.map(l=>l.name.length)):0;for(let l of n)s.push(...xP(l,l.name.padEnd(i),e));s.push(...o);let a=n.some(l=>$P.has(l.action)),c=n.every(l=>l.action==="noop");if(a){let l=e==="plan"?" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users.":e==="preview"?" nothing was created \u2014 promoting this preview applies them.":" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.";s.push({stream:"out",text:g.dim(l)})}else if(o.length===0&&c&&n.some(l=>bb(l))){let l=e==="applied"?"no role changed":e==="preview"?"no role would change on promote":"no role would change",u=n.some(p=>kb(p))?"each note above recurs on every deploy until the manifest or the role is changed.":"the adopted values were already on the roles.";s.push({stream:"out",text:g.dim(` ${l} \u2014 ${u}`)})}return s}var $P=new Set(["create","add_capabilities","update_scopes"]);function ku(t){let{app:e,roles:r}=t;if(r===null)return[];let n=(o,s)=>[{stream:"out",text:""},{stream:"out",text:g.yellow(`! ${o}`)},{stream:"out",text:g.dim(` ${s}`)}];if(r.length===0){let o='"roles": [] retires the content values this app added to roles on an earlier deploy.';return e===null?n(o,"pass --app <slug> so the plan can name them."):Array.isArray(t.retired)?t.retired.some(s=>(s.removedGrants?.length??0)>0)?[]:[{stream:"out",text:""},{stream:"out",text:g.dim(' "roles": [] \u2014 no content value this app added is on a role, so a deploy retires nothing.')}]:n(o,"this instance's plan does not list them \u2014 read the roles section the deploy prints.")}return e===null&&r.some(o=>o.scopes!==void 0&&o.scopes!==null)?n("a declared role carries scopes, but no app was named \u2014 pass --app <slug> (or --as app:<slug>).","without it this plan cannot tell this app's earlier declarations from another app's: a scope another deploy declared on the same role is not planned (the deploy decides it, and may refuse), and content values the deploy would retire are not listed."):[]}function Sb(t){let e=t.roles;return Array.isArray(e)?{verdicts:e,retired:t.rolesRetired??[]}:e&&typeof e=="object"?{verdicts:e.verdicts??[],retired:e.retired??t.rolesRetired??[]}:{verdicts:[],retired:t.rolesRetired??[]}}var xu=".github/workflows/turbobase-release-deploy.yml",TP=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2393
2394
|
# Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
2394
2395
|
#
|
|
2395
2396
|
# Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
|
|
@@ -2491,7 +2492,7 @@ jobs:
|
|
|
2491
2492
|
--ref "\${{ github.sha }}" \\
|
|
2492
2493
|
--project . \\
|
|
2493
2494
|
--follow
|
|
2494
|
-
`,
|
|
2495
|
+
`,RP=".github/workflows/turbobase-app-deploy.yml",EP=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2495
2496
|
# Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
|
|
2496
2497
|
#
|
|
2497
2498
|
# What ships from this repo, and when:
|
|
@@ -2711,14 +2712,14 @@ jobs:
|
|
|
2711
2712
|
else
|
|
2712
2713
|
echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
|
|
2713
2714
|
fi
|
|
2714
|
-
`;function
|
|
2715
|
+
`;function $b(){return[{path:xu,content:TP}]}function Tb(){return[{path:RP,content:EP}]}pa();var PP=[".mcp.json"];function Pb(t,e=PP){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
|
|
2715
2716
|
`).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(r)),o=e.filter(i=>!n.has(r(i)));return o.length===0?null:`${t===""||t.endsWith(`
|
|
2716
2717
|
`)?t:`${t}
|
|
2717
2718
|
`}
|
|
2718
2719
|
# Added by the Turbobase scaffold.
|
|
2719
2720
|
${o.join(`
|
|
2720
2721
|
`)}
|
|
2721
|
-
`}var
|
|
2722
|
+
`}var AP=`# Turbobase Extensions \u2014 extension project
|
|
2722
2723
|
|
|
2723
2724
|
This directory authors **Turbobase extensions** (hooks today; conduits later)
|
|
2724
2725
|
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
@@ -2787,8 +2788,8 @@ order is the signal, and it is the part the product team reads first.
|
|
|
2787
2788
|
|
|
2788
2789
|
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
2789
2790
|
updating a test. It is checked into the repo so the whole team sees it.
|
|
2790
|
-
|
|
2791
|
-
`;function
|
|
2791
|
+
`,CP=JSON.stringify({mcpServers:{"turbobase-authoring":{type:"http",url:"__BASE_URL__/mcp/authoring",headers:{Authorization:"Bearer __PAT__"}},turbobase:{type:"http",url:"__BASE_URL__/mcp"}}},null,2)+`
|
|
2792
|
+
`;function IP(t){return`---
|
|
2792
2793
|
name: generate-types
|
|
2793
2794
|
description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
2794
2795
|
---
|
|
@@ -2799,7 +2800,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
|
|
|
2799
2800
|
|
|
2800
2801
|
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
2801
2802
|
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
2802
|
-
`}var
|
|
2803
|
+
`}var OP=`---
|
|
2803
2804
|
name: mock-test
|
|
2804
2805
|
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
2805
2806
|
---
|
|
@@ -2808,7 +2809,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
|
2808
2809
|
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
2809
2810
|
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
2810
2811
|
fixture for each branch (a passing record and a rejecting record).
|
|
2811
|
-
`,
|
|
2812
|
+
`,NP=`---
|
|
2812
2813
|
name: deploy
|
|
2813
2814
|
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
2814
2815
|
---
|
|
@@ -2816,7 +2817,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
|
2816
2817
|
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
2817
2818
|
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
2818
2819
|
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
2819
|
-
`;function
|
|
2820
|
+
`;function LP(t){return`# ${t} \u2014 Turbobase app
|
|
2820
2821
|
|
|
2821
2822
|
This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
|
|
2822
2823
|
same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
|
|
@@ -3179,7 +3180,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
|
3179
3180
|
review, so what you write reaches the knowledge base and the product team instead
|
|
3180
3181
|
of evaporating at the end of the session. Keep the section headings exactly as
|
|
3181
3182
|
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
3182
|
-
`}var
|
|
3183
|
+
`}var bo="customer",Ln="email",jP="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",zP=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
|
|
3183
3184
|
//
|
|
3184
3185
|
// It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
|
|
3185
3186
|
// the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
|
|
@@ -3198,8 +3199,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
|
|
|
3198
3199
|
// Pure and credentials-free: no secrets, no network, no Node builtins, one
|
|
3199
3200
|
// concern per file, nothing factored into a shared module (the sandbox fences
|
|
3200
3201
|
// every import except the SDK).
|
|
3201
|
-
`;function
|
|
3202
|
-
`;return[{path:t.relativePath,content:`${
|
|
3202
|
+
`;function DP(){let t=yr("hook",{recordType:bo,event:"before_save",template:"enforce-format",field:Ln,regex:jP,id:`app:${bo}:${Ln}-format`,description:`Reject a ${bo} write whose ${Ln} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:bo,event:"before_save",payload:r},expect:n},null,2)+`
|
|
3203
|
+
`;return[{path:t.relativePath,content:`${zP}${t.content}`},{path:`samples/${bo}.${Ln}-ok.json`,content:e({company_name:"Acme Supply",[Ln]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${bo}.${Ln}-malformed.json`,content:e({company_name:"Acme Supply",[Ln]:"ada-at-example"},"reject","a malformed address is rejected")}]}var MP="---\nname: preview-app\ndescription: Run the app locally against the instance and check it in a browser. Use after editing the app, before pushing.\n---\n\nStart the dev server NON-BLOCKING (`npm run dev` detached) \u2014 a foreground dev\nserver hangs the session. It proxies `/rest`, `/realtime`, `/v1`, `/auth`,\n`/login` and `/_app` to the instance, so localhost behaves same-origin and the\nsession cookie applies.\n\n**The app is at `http://localhost:3000/a/<slug>/`, not `/`.** Vite serves under\n`base` in dev too; `/` 302s there. Probing `/` and reading the 302 as \"broken\" is\nthe easy mistake here.\n\nThen actually look at it. A build that compiles and a lint that passes prove the\ncode is well-formed, not that it runs: a guard that throws during render, a\nPostgREST embed that 400s because the FK doesn't exist on this instance, an empty\nstate standing in for a failed query \u2014 none of those move the build signal.\n\n- Unauthenticated `/a/<slug>/` returns 200 with the SPA shell, and so does a deep\n client route like `/a/<slug>/customers/42` (Vite's SPA fallback). A 500 means a\n component threw \u2014 fix it, don't ship it.\n- `/login` returns the INSTANCE's sign-in page through the proxy. The app itself\n has no login route and should never grow one.\n- If a list renders empty, check the network tab before assuming there's no data:\n a 400 from PostgREST and a genuinely empty table look identical on screen.\n- `permission denied for table <x>` (SQLSTATE `42501`) usually means NOT SIGNED\n IN, not a role problem: with no session cookie PostgREST answers as the\n anonymous role and every table denies. Load `/login` through the proxy and\n sign in before reading the error as an RLS grant issue.\n\nVite reads `vite.config.ts` and `.env` only at boot \u2014 restart after changing either.\n",UP=`---
|
|
3203
3204
|
name: ship-app
|
|
3204
3205
|
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
3205
3206
|
---
|
|
@@ -3242,7 +3243,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
|
|
|
3242
3243
|
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
3243
3244
|
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
3244
3245
|
project root and DO travel \u2014 deploy reads them.
|
|
3245
|
-
`,
|
|
3246
|
+
`,qP=`---
|
|
3246
3247
|
name: business-rule-to-hook
|
|
3247
3248
|
description: Decide where a rule belongs \u2014 a hook on the instance (enforced for every writer, reusable by every app) or the app's UI. Use whenever you are about to write a validation, threshold, or "you can't do that" check.
|
|
3248
3249
|
---
|
|
@@ -3310,7 +3311,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
|
|
|
3310
3311
|
standing rules for every agent on the instance \u2014 see the record-learning skill.
|
|
3311
3312
|
A rule enforced in code and nowhere written down gets re-litigated by the next
|
|
3312
3313
|
person.
|
|
3313
|
-
|
|
3314
|
+
`,FP="---\nname: write-a-process\ndescription: Write, deploy and run a Turbobase process (defineProcess) \u2014 a chain of record writes, or an eachRow migration that moves many records. Use whenever you create or change a file under processes/, call POST /v1/processes/:id, or debug a process run.\n---\n\nThe contract is the published guide \u2014 read it before writing one:\n`https://docs.turbobase.io/extending/writing-processes/`, and for moving data\nbetween connected systems `https://docs.turbobase.io/extending/migrating-between-systems/`.\nStart from its **A migration recipe** section for any `eachRow` process.\n\nCheck these before you conclude the platform is wrong:\n\n1. **Instance version.** `update` steps, `ctx.row` in a deployed process,\n slices that queue themselves and `{ kind: 'process' }` schedules all need\n **v1.38.0** or later. On an older instance an `update` step CREATES a row.\n2. **Changing a row = `update:` on the step**, e.g.\n `update: { pgRowId: (ctx) => ctx.row.pg_row_id }`, with `pg_row_id` in the\n `outstanding` select. `build` returns `{ parent, lines? }` only \u2014 an id\n returned from `build` is ignored and the step creates.\n3. **The first `id: '\u2026'` in the file must be the process id**, as a literal.\n `ext deploy` stores the file under that string and refuses it with\n `extension_id_mismatch` when the module defines another id \u2014 fix the file,\n do not rename the deploy. `(replaced existing)` in its output means an\n existing copy was replaced, and the line names the id it used.\n4. **The invoke body IS the input** \u2014 no `{ input: \u2026 }` envelope.\n5. **A run continues itself.** Invoke once (async); it queues its own next\n slice. For unattended runs use a `{ kind: 'process' }` entry in\n `turbobase/schedules.json`. From a terminal, `turbobase processes invoke\n <id> --input '<json>'` starts one (an administrator's `extensions:deploy`\n token; the run writes as that person). A process cannot start a process.\n6. **`outstanding` is read once per slice**, and must stop returning a row once\n it is done \u2014 otherwise update steps re-run every slice.\n7. **NetSuite transaction creates need `lines`** (`ATOMIC_WRITE_REQUIRED`).\n On `write_settle_conflict` the record EXISTS upstream: never re-save it; the\n id is on `record_write_state.external_id`. Link the row to it with\n `turbobase data settle <recordType> <pgRowId>`\n (`POST /v1/data/<recordType>/settle`).\n8. **Undo a finished run with `turbobase processes rollback <runId>`** \u2014 it\n deletes only records that run created (never one an `update` step changed),\n paced by its own rollback cap rather than the customer delete cap. Until\n every source delete is sent, the run's `reason` says so.\n";function BP(t){return`---
|
|
3314
3315
|
name: record-learning
|
|
3315
3316
|
description: Append to INSTANCE-LEARNINGS.md or TURBOBASE-FEEDBACK.md. Use the MOMENT you establish a fact about how this instance is set up, or the platform costs you time \u2014 in the same change, not at the end of the task and not when asked.
|
|
3316
3317
|
---
|
|
@@ -3365,7 +3366,7 @@ earlier claim" and still publish.
|
|
|
3365
3366
|
|
|
3366
3367
|
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
3367
3368
|
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
3368
|
-
`}function
|
|
3369
|
+
`}function ZP(t){return`# What this instance's source system actually does
|
|
3369
3370
|
|
|
3370
3371
|
Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
3371
3372
|
Written for the knowledge base, and **everything here is verified against real
|
|
@@ -3496,7 +3497,7 @@ finding has not been handed to the knowledge base yet.
|
|
|
3496
3497
|
and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
|
|
3497
3498
|
already live, which is worth reading before adding another rule. -->
|
|
3498
3499
|
|
|
3499
|
-
`}function
|
|
3500
|
+
`}function VP(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
|
|
3500
3501
|
|
|
3501
3502
|
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
3502
3503
|
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
@@ -3576,7 +3577,7 @@ Expected / happened / cost / fix.
|
|
|
3576
3577
|
and what it would replace. These are the highest-signal entries in the file:
|
|
3577
3578
|
each one is a page downloading rows to fold that it could have asked for
|
|
3578
3579
|
folded. -->
|
|
3579
|
-
`}function
|
|
3580
|
+
`}function HP(t,e){let r=e?`
|
|
3580
3581
|
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
3581
3582
|
# --records focus a previous run stamped into the file, so a refresh never
|
|
3582
3583
|
# narrows what an agent deliberately widened.
|
|
@@ -3607,8 +3608,8 @@ ${r}
|
|
|
3607
3608
|
# surface unticked items at the start of a session.
|
|
3608
3609
|
turbobase project adopt -o ADOPT.md >/dev/null \\
|
|
3609
3610
|
|| echo "turbobase: \\\`turbobase project adopt\\\` failed (its error is above) \u2014 ADOPT.md was NOT refreshed." >&2
|
|
3610
|
-
`}var
|
|
3611
|
-
name: ${
|
|
3611
|
+
`}var Ab="Turbobase consultant",KP="turbobase-consultant",WP=`---
|
|
3612
|
+
name: ${Ab}
|
|
3612
3613
|
description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
|
|
3613
3614
|
keep-coding-instructions: true
|
|
3614
3615
|
---
|
|
@@ -3681,8 +3682,8 @@ exists on purpose.
|
|
|
3681
3682
|
- Do not show a stack trace. Say what broke and what you are doing about it.
|
|
3682
3683
|
- Do not apologise repeatedly or pad with "great question".
|
|
3683
3684
|
- Do not use a table when a sentence works.
|
|
3684
|
-
`,
|
|
3685
|
-
`,
|
|
3685
|
+
`,GP=JSON.stringify({outputStyle:Ab,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"}]}]}},null,2)+`
|
|
3686
|
+
`,JP=`#!/usr/bin/env bash
|
|
3686
3687
|
# PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
|
|
3687
3688
|
#
|
|
3688
3689
|
# Advisory only: exits 0 always, and adds a note for the agent when the edited
|
|
@@ -3699,7 +3700,7 @@ set -uo pipefail
|
|
|
3699
3700
|
command -v node >/dev/null 2>&1 || exit 0
|
|
3700
3701
|
|
|
3701
3702
|
exec node "$(dirname "$0")/check-rule-placement.mjs"
|
|
3702
|
-
`,
|
|
3703
|
+
`,YP=String.raw`/**
|
|
3703
3704
|
* Is the file that was just edited enforcing a business rule inside the SPA?
|
|
3704
3705
|
*
|
|
3705
3706
|
* Reads the PostToolUse payload on stdin, and when BOTH signals are present —
|
|
@@ -3768,7 +3769,7 @@ process.stdout.write(
|
|
|
3768
3769
|
},
|
|
3769
3770
|
}),
|
|
3770
3771
|
);
|
|
3771
|
-
`,
|
|
3772
|
+
`,XP=`---
|
|
3772
3773
|
name: roles-and-permissions
|
|
3773
3774
|
description: Decide who can open a screen and who can change a record \u2014 declare roles (and their scopes \u2014 row restrictions and Slack channel content grants) in public/turbobase.json, gate the UI on capabilities, and turn a denial into a message that names the role to ask for. Use when adding a screen, a nav item, a write button, a role, a scope, a screen that reads Slack history, or answering "who can see/do X".
|
|
3774
3775
|
---
|
|
@@ -4001,7 +4002,7 @@ a denial look like emptiness.
|
|
|
4001
4002
|
- Does every write catch \`TurbobasePermissionError\`?
|
|
4002
4003
|
- Did you run \`turbobase apps plan . --app <slug>\`?
|
|
4003
4004
|
- Did you tell the user their administrator still has to ASSIGN the role?
|
|
4004
|
-
`,
|
|
4005
|
+
`,QP=`---
|
|
4005
4006
|
name: app-design
|
|
4006
4007
|
description: How a Turbobase app should look and behave. Read the published design system first, then the display rules here that stop a working build showing wrong data. Use before building any screen.
|
|
4007
4008
|
---
|
|
@@ -4096,7 +4097,7 @@ The design system covers the look. Two rules it does not:
|
|
|
4096
4097
|
Load it in the browser and check: does it render with ZERO rows, with ONE row,
|
|
4097
4098
|
and with several hundred? Does it survive the query failing? Does tab reach every
|
|
4098
4099
|
control, with a visible focus ring? A green \`npm run build\` proves none of these.
|
|
4099
|
-
`,
|
|
4100
|
+
`,ha="",Rb=String.raw`{
|
|
4100
4101
|
"_comment": [
|
|
4101
4102
|
"Declarative sync config — part of this repo's desired state.",
|
|
4102
4103
|
" turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
|
|
@@ -4118,7 +4119,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
4118
4119
|
"fields": [],
|
|
4119
4120
|
"tables": []
|
|
4120
4121
|
}
|
|
4121
|
-
|
|
4122
|
+
`,Eb=String.raw`{
|
|
4122
4123
|
"_comment": [
|
|
4123
4124
|
"Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
|
|
4124
4125
|
"Removing an entry does NOT remove the schedule unless you pass --prune.",
|
|
@@ -4134,93 +4135,95 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
4134
4135
|
],
|
|
4135
4136
|
"schedules": []
|
|
4136
4137
|
}
|
|
4137
|
-
`,
|
|
4138
|
+
`,eA=t=>`node_modules/
|
|
4138
4139
|
|
|
4139
4140
|
# Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
|
|
4140
4141
|
.mcp.json
|
|
4141
4142
|
|
|
4142
4143
|
.DS_Store
|
|
4143
|
-
`;function Su(t={}){let e
|
|
4144
|
-
|
|
4145
|
-
|
|
4144
|
+
`;function Su(t={}){let e=CP.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:t.appSlug}:void 0,s=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:eA(r)},{path:"INSTANCE-LEARNINGS.md",content:ZP(o)},{path:"TURBOBASE-FEEDBACK.md",content:VP(o)},{path:".claude/settings.json",content:GP},{path:`.claude/output-styles/${KP}.md`,content:WP},{path:".claude/skills/generate-types/SKILL.md",content:IP(n)},{path:".claude/skills/record-learning/SKILL.md",content:BP(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:qP},{path:".claude/skills/write-a-process/SKILL.md",content:FP},{path:".claude/hooks/session-start-refresh-types.sh",content:HP(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:JP,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:YP}];return r?[{path:"CLAUDE.md",content:LP(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:MP},{path:".claude/skills/ship-app/SKILL.md",content:UP},{path:".claude/skills/app-design/SKILL.md",content:QP},{path:".claude/skills/roles-and-permissions/SKILL.md",content:XP},...DP(),{path:"conduits/.gitkeep",content:ha},{path:"turbobase/sync.json",content:Rb},{path:"turbobase/schedules.json",content:Eb},...Tb()]:[{path:"CLAUDE.md",content:AP},...s,{path:".claude/skills/mock-test/SKILL.md",content:OP},{path:".claude/skills/deploy/SKILL.md",content:NP},{path:"hooks/.gitkeep",content:ha},{path:"conduits/.gitkeep",content:ha},{path:"samples/.gitkeep",content:ha},{path:"turbobase/sync.json",content:Rb},{path:"turbobase/schedules.json",content:Eb}]}import{promises as Tu}from"node:fs";import{dirname as tA,join as rr,resolve as Lb}from"node:path";function Ib(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var bs="bundle.json",ma="turbobase";function Ob(t){let e;try{e=JSON.parse(t)}catch(c){throw new Error(`bundle.json is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=c=>Array.isArray(c)?c:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return $u(a)}function $u(t){let e=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(Cb)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Cb)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Cb(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Nb(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}var ga="hooks",ya="conduits",jb="processes",Gr="turbobase/sync.json",Jr="turbobase/schedules.json";function Ru(t){let e=l=>{let u=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return u?u[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let l=e("source")??"standalone";return s?{id:s,recordType:"*",event:"invoke",source:l,extensionKind:"process"}:null}if(r){let l=e("on"),u=e("source");return!s||!i||!l||!u?null:{id:s,recordType:i,event:l,source:u,extensionKind:"conduit"}}let a=e("event"),c=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:c,extensionKind:"hook"}}function Eu(t,e){if(!t||typeof t!="object")return null;let r=t;if(r.error!=="extension_id_mismatch")return null;let n=String(r.claimed??""),o=String(r.definitionId??"");return`${e?`${e}: `:""}refused (extension_id_mismatch) \u2014 the first \`id:\` literal in the file is '${n}', but the module defines '${o}'. Nothing was deployed.
|
|
4145
|
+
The deploy is stored under the first \`id:\` literal, and the runtime serves the module's own id, so the two have to agree.
|
|
4146
|
+
Fix: write \`id: '${o}'\` as a string literal on the define call, and make sure no comment, constant, step or inlined helper above it carries an \`id:\` literal.`}function zb(t){return t==="written"?"new":t==="duplicate"?"replaced existing":t}function Pu(t){return/\bdefineProcess\s*[<(]/.test(t)?"could not read a quoted id \u2014 is it a defineProcess({...}) file? A process binds to no single record type; its steps carry their own.":/\bdefineConduit\s*[<(]/.test(t)?"could not read id / on / from.source / from.recordType \u2014 is it a defineConduit({...}) file?":"could not read id / recordType / event \u2014 is it a defineHook({...}) file?"}async function ws(t){let e;try{e=await Tu.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await ws(rr(t,n.name)))r.push(`${n.name}/${o}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function fa(t,e){let r;try{r=await Tu.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function rA(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function nA(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function oA(t){let e={name:String(t.name??""),scheduleKind:String(t.scheduleKind??"cron"),scheduleExpr:String(t.scheduleExpr??""),scheduleTz:String(t.scheduleTz??"UTC"),body:t.body??{}};return typeof t.status=="string"&&(e.status=t.status),e}async function Db(t=process.cwd()){let e=Lb(t),[r,n,o]=await Promise.all([ws(rr(e,ga)),ws(rr(e,ya)),ws(rr(e,jb))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([fa(rr(e,Gr),Gr).catch(()=>{}),fa(rr(e,Jr),Jr).catch(()=>{})]);return s!==void 0||i!==void 0}async function Mb(t=process.cwd(),e={}){let r=Lb(t),n=Ib(e.tenant),o=[],s=[];for(let c of[ga,ya,jb])for(let l of await ws(rr(r,c))){let u=`${c}/${l}`,p=await Tu.readFile(rr(r,c,l),"utf8"),b=e.inline?await e.inline(p,tA(rr(r,c,l))):p,f=Ru(b);if(!f){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(b)&&s.push({file:u,reason:Pu(b)});continue}let m={id:f.id,kind:f.extensionKind,recordType:f.recordType,event:f.event,source:f.source,sourceCode:b};f.extensionKind==="conduit"?n.conduits.push(m):n.hooks.push(m),o.push(u)}let i=await fa(rr(r,Gr),Gr);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Gr} must be a JSON object with "fields" and/or "tables".`);let c=i;for(let l of Array.isArray(c.fields)?c.fields:[])n.sync.fields.push(rA(l));for(let l of Array.isArray(c.tables)?c.tables:[])n.sync.tables.push(nA(l));o.push(Gr)}let a=await fa(rr(r,Jr),Jr);if(a!==void 0){let c=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(c===null)throw new Error(`${Jr} must be a JSON array, or an object with a "schedules" array.`);for(let l of c)n.schedules.push(oA(l));o.push(Jr)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(c=>c.event==="before_save").map(c=>c.id).sort(),{manifest:$u(n),contributed:o,unparsed:s}}import{promises as Iu}from"node:fs";import{resolve as uA}from"node:path";var sA="For app developers \u2014 adopt these";function Ub(t){let e=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(t.trim());return e?{core:[Number(e[1]),Number(e[2]??0),Number(e[3]??0)],prerelease:e[4]??""}:null}function qb(t,e){let r=Ub(t),n=Ub(e);if(!r&&!n)return 0;if(!r)return-1;if(!n)return 1;for(let o=0;o<3;o++){let s=(r.core[o]??0)-(n.core[o]??0);if(s!==0)return s}return r.prerelease===n.prerelease?0:r.prerelease?n.prerelease?r.prerelease<n.prerelease?-1:1:-1:1}function iA(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var TZ=iA(sA);us();er();var aA=t=>new Promise(e=>setTimeout(e,t));function Fb(t){return t.stage==="completed"||t.stage==="failed"}function cA(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function lA(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
|
|
4147
|
+
`))r(i)}return n}async function Au(t,e={}){let r=e.sink??(b=>{process.stdout.write(`${b}
|
|
4148
|
+
`)}),n=e.sleep??aA,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(b=>r(cA(b))),a=e.onPoll,c="",l="",u=b=>{a?.(b),b.stage!==l&&i(b),c=lA(b,c,r),l=b.stage},p=await t();if(u(p),Fb(p))return p;for(let b=0;b<s;b+=1)if(await n(o),p=await t(),u(p),Fb(p))return p;return p}var _=t=>{process.stdout.write(`${t}
|
|
4146
4149
|
`)},q=t=>{process.stderr.write(`${t}
|
|
4147
|
-
`)};function k(t){q(g.red(`turbobase: ${t}`)),process.exit(1)}var
|
|
4148
|
-
`)){let o=
|
|
4150
|
+
`)};function k(t){q(g.red(`turbobase: ${t}`)),process.exit(1)}var wo=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Bb(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&wu(!1)}async function G(t){let e=await Qt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Cr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";k(`not signed in to ${Ut(t)}.${n} Run \`turbobase auth login --base-url ${Ut(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&k("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it())try{let n=await at("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await Xi(n);let o=await Qt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}k(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function ee(t,e,r){if(!(t instanceof se)||t.status!==403)return;t.body?.error==="approval_required"&&k(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),k(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Cu(t,e,r){let n=r?Number(r):void 0;if(la()){let s=vu(e),i;try{i=await Au(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),k(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await Au(t,{sink:_,intervalMs:n})}catch(s){k(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&k(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),_(`${e} ${o.stage}.`)}var dA=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function pA(t){try{let e=await Iu.readFile(t,"utf8");return dA.exec(e)?.[1]??null}catch{return null}}var hA=/GENERATED by `turbobase project adopt`/,Vb=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,mA=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Zb(t){let e=[],r=null;for(let n of t.split(`
|
|
4151
|
+
`)){let o=Vb.exec(n);if(o){r={version:o[1],items:[]},e.push(r);continue}if(/^#{1,6}[ \t]/.test(n)){r=null;continue}if(!r)continue;let s=mA.exec(n);if(s){let a=s[2].trim();r.items.push({key:a.replace(/\s+/g," "),done:s[1]!==" ",text:a,extra:[]});continue}let i=r.items[r.items.length-1];i&&n.trim()!==""&&i.extra.push(n)}return e}function fA(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
|
|
4149
4152
|
`)).join(`
|
|
4150
4153
|
`);return`## v${t.version}
|
|
4151
4154
|
|
|
4152
|
-
${e}`}function
|
|
4153
|
-
`),a=i.findIndex(u=>
|
|
4155
|
+
${e}`}function gA(t,e){let r=Zb(t);if(r.length===0&&!hA.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of Zb(e)){let p=n.get(u.version);n.delete(u.version);let b=new Set(u.items.map(m=>m.key)),f=u.items.map(m=>{let w=p?.items.find($=>$.key===m.key);return w?{...m,done:w.done,extra:w.extra}:m});for(let m of p?.items??[])b.has(m.key)||m.done||(f.push(m),s+=1);o.push({version:u.version,items:f})}for(let u of n.values()){let p=u.items.filter(b=>!b.done);p.length!==0&&(s+=p.length,o.push({version:u.version,items:p}))}o.sort((u,p)=>qb(p.version,u.version));let i=e.split(`
|
|
4156
|
+
`),a=i.findIndex(u=>Vb.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
|
|
4154
4157
|
`).replace(/\s+$/,"");return{markdown:o.length===0?`${c}
|
|
4155
4158
|
`:`${c}
|
|
4156
4159
|
|
|
4157
|
-
${o.map(
|
|
4160
|
+
${o.map(fA).join(`
|
|
4158
4161
|
|
|
4159
4162
|
`)}
|
|
4160
|
-
`,carried:s}}function
|
|
4161
|
-
|
|
4162
|
-
`,f=await
|
|
4163
|
-
`);for(let n of r.slice(0,
|
|
4164
|
-
`)),_(
|
|
4165
|
-
`))}catch(l){if(l instanceof
|
|
4166
|
-
`))}async function
|
|
4167
|
-
`))r.push(` ${g.dim("|")} ${a}`)}r.push("")}),r}function
|
|
4168
|
-
`)),_(
|
|
4169
|
-
`)).trim();continue}e[i]=
|
|
4163
|
+
`,carried:s}}function Hb(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:r,token:n}=await G(e.baseUrl),o=uA(process.cwd(),e.out),s=e.since?.trim()||await pA(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),c=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});c.ok||k(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let l=await c.json();if(!l.available){_(`${r} ships no release notes to adopt from (nothing written).`);return}let u=l.releases.reduce(($,R)=>$+R.items.length,0);if(u===0){_(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${l.currentVersion?` (instance is on v${l.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let p=l.currentVersion??l.releases[0]?.version??"",b=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${p}. Re-run to refresh; delete this file once every line is done. -->
|
|
4164
|
+
|
|
4165
|
+
`,f=await Iu.readFile(o,"utf8").catch(()=>null),m=l.markdown,w=0;if(f!==null&&f.trim()!==""){let $=gA(f,l.markdown);$||k(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),m=$.markdown,w=$.carried}await Iu.writeFile(o,b+m,"utf8"),_(`wrote ${o} \u2014 ${u} item(s) across ${l.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${w>0?`, keeping ${w} unticked item(s) already in the file`:""}.`)})}er();var _s=["suggested_kb_edit","kb_correction"];var yA=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function bA(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var MZ=new Map(yA.map(t=>[bA(t.heading),t]));var UZ=new RegExp(["^the (situation|context|background|problem|ask|point|gist|upshot|part\\b)","^the (one|two|three|four|five|six|seven|eight|nine|ten|\\d{1,2}) \\w+s?\\b","^(on|about) \\w+ing\\b","^(concrete|specific|possible|suggested) \\w+","^what (we|i|you)(\\b|'d| would| could| should)","^(background|summary|context|recommendations?|next steps|takeaways?|conclusion|in short|tl;?dr)\\b","^why (this|that|it) matters\\b"].join("|"),"i");function wA(t){return t.diff??!!t.dryRun}var _A={update_page:"append to the existing page",new_page:"create a NEW page"},Or=(t,e)=>` ${g.dim(t.padEnd(11))}${e}`,Gb=t=>t.ownerEmail??t.ownerId;function _o(t){return!t.needsPageRef&&!t.blockedBy}var ba=t=>g.green(t?` + ${t}`:" +"),vA=t=>g.red(t?` - ${t}`:" -"),jn=t=>g.dim(` ${t}`),kA=` ${g.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Ou=80;function xA(t){let e=[kA];t.target?(e.push(jn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(vA(`visibility: ${t.target.visibility}`)),e.push(ba("visibility: admin"))):e.push(jn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(jn("title, slug, evidence: untouched")),e.push(jn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(jn("turbobase.document \xB7 new")),e.push(ba(`title: ${t.pageTitle}`)),e.push(ba("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(jn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(jn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
4166
|
+
`);for(let n of r.slice(0,Ou))e.push(ba(n?` ${n}`:""));return r.length>Ou&&e.push(g.yellow(` \u2026 ${r.length-Ou} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function SA(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${g.bold(n.pageTitle)}`),r.push(Or("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:g.dim("new \u2014 no existing page matches"))),r.push(Or("action",_o(n)?_A[n.action]:g.red("SKIP \u2014 nothing is written"))),n.needsPageRef){let a=[...new Set(i.map(c=>c.kb_page_ref?.trim()).filter(c=>!!c))];r.push(Or("unresolved",g.red((a.length>0?`no page matches ${a.map(c=>`"${c}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.push(Or("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let c=a.verdict?` ${g.dim(`\xB7 ${a.verdict}`)}`:"",l=a.kb_page_ref?` ${g.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${g.dim("\xB7")} ${a.title.trim()}${l}${c}`)}),r.push(Or("confidence",n.withdraws?g.red("WITHDRAWN from readers (text untouched)"):g.dim("untouched"))),n.supersedes&&r.push(Or("supersedes",g.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(Or("blocked",g.red(`unpublished work on this page belongs to ${Gb(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Or("ambiguous",g.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),(n.similarTo?.length??0)>0){let a=(n.similarTo??[]).map(c=>{let l=t.findIndex(p=>p.key===c),u=l>=0?t[l]:void 0;return u?`#${l+1} "${u.pageTitle}"`:c});r.push(Or("similar",g.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&_o(n)&&r.push(...xA(n)),r.push("")}),r}function $A(t){let e=l=>t.filter(l).length,r=t.reduce((l,u)=>l+u.entries.length,0),n=e(l=>l.withdraws),o=e(l=>l.blockedBy!=null),s=e(l=>l.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${e(_o)} page(s)`,`${e(l=>l.action==="update_page"&&_o(l))} appended`,`${e(l=>l.action==="new_page"&&_o(l))} created (unpublished)`,...s>0?[g.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?g.red(`${n} page(s) WITHDRAWN from readers`):g.dim("no page withdrawn"),c=o>0?` \xB7 ${g.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${c}`}function TA(t,e){let r=new Map(e.map(o=>[o.key,o])),n=[];for(let o of t){let s=r.get(o.key),i=o.pageTitle||s?.pageTitle||o.key;if(o.skipped==="blocked_by_draft_owner"){n.push(`${g.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Gb(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let c=[...new Set((s?.entries??[]).map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];n.push(`${g.yellow("skipped")} ${i} \u2014 `+(c.length>0?`no page matches ${c.map(l=>`"${l}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${g.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?g.green("created "):g.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${g.bold(o.documentId??"?")}`+(o.created?g.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${g.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${g.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${g.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Kb(t){if(t instanceof se){let e=t.body;t.status===403&&e?.reason==="admin_required"&&k("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&k("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}ee(t,"extensions:deploy","learnings push-kb")}async function vs(t,e){let r;try{r=await ie("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof se&&o.status===404?q(g.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):Ry(o)?q(g.yellow(Wb(o))):q(g.yellow(`could not re-read the pushed markdown: ${Wb(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return q(g.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),r;let n=[`${r.filesScanned} file(s) scanned`];return r.docsIngested>0&&n.push(`${r.docsIngested} changed`),r.docsUnchanged>0&&n.push(`${r.docsUnchanged} unchanged`),n.push(`${r.entriesAdded} new finding(s)`),r.entriesDuplicate>0&&n.push(`${r.entriesDuplicate} already known`),r.parseSkipped>0&&n.push(g.yellow(`${r.parseSkipped} unparseable`)),q(g.dim(n.join(" \xB7 "))),r}function Wb(t){return t instanceof Error?t.message:String(t)}async function Jb(t,e=r=>new K(r)){t.section&&!_s.includes(t.section.trim())&&k(`unknown --section "${t.section}" \u2014 expected one of ${_s.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await G(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s=await vs(n,t.app),i;try{i=await ie("reading the pending queue",()=>n.learningsPending(o))}catch(l){Kb(l),k(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){q(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}q(i.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${i.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(_(SA(i.items,{diff:wA(t)}).join(`
|
|
4167
|
+
`)),_($A(i.items)),t.dryRun){q(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(_o);if(a.length===0){q(g.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let c=a.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!it()){q(g.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await at(`Push ${c} finding(s) into the knowledge base as ${a.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await ie("writing pages",()=>n.learningsPushKb(i.planToken,o));_(TA(l.applied,i.items).join(`
|
|
4168
|
+
`))}catch(l){if(l instanceof se&&l.status===409){q(g.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),q(`re-run \`${wo} kb push\` to review the current plan.`),process.exitCode=2;return}Kb(l),q(g.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}er();var vo=t=>new K(t);async function ko(t,e){let r=await G(t.baseUrl);return e(r)}async function wa(t,e,r,n){return n.yes?!0:it()?await at(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function RA(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function Yb(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function EA(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${Yb(g.bold(s.slug),e)} ${Yb(RA(s),10)} ${g.dim(s.path)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} page(s) \xB7 ${n} readable \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function Xb(t,e=vo){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await ko(t,e),o;try{o=await ie("reading the knowledge base",()=>n.docsList(r))}catch(s){ee(s,"docs:publish","read the knowledge base"),k(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}_(EA(o).join(`
|
|
4169
|
+
`))}async function Qb(t,e,r=vo){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await ko(e,r);if(!await wa(`Publish ${n.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",e))return;let i;try{i=await ie("publishing",()=>o.docsPublish(n))}catch(c){ee(c,"docs:publish","publish a page"),k(`publish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.published.map(c=>c.slug);_(g.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),q(g.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function ew(t,e,r=vo){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let o=await ko(e,r);if(!await wa(`Hide ${n.length} page(s) from readers?`,"Yes \u2014 unpublish them","they drop out of the reader snapshot immediately; the text and its history are kept",e))return;let i;try{i=await ie("unpublishing",()=>o.docsUnpublish(n))}catch(c){ee(c,"docs:publish","unpublish a page"),k(`unpublish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.unpublished.map(c=>c.slug);_(g.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),q(g.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function tw(t,e=vo){let r=await ko(t,e),n;try{n=await ie("reading the releases",()=>r.docsVersions())}catch(o){ee(o,"docs:publish","read the knowledge-base releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){_("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?g.green("current"):g.dim(" ");_(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${g.dim(o.published_by)}`:""}`),o.release_note&&_(` ${g.dim(o.release_note)}`)}}async function rw(t,e,r=vo){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await ko(e,r);if(await wa(`Roll the knowledge base back to release v${n}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await ie("rolling back",()=>o.docsRollback(n));_(g.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){ee(i,"docs:publish","roll the knowledge base back"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function nw(t,e,r=vo){let n=(t??"").trim();n||k("name the page slug to delete. `turbobase kb list` shows them.");let o=await ko(e,r);if(await wa(`Delete "${n}"?`,"Yes \u2014 delete it","it drops out of the tree and every reader release; its subtree goes with it, and it stays restorable from the editor\u2019s trash",e))try{let i=await ie("deleting",()=>o.docsDelete(n));_(g.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){ee(i,"docs:publish","delete a page"),k(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}er();function PA(t){return t.diff??!!t.dryRun}function AA(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?g.green("new rule"):g.yellow("amend rule"),i=n.targetPublished?` ${g.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${g.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${g.dim(n.description)}`);for(let a of n.entries)r.push(` ${g.dim("\xB7")} ${g.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
|
|
4170
|
+
`))r.push(` ${g.dim("|")} ${a}`)}r.push("")}),r}function CA(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(g.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function ow(t,e=r=>new K(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let r=await G(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await vs(n,t.app),i;try{i=await ie("reading the pending rules",()=>n.rulesPending(o))}catch(c){ee(c,"extensions:deploy","read the pending rules"),k(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){q(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}q(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(_(AA(i.items,{diff:PA(t)}).join(`
|
|
4171
|
+
`)),_(CA(i.items)),t.dryRun){q(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((c,l)=>c+l.entries.length,0);if(!t.yes){if(!it()){q(g.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await at(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await ie("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof se&&c.status===409&&k("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),k(`push failed: ${c instanceof Error?c.message:String(c)}`)}_(g.green(`wrote ${i.items.length} draft rule(s).`)),q(g.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as zA,readFile as DA,stat as MA}from"node:fs/promises";import{join as aw,resolve as UA}from"node:path";var Nr=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},IA=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function sw(t){let e=t.replace(/^/,""),r=IA.exec(e);if(!r)throw new Nr("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=OA(n??""),i=s.name,a=s.description;if(!i)throw new Nr("SKILL.md frontmatter is missing required `name`");if(!a)throw new Nr("SKILL.md frontmatter is missing required `description`");let c=new Set(["name","description","license","version"]),l=Object.entries(s).filter(([p])=>!c.has(p));return{frontmatter:{name:i,description:a,...s.license?{license:s.license}:{},...s.version?{version:s.version}:{},...l.length?{extra:Object.fromEntries(l)}:{}},body:(o??"").trim()}}function OA(t){let e={},r=t.split(/\r?\n/),n=0;for(;n<r.length;){let o=r[n]??"";if(!o.trim()||o.trim().startsWith("#")){n+=1;continue}if(/^\s/.test(o))throw new Nr(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new Nr(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=LA(a),a===">"||a==="|"){let c=[];for(n+=1;n<r.length;){let l=r[n]??"";if(l.length===0||/^\s/.test(l))c.push(l.replace(/^\s{0,2}/,"")),n+=1;else break}e[i]=(a===">"?c.join(" "):c.join(`
|
|
4172
|
+
`)).trim();continue}e[i]=NA(a),n+=1}return e}function NA(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function LA(t){let e=!1,r=!1;for(let n=0;n<t.length;n+=1){let o=t[n];if(o==="'"&&!r)e=!e;else if(o==='"'&&!e)r=!r;else if(o==="#"&&!e&&!r)return t.slice(0,n).trim()}return t}var jA=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function iw(t){let e=[];t.length===0&&e.push("no skill files: expected <dir>/<slug>/SKILL.md"),t.length>50&&e.push(`${t.length} skill files; at most 50 per push`);let r=new Set;for(let n of t){let o=n.slug||"(unnamed)";jA.test(n.slug??"")||e.push(`${o}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),r.has(n.slug)&&e.push(`${o}: two files share this slug`),r.add(n.slug),n.name?.trim()?n.name.length>200&&e.push(`${o}: \`name\` is over 200 characters`):e.push(`${o}: frontmatter \`name\` is empty`),n.description?.trim()?n.description.length>1024&&e.push(`${o}: \`description\` is over 1024 characters`):e.push(`${o}: frontmatter \`description\` is empty \u2014 it is what an MCP client reads to choose the skill`),n.body?.trim()?Buffer.byteLength(n.body,"utf8")>65536&&e.push(`${o}: the body is over ${65536/1024} KB`):e.push(`${o}: the body after the frontmatter is empty`)}return e}er();async function qA(t){let e=UA(t),r;try{r=(await zA(e)).sort()}catch{k(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=aw(e,o,"SKILL.md");if(await MA(s).then(a=>a.isFile()).catch(()=>!1))try{let a=sw(await DA(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Nr&&k(`${aw(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var _a={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},FA={slug_taken:"a skill with this slug exists and was not written by this app \u2014 rename the directory",owned_by_another_app:"another app owns a skill with this slug \u2014 rename the directory"};function BA(t){let e=[];for(let r of t.items){let n=r.action==="refused"?g.red(_a.refused):r.action==="unchanged"?g.dim(_a.unchanged):r.action==="new"?g.green(_a.new):g.yellow(_a.update),o=r.targetPublished?` ${g.yellow("[currently live]")}`:"";e.push(`${n} ${g.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${g.red(FA[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${g.yellow("orphan")} ${g.bold(r)} \u2014 this app wrote it and no file names it now; left as it is (\`skills unpublish\` / \`skills delete\` to remove it)`);return e}async function cw(t,e=r=>new K(r)){t.app||k("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await qA(t.from),n=iw(r);n.length>0&&k(`nothing was sent:
|
|
4170
4173
|
${n.join(`
|
|
4171
|
-
`)}`);let o=await
|
|
4172
|
-
`));let c=a.items.filter(b=>b.action==="new"||b.action==="update").length,l=a.items.filter(b=>b.action==="refused").length;if(t.dryRun){q(g.dim("dry run \u2014 nothing was written.")),l>0&&(process.exitCode=1);return}let u=a;if(c>0){if(!t.yes){if(!it()){q(g.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await at(`Write ${c} skill(s)${t.publish?" and publish them":" as drafts"}?`,[{value:"yes",label:"Yes"},{value:"no",label:"No \u2014 write nothing"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}u=await i(!1)}let p=u.items.filter(b=>b.action==="new"||b.action==="update").map(b=>b.slug);if(_(`${p.length} written, ${u.items.filter(b=>b.action==="unchanged").length} unchanged, ${u.items.filter(b=>b.action==="refused").length} refused.`),t.publish&&p.length>0){let b;try{b=await
|
|
4173
|
-
`+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}_(tr(o.map(
|
|
4174
|
-
`))}async function
|
|
4174
|
+
`)}`);let o=await G(t.baseUrl),s=e(o),i=async b=>{try{return await ie(b?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,b))}catch(f){if(ee(f,"extensions:deploy","push skill files"),f instanceof se&&f.status===404){let m=f.body;k(m?.error==="app_not_found"?String(m.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}k(`push failed: ${f instanceof Error?f.message:String(f)}`)}},a=await i(!0);_(BA(a).join(`
|
|
4175
|
+
`));let c=a.items.filter(b=>b.action==="new"||b.action==="update").length,l=a.items.filter(b=>b.action==="refused").length;if(t.dryRun){q(g.dim("dry run \u2014 nothing was written.")),l>0&&(process.exitCode=1);return}let u=a;if(c>0){if(!t.yes){if(!it()){q(g.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await at(`Write ${c} skill(s)${t.publish?" and publish them":" as drafts"}?`,[{value:"yes",label:"Yes"},{value:"no",label:"No \u2014 write nothing"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}u=await i(!1)}let p=u.items.filter(b=>b.action==="new"||b.action==="update").map(b=>b.slug);if(_(`${p.length} written, ${u.items.filter(b=>b.action==="unchanged").length} unchanged, ${u.items.filter(b=>b.action==="refused").length} refused.`),t.publish&&p.length>0){let b;try{b=await ie("publishing",()=>s.skillsPublish(p))}catch(f){ee(f,"skills:publish","publish the pushed skills"),k(`the skills were written as drafts but publishing failed: ${f instanceof Error?f.message:String(f)}`)}_(g.green(`published ${b.published.join(", ")} \u2014 live as of release ${b.version.version_no}.`))}else t.publish?_(g.dim("nothing changed \u2014 nothing to publish.")):p.length>0&&q(g.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));u.items.some(b=>b.action==="refused")&&(q(g.red("one or more skill files were refused and not written.")),process.exitCode=1)}er();var ZA=["proposed","active","rejected"],VA=["mechanic","operator","learning","code-baseline"],va=t=>new K(t);async function ka(t,e){let r=await G(t.baseUrl);return e(r)}function lw(t,e,r){if(!t)return;let n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length!==0){for(let o of n)e.includes(o)||k(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function HA(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&k("--limit must be a positive number."),Math.floor(e)}function pw(t){let e=lw(t.status,ZA,"--status"),r=lw(t.provenance,VA,"--provenance"),n=HA(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function uw(t){return!!(t.provenance?.length||t.recordType||t.source)}var hw=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function KA(t){return t.status==="active"?g.green("active"):t.status==="rejected"?g.dim("rejected"):g.yellow("proposed")}function WA(t){return t.message?t.message:t.kind&&t.field?g.dim(`${t.kind} ${t.field}`):t.kind?g.dim(t.kind):g.dim("(no description)")}function mw(t){return[t.hookId,KA(t),t.provenance==="learning"?g.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),WA(t)]}async function fw(t={},e=va){let r=await ka(t,e),n=pw(t),o;try{o=await r.proposals(n)}catch(i){ee(i,"extensions:deploy","list hook proposals"),k(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return _(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return _(`no ${i} hook proposals.
|
|
4176
|
+
`+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}_(tr(o.map(mw),{head:hw})),_(g.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let s=o.filter(i=>i.provenance==="learning"&&i.status==="proposed");s.length>0&&_(g.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function GA(t,e,r){return r.yes?!0:it()?await at(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function JA(t){return!(t instanceof se)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Nu(t,e){JA(t)&&ee(t,"extensions:deploy",e)}function Lu(t,e){let r=e instanceof se?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);q(Le.error(`${g.bold(t)} \u2014 ${s}`))}async function dw(t,e){try{let r=await t.proposalPromote(e);return _(Le.success(`${g.bold(e)} ${g.dim(`${r.previousStatus} \u2192`)} ${g.green(r.status)}`)),!0}catch(r){return Nu(r,"promote a hook proposal"),Lu(e,r),!1}}async function gw(t,e={},r=va){!e.auto&&t.length===0&&k("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&k("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&k("promote: --apply / --all only mean something with --auto.");let n=await ka(e,r);if(!e.auto){let u=0;for(let p of t)await dw(n,p)&&(u+=1);u>0&&_(g.dim(` ${u} hook(s) armed \u2014 the loader compiles them on its next reload.`)),u<t.length&&(process.exitCode=1);return}let o=pw({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&k("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),o.status?.some(u=>u!=="proposed")&&k("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(u){ee(u,"extensions:deploy","list hook proposals"),k(`list hook proposals failed: ${u instanceof Error?u.message:String(u)}`)}let i=s.filter(u=>u.provenance==="learning"),a=s.filter(u=>u.provenance!=="learning");if(e.json&&(_(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(_(`nothing to promote${uw(o)?" for that filter":""}.`),i.length>0&&_(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(_(e.apply?`promoting ${g.bold(String(a.length))} hook proposal(s):`:`${g.bold("dry run")} \u2014 would promote ${g.bold(String(a.length))} hook proposal(s):`),_(tr(a.map(mw),{head:hw})),i.length>0&&_(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){_(""),_(Le.info("nothing was changed. Re-run with --apply to arm these."));return}if(!uw(o)&&!e.all&&k(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await GA(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let l=0;for(let u of a)await dw(n,u.hookId)&&(l+=1);_(g.dim(` ${l}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),l<a.length&&(process.exitCode=1)}async function yw(t,e={},r=va){t.length===0&&k("retract: name at least one proposal id.");let n=await ka(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);_(Le.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.yellow(i.status)}`)),o+=1}catch(i){Nu(i,"retract a hook proposal"),Lu(s,i)}o>0&&_(g.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function bw(t,e={},r=va){t.length===0&&k("reject: name at least one proposal id.");let n=await ka(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);_(Le.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.dim(i.status)}`)),o+=1}catch(i){Nu(i,"reject a hook proposal"),Lu(s,i)}o<t.length&&(process.exitCode=1)}er();var ju=t=>new K(t);async function YA(t,e){let r=await G(t.baseUrl);return e(r)}function XA(t){return!(t instanceof se)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function QA(t,e){let r=e instanceof se?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{not_found:"no extension with that id",wrong_kind:"that id is not an extension this instance manages",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);q(Le.error(`${g.bold(t)} \u2014 ${s}`))}async function zu(t,e,r,n,o,s,i){e.length===0&&k(`${t}: name at least one extension id.`);let a=await YA(r,n),c=[];for(let l of e)try{let u=await o(a,l);c.push(u),r.json||_(s(u))}catch(u){XA(u)&&ee(u,"extensions:deploy",`${t} an extension`),QA(l,u)}if(r.json)_(JSON.stringify(c,null,2));else{let l=i(c.length);l&&_(g.dim(l))}c.length<e.length&&(process.exitCode=1)}async function ww(t,e={},r=ju){await zu("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>Le.success(`${g.bold(n.id)} ${g.dim(`${n.previousStatus} \u2192`)} ${g.yellow(n.status)}`),n=>n>0?" definition kept \u2014 the loader drops it on its next reload. Put it back with `turbobase ext enable <id>`.":null)}async function _w(t,e={},r=ju){await zu("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>Le.success(`${g.bold(n.id)} ${g.dim(`${n.previousStatus} \u2192`)} ${g.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function vw(t,e={},r=ju){await zu("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>Le.success(`${g.bold(n.id)} ${g.dim(`${n.previousStatus} \u2192`)} ${g.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}er();var xo=t=>new K(t);async function So(t,e){let r=await G(t.baseUrl);return e(r)}async function xa(t,e,r,n){return n.yes?!0:it()?await at(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function eC(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function kw(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function tC(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${kw(g.bold(s.slug),e)} ${kw(eC(s),10)} ${s.surfaces.join(",")||g.dim("none")}`),s.description&&r.push(` ${g.dim(s.description)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function xw(t,e=xo){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await So(t,e),o;try{o=await ie("reading the skills",()=>n.skillsList(r))}catch(s){ee(s,"skills:publish","read the instance skills"),k(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}_(tC(o).join(`
|
|
4177
|
+
`))}async function Sw(t,e,r=xo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await So(e,r);if(!await xa(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await ie("publishing",()=>o.skillsPublish(n))}catch(a){ee(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function $w(t,e,r=xo){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let o=await So(e,r);if(!await xa(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await ie("unpublishing",()=>o.skillsUnpublish(n))}catch(a){ee(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Tw(t,e,r=xo){let n=Number(t);(!Number.isInteger(n)||n<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await So(e,r);if(await xa(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await ie("rolling back",()=>o.skillsRollback(n));_(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){ee(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Rw(t,e=xo){let r=await So(t,e),n;try{n=await ie("reading the releases",()=>r.skillsReleases())}catch(o){ee(o,"skills:publish","read the skills releases"),k(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){q("no releases yet.");return}for(let o of n.items){let s=o.is_current?g.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";_(`${s} v${o.version_no} ${o.skill_count} skill(s) ${g.dim(o.published_at)}${o.published_by?g.dim(` by ${o.published_by}`):""}${g.dim(i)}`)}}async function Ew(t,e,r=xo){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await So(e,r);if(!await xa(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
4175
4178
|
${n.join(`
|
|
4176
|
-
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let l of n)try{i.push(await
|
|
4177
|
-
`,{mode:384})}async function $C(t){let e=await Ku();e.push(t),await Lw(e)}async function zw(t){let e=await Ku(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Lw(e),n??null}async function Sa(){return Ku()}function Wu(t,e=Date.now()){let r=[],n=[];for(let o of t)hC(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function jw(t,e){Hu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new vs(r);let n=mC(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>vC(l)))(e.fromTenant),i=xC(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=fC(l.rows,n),p=bC(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:pC(e.ttl,o),sampleFraction:n,url:SC(s,e.baseUrl)};return await $C(c),c}async function Dw(t,e){Hu(t.target());let n=(await Sa()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await zw(e),n):null}async function Gu(t,e=Date.now()){Hu(t.target());let r=await Sa(),{expired:n}=Wu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await zw(s.name),o.push(s)}return o}var ks={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},F2=Object.keys(ks).filter(t=>ks[t].mintable);var V2=ks.pat.prefix,TC=Object.entries(ks).map(([t,e])=>[e.prefix,t]),RC=/^[A-Za-z0-9_-]{20,}$/;function EC(t){if(typeof t!="string")return null;for(let[e,r]of TC)if(t.startsWith(e)&&RC.test(t.slice(e.length)))return r;return null}function Mw(t){return EC(t)==="pat"}cs();var PC=8e3,AC={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function CC(t){return AC[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function IC(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(PC)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Uw(t){return t.state==="accepted"?nt()?g.green("accepted"):"accepted":t.state==="rejected"?nt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:nt()?g.yellow("unreachable"):"unreachable"}async function qw(t={},e=fetch){let r=await Cr(),{file:n}=Ji();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Qt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await IC(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(nt())_(tr(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Uw(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Uw(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${CC(i.check.reason)}.`)),q(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function aq(t){let e=await Cr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function cq(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function lq(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function uq(t,e,r){let n=await vy({baseUrl:t,token:e}),o=(await Cr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),lq(n.baseUrl),!r)return;let s=await cq(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function dq(t){let e=await pu(await ps(t),Ur(t)),r=Ru(e);return r||k(`${t}: ${Eu(e)}`),{...r,sourceCode:e}}async function to(t,e,r,n){try{return await _e.access(t),"skipped"}catch{}return await _e.mkdir(Ur(t),{recursive:!0}),await _e.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await _e.chmod(t,n),"wrote"}async function MT(t,e){if(qT(t)!==".gitignore")return to(t,e.content,e.executable,e.mode);let r=await _e.readFile(t,"utf8").catch(()=>null);if(r===null)return to(t,e.content,e.executable,e.mode);let n=Tb(r);return n===null?"skipped":(await _e.writeFile(t,n,"utf8"),"merged")}function dg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function bl(t){process.exit(t)}function pq(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function hq(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function mq(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function UT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function yg({includeInternal:t=!0}={}){let e=new zg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.39.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${wu()}
|
|
4178
|
-
`),e.hook("preAction",(d,
|
|
4179
|
-
${
|
|
4180
|
-
`).length} lines).`)}),
|
|
4179
|
+
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let l of n)try{i.push(await ie(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof se&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),ee(u,"skills:publish","delete a skill"),k(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&_(g.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Pw}from"node:fs";import{join as rC,relative as nC,resolve as oC,sep as sC}from"node:path";var iC=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),aC=new Set([".mcp.json",".env"]);function cC(t){return aC.has(t)||t.startsWith(".env.")&&t!==".env.example"}function lC(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function uC(t){return t.includes(0)}async function Aw(t){let e=oC(t),r={},n=[],o=[],s=[];async function i(a){let c=await Pw.readdir(a,{withFileTypes:!0});for(let l of c){let u=rC(a,l.name);if(iC.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=nC(e,u).split(sC).join("/");if(cC(l.name)){o.push(p);continue}let b=await Pw.readFile(u);if(!lC(b)){n.push(p);continue}uC(b)&&s.push(p),r[p]=b.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as dC}from"node:crypto";var pC="/_tb/app-assets",hC=16,mC=/^[0-9a-f]{32}$/;function Cw(){return dC(hC).toString("hex")}function fC(t){return mC.test(t)}function Iw(t){if(!fC(t))throw new Error(`not a build id: ${t}`);return`${pC}/${t}/`}var Ow=7;Mu();var Uu=50*1024*1024;import Sa from"node:fs/promises";import ks from"node:path";var qu={esbuild:"0.28.1","isolated-vm":"6.1.2"},Fu="@turbobase/isolated-vm-prebuilds";function Bu(t,e){return`${t}-${e}`}function Zu(t=process.versions){return`abi${t.modules}`}var Nw=["darwin-x64","win32-arm64"];async function Lw(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Bu(e,r),o=ks.join(t.home,"node_modules"),s=ks.join(o,...Fu.split("/"),"prebuilds",n),i=ks.join(o,"isolated-vm","prebuilds",n),a;try{a=await Sa.readdir(s)}catch{return[]}let c=[];await Sa.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=ks.join(i,l);try{await Sa.copyFile(ks.join(s,l),u,Sa.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as gC}from"node:os";import{join as jw}from"node:path";import{promises as Vu}from"node:fs";function Dw(){let t=process.env.TURBOBASE_HOME??jw(gC(),".turbobase");return{dir:t,file:jw(t,"sandboxes.json")}}var yC={s:1e3,m:6e4,h:36e5,d:864e5};function bC(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*yC[e[2]]}function wC(t,e=Date.now()){return new Date(e+bC(t)).toISOString()}function _C(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function vC(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function kC(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var xC="[REDACTED]",xs=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Hu=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function SC(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Hu(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:xC:n[o]=s}return n}function $C(t,e,r){return e.map(n=>SC(t,n,r))}var zw=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),TC=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function RC(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Ku(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of TC)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=RC(t);if(!zw.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...zw].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function EC(t,e=PC){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function PC(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function AC(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function CC(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Wu(){let{file:t}=Dw();try{let e=await Vu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Mw(t){let{dir:e,file:r}=Dw();await Vu.mkdir(e,{recursive:!0}),await Vu.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
4180
|
+
`,{mode:384})}async function IC(t){let e=await Wu();e.push(t),await Mw(e)}async function Uw(t){let e=await Wu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Mw(e),n??null}async function $a(){return Wu()}function Gu(t,e=Date.now()){let r=[],n=[];for(let o of t)_C(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function qw(t,e){Ku(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new xs(r);let n=vC(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>EC(l)))(e.fromTenant),i=AC(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=kC(l.rows,n),p=$C(l.table,u,l.classification);p.length>0&&await t.copyRows(i,l.table,p)}let c={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:wC(e.ttl,o),sampleFraction:n,url:CC(s,e.baseUrl)};return await IC(c),c}async function Fw(t,e){Ku(t.target());let n=(await $a()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Uw(e),n):null}async function Ju(t,e=Date.now()){Ku(t.target());let r=await $a(),{expired:n}=Gu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Uw(s.name),o.push(s)}return o}var Ss={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},J2=Object.keys(Ss).filter(t=>Ss[t].mintable);var Q2=Ss.pat.prefix,OC=Object.entries(Ss).map(([t,e])=>[e.prefix,t]),NC=/^[A-Za-z0-9_-]{20,}$/;function LC(t){if(typeof t!="string")return null;for(let[e,r]of OC)if(t.startsWith(e)&&NC.test(t.slice(e.length)))return r;return null}function Bw(t){return LC(t)==="pat"}us();var jC=8e3,zC={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function DC(t){return zC[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function MC(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(jC)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Zw(t){return t.state==="accepted"?nt()?g.green("accepted"):"accepted":t.state==="rejected"?nt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:nt()?g.yellow("unreachable"):"unreachable"}async function Vw(t={},e=fetch){let r=await Cr(),{file:n}=Yi();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Qt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await MC(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(nt())_(tr(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Zw(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Zw(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${DC(i.check.reason)}.`)),q(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function mq(t){let e=await Cr();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{k("cancelled.")}}async function fq(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function gq(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function yq(t,e,r){let n=await ky({baseUrl:t,token:e}),o=(await Cr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),gq(n.baseUrl),!r)return;let s=await fq(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function bq(t){let e=await hu(await ms(t),Ur(t)),r=Ru(e);return r||k(`${t}: ${Pu(e)}`),{...r,sourceCode:e}}async function to(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Ur(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function BT(t,e){if(VT(t)!==".gitignore")return to(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return to(t,e.content,e.executable,e.mode);let n=Pb(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function pg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function wl(t){process.exit(t)}function wq(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function _q(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function vq(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function ZT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function bg({includeInternal:t=!0}={}){let e=new zg;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.40.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${_u()}
|
|
4181
|
+
`),e.hook("preAction",(d,h)=>{Bb(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let h=Ut(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
4182
|
+
${wo} auth login --base-url ${h} --token tb_pat_\u2026`),Bw(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await yq(h,d.token,d.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async d=>Vw({probe:d.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let h=d??await mq("Pick the active instance:"),v=await Xi(h);if(!v){let T=await Cr();k(`no stored sign-in for ${Ut(h)}.`+(T.length?` Stored: ${T.map(x=>x.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Ut(h)} --token tb_pat_\u2026\`.`)}_(`active instance \u2192 ${v.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let T=await Cr();for(let x of T)await au(x.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await au(d.baseUrl);h||k(d.baseUrl?`no stored sign-in for ${Ut(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await Qt();_(`signed out of ${h}.`+(v?` Active instance \u2192 ${v.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T;try{T=await Nn({baseUrl:h,token:v,recordsOnly:d.recordsOnly})}catch(y){let S=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){q("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await Nn({baseUrl:h,token:v,recordsOnly:!0})}catch(E){k(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else k(`types generation failed: ${S}`)}let x=ge(process.cwd(),d.out);await be.writeFile(x,T,"utf8"),_(`wrote ${x} (${T.split(`
|
|
4183
|
+
`).length} lines).`)}),Hb(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let x=T.toString(),y=await fetch(`${h}/v1/catalog/grounding${x?`?${x}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});y.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let E=((await y.json()).markdown??"").trim(),O=ge(process.cwd(),d.out),j=d.records?` records=${d.records}`:"",M=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${j} \u2014 do not edit; re-run to refresh. -->
|
|
4181
4184
|
|
|
4182
|
-
`;await
|
|
4185
|
+
`;await be.writeFile(O,M+(E?`${E}
|
|
4183
4186
|
`:`(no grounding available yet)
|
|
4184
|
-
`),"utf8"),_(`wrote ${N}${P?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${bs.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>Hb(d)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>Wb(d)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,m)=>Gb(d,m)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,m)=>Jb(d,m)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Yb(d)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,m)=>Xb(d,m)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,m)=>Qb(d,m)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>(d.publish&&!d.from&&k("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),d.from?ow({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):ew(d))),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>ww(d)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,m)=>_w(d,m)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,m)=>vw(d,m)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>xw(d)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,m)=>kw(d,m)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,m)=>Sw(d,m));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async d=>{let m;try{m=yr("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let v=ye(process.cwd(),m.relativePath);await to(v,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let m;try{m=yr("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let v=ye(process.cwd(),m.relativePath);await to(v,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let m;try{m=yr("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let v=ye(process.cwd(),m.relativePath);await to(v,m.content)==="skipped"&&k(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(d,m)=>{let v=dg(m.reporter),$=await ps(ye(process.cwd(),d)),x=ye(process.cwd(),m.samples),y=await ds(x);y.length===0&&!v&&_(`no samples found under ${x} \u2014 add JSON fixtures to dry-run against.`);let T;try{T=await sa($,y.map(z=>z.fixture),{resolveDir:Ur(ye(process.cwd(),d))})}catch(z){k(`bundle failed: ${z instanceof Error?z.message:String(z)}`)}if(v){let z=pq(T);_(aa(z,v)),bl(z.cases.some(M=>M.status==="failed")?1:0)}let P=0;for(let z of T){let M=z.pass?g.green("PASS"):g.red("FAIL");z.pass||(P+=1);let re=z.error?` (error: ${z.error})`:z.observed!==z.expected?` (expected ${z.expected}, observed ${z.observed})`:z.rejection?` (rejected: ${z.rejection.code??"rejected"})`:"";_(` ${M} ${z.name}${re}`)}let N=`${T.length-P}/${T.length} sample(s) passed.`;_(`
|
|
4185
|
-
${P===0?g.green(N):g.yellow(N)}`),bl(P>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,m)=>{if(m.to){let T=await pg(),{baseUrl:P,token:N}=await Y(m.baseUrl),z=new K({baseUrl:P,token:N});try{let M=await se(`applying bundle to ${m.to}`,()=>z.configApply(T,{prune:m.prune}));_(`applied bundle to ${m.to}: +${M.applied.add} ~${M.applied.change} -${M.applied.destroy}`+(M.backfillsQueued.length?` (${M.backfillsQueued.length} backfill(s) queued)`:""));let re=M.skippedDestroys??[];if(re.length>0){q(`${re.length} resource(s) exist on ${m.to} but are not declared by this project \u2014 NOT removed:`);for(let U of re)q(` ${U.kind} ${U.id}`);q("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(M){M instanceof le&&M.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin."),k(`bundle apply failed: ${M instanceof Error?M.message:String(M)}`)}return}d||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:$}=await Y(m.baseUrl),x=await dq(ye(process.cwd(),d)),y=new K({baseUrl:v,token:$});try{let T=await se(`deploying ${qT(d)}`,()=>y.deploy(x));nt()?_(Wr("Deployed",[`${g.bold(T.id)} ${fo(T.status)} ${g.dim(T.outcome)}`])):_(`deployed ${T.id} \u2192 status=${T.status} (${T.outcome}).`)}catch(T){T instanceof le&&T.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),k(`deploy failed: ${T instanceof Error?T.message:String(T)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,m,v)=>{let $=!!(v.preview||v.replace||v.replaceLabel);v.replace&&v.replaceLabel&&k("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let x=ye(process.cwd(),m??".");await _e.mkdir(x,{recursive:!0});let y=v.proposal??await S(x),{baseUrl:T,token:P}=await Y(v.baseUrl),N=new K({baseUrl:T,token:P}),z=!1;try{z=(await N.appsList()).some(be=>be.slug===d||be.id===d)}catch(be){te(be,"extensions:deploy","deploy"),k(`could not reach ${T}: ${be instanceof Error?be.message:String(be)}`)}if(!z){v.create||k(`no app "${d}" on ${T} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let be=await se(`creating app ${d}`,()=>p(T,P,{slug:d},{tolerateExisting:!0}));be.existed||_(`created ${be.slug??d}.`)}let M;if(v.replace)if(typeof v.replace=="string")M=v.replace;else{let{previews:be}=await W(T,P,d);if(be.length===0&&k(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),be.length>1){for(let Xe of be)_(` ${Xe.previewId} v${Xe.version}${Xe.label?` ${Xe.label}`:""} ${Xe.url}`);k(`${d} has ${be.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${be[0].previewId}\`.`)}M=be[0].previewId}let re;if(v.replaceLabel){let be=v.replaceLabel,{previews:Xe}=await W(T,P,d),hr=Xe.filter(kl=>kl.label===be);hr.length>0?(M=hr[0].previewId,hr.length>1&&q(`${hr.length} open previews carry the label "${be}"; replacing the newest (${M}). Close the others with \`turbobase apps preview discard\`.`)):_(`no open preview labelled "${be}" \u2014 opening one.`),re=be}let U=be=>_e.stat(Ot(x,be)).then(()=>!0).catch(()=>!1),ne=d,Ee=x,ce=v.build!==!1;if(ce&&!await U("package.json"))if(await U("index.html"))_("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),ce=!1;else if(v.pull===!1)k(`${x} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let be=await se(`pulling ${d}`,()=>b(T,P,d));ne=be.slug??d,await f(x,be.files,!0),_(`pulled generated source (rev ${be.rev}).`)}let Ce;if(ce){let be=Rw();if(Ce={buildId:be,assetBase:Ew(be)},v.install!==!1&&!await U("node_modules")){_("installing dependencies\u2026");try{await A(["install"],x)}catch(Xe){k(`npm install failed: ${Xe instanceof Error?Xe.message:String(Xe)}`)}}_("building\u2026");try{await A(["run","build"],x,{TURBOBASE_ASSET_BASE:Ce.assetBase})}catch(Xe){k(`build failed: ${Xe instanceof Error?Xe.message:String(Xe)}`)}await U("dist")||k(`no dist/ after build in ${x} \u2014 check the app's build script.`),Ee=Ot(x,"dist")}$&&!Ce&&k(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${ne}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let Pe=await Ke(T,P,ne,Ee,v.entry,y,Ce,$?{label:v.label??re,replacePreviewId:M}:void 0);if($){let be=Pe.previewUrl??"(no url returned)",Xe=Pe.expiresAt?new Date(Pe.expiresAt).toLocaleDateString():`${Pw} days`,hr=Pe.replacedVersion==null?null:`replaced v${Pe.replacedVersion} \u2014 same URL`;if(nt())_(Wr(hr?"Preview replaced":"Preview deployed",[`${g.bold(ne)} ${g.green(`v${Pe.version??"?"}`)} ${g.dim("not live")}`,`${g.bold(be)}`,...hr?[g.dim(hr)]:[],g.dim(`expires ${Xe}`)]));else{let kl=hr?`; ${hr}`:"";_(`preview ${ne} v${Pe.version??"?"} \u2192 ${be} (expires ${Xe}; /a/${ne} unchanged${kl}).`)}jt(Pe),_(`next: turbobase apps promote ${ne} ${Pe.previewId??"<preview-id>"} # make it live`),_(` turbobase apps preview discard ${Pe.previewId??"<preview-id>"}`);return}nt()?_(Wr("Deployed",[`${g.bold(ne)} ${g.green(`v${Pe.version??"?"}`)} ${g.dim(Pe.url??`/a/${ne}`)}`])):_(`deployed ${ne} \u2192 v${Pe.version??"?"} (${Pe.url??`/a/${ne}`}).`),jt(Pe),qr(Pe),await dr(Pe,x)}),c.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(d,m)=>{let v=m.as?.startsWith("app:")?m.as.slice(4).trim():"";m.app!==void 0&&m.app.trim()===""&&k("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let $=m.app?.trim()??"";$&&v&&$!==v&&k(`--app ${$} and --as app:${v} name two different apps \u2014 pass one slug.`);let x=$||v||null,y=await gq(d??".");y||k(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`);let T=Array.isArray(y.manifest.tables)?y.manifest.tables:[],P=Array.isArray(y.manifest.writes)?y.manifest.writes:[],N=Array.isArray(y.manifest.roles)?y.manifest.roles:null,z=N??[],M=Array.isArray(y.manifest.labels)?y.manifest.labels:[],re=N!==null&&N.length===0;if(T.length===0&&P.length===0&&z.length===0&&M.length===0){if(!re)return _(`${y.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(x===null){for(let ce of ku({app:null,roles:N}))_(ce.text);return}}let{baseUrl:U,token:ne}=await Y(m.baseUrl),Ee=new K({baseUrl:U,token:ne});if(T.length>0){let ce;try{ce=await se("planning tables",()=>Ee.tablesPlan({claimedBy:m.as,tables:T}))}catch(Ce){te(Ce,"extensions:deploy","plan tables"),Pi(Ce)}_(`claiming as ${g.bold(ce.claimedBy)}`);for(let Ce of ce.tables)Ei(Ce,{showClaimants:!0})}if(P.length>0||z.length>0||M.length>0||re&&x!==null){let ce;try{ce=await se("checking declared writes, roles and labels",()=>Ee.appsPlan({writes:P,...N!==null?{roles:N}:{},labels:M,...x!==null?{app:x}:{}}))}catch(Ce){te(Ce,"extensions:deploy","plan writes"),k(`plan writes failed: ${Ce instanceof Error?Ce.message:String(Ce)}`)}ce.roles&&Je("plan",ce.roles.verdicts,ce.roles.retired);for(let Ce of ku({app:x,roles:N,retired:ce.roles?.retired??null}))_(Ce.text);if(ce.labels&&ce.labels.verdicts.length>0){_(""),_(g.bold("labels"));let Ce=Math.max(...ce.labels.verdicts.map(Pe=>Pe.name.length));for(let Pe of ce.labels.verdicts){let be=Pe.name.padEnd(Ce);if(Pe.action==="create")_(` create ${be} ${g.dim(Pe.color)}`);else{let Xe=Pe.declaredColor?`${Pe.color} \u2014 declared ${Pe.declaredColor}, the instance's colour is kept`:Pe.color;_(` ${g.dim("ok")} ${be} ${g.dim(Xe)}`)}}_(g.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}P.length>0&&_("");for(let Ce of ce.verdicts){let Pe=`${Ce.source} ${Ce.recordType}.${Ce.op}`;Ce.allowed?Ce.heldForApproval?_(`${g.dim("HELD")} ${Pe} \u2014 allowed, but each write waits for operator approval.`):_(`${g.dim("ok")} ${Pe}`):q(`${g.bold("DENIED")} ${Pe}${Ce.rule?` \u2014 guardrail "${Ce.rule}"`:""} (${Ce.reason})`)}ce.ok||(_(""),k(ce.message??(ce.roles&&!ce.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}_(""),_(g.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),c.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m,v)=>{let{baseUrl:$,token:x}=await Y(v.baseUrl),y=await se(`promoting ${m}`,()=>F($,x,d,"promote",{previewId:m}));nt()?_(Wr("Promoted",[`${g.bold(d)} ${g.green(`v${y.version??"?"}`)} ${g.dim(y.url??`/a/${d}`)}`])):_(`promoted ${d} \u2192 v${y.version??"?"} is now live at ${y.url??`/a/${d}`}.`);let T=vb(y);Je("applied",T.verdicts,T.retired),qr({labels:y.labels?{applied:!0,verdicts:y.labels}:null}),await dr(y)});let l=c.command("preview").description("Inspect and manage an app's open previews.");l.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,m)=>{let{baseUrl:v,token:$}=await Y(m.baseUrl),x=await W(v,$,d);if(m.json)return _(JSON.stringify(x.previews,null,2));if(x.previews.length===0){_(`no open previews for ${d}.`);return}for(let y of x.previews){let T=y.label?` ${y.label}`:"",P=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";_(`v${y.version} ${y.previewId}${T} ${y.url} (expires ${P})`)}}),l.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m,v)=>{let{baseUrl:$,token:x}=await Y(v.baseUrl);await se(`discarding ${m}`,()=>F($,x,d,"discard",{previewId:m})),_(`discarded ${m}.`)}),c.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{let{baseUrl:v,token:$}=await Y(m.baseUrl),x=await se(`creating ${d}`,()=>p(v,$,{slug:d,name:m.name,description:m.description})),y=x.slug??d;nt()?_(Wr("Created",[`${g.bold(y)} ${g.dim(x.url??`/a/${y}`)}`])):_(`created ${y} (${x.url??`/a/${y}`}).`),_(`next: turbobase apps push ${y} . # store the source`),_(` turbobase apps deploy ${y} # build + go live`)});let u=Xi(fetch);async function p(d,m,v,$={}){let x=`${d.replace(/\/+$/,"")}/v1/apps`,y;try{y=await u(x,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:v.slug,name:v.name??v.slug,description:v.description})})}catch(T){k(`create request failed: ${T instanceof Error?T.message:String(T)}`)}if(y.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),y.status===409){if($.tolerateExisting)return{slug:v.slug,existed:!0};k(`an app with slug "${v.slug}" already exists.`)}return y.ok||k(`create failed: HTTP ${y.status} ${(await y.text().catch(()=>"")).slice(0,200)}`),await y.json().catch(()=>({}))}async function b(d,m,v){let $=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,x;try{x=await u($,{headers:{Authorization:`Bearer ${m}`}})}catch(y){k(`pull request failed: ${y instanceof Error?y.message:String(y)}`)}return x.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),x.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),x.status===404&&k(`no generated source for "${v}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),x.ok||k(`pull failed: HTTP ${x.status} ${(await x.text().catch(()=>"")).slice(0,200)}`),await x.json()}async function f(d,m,v){let $=ye(d),x=0;for(let[y,T]of Object.entries(m)){let P=ye($,y);P!==$&&!P.startsWith($+fg)&&k(`refusing to write outside ${$}: ${y}`),v||await _e.stat(P).then(()=>!0).catch(()=>!1)&&k(`${P} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await _e.mkdir(Ur(P),{recursive:!0}),await _e.writeFile(P,T,"utf8"),x+=1}return x}function h(d){let m=d.indexOf(","),v=d.startsWith("data:")?m>=0?d.slice(m+1):"":d;if(!v)return null;try{let $=Buffer.from(v,"base64");return $.length>0?new Uint8Array($):null}catch{return null}}async function w(d,m,v){let $=ye(d),x=async(T,P)=>{let N=ye($,T);N!==$&&!N.startsWith($+fg)&&k(`refusing to write outside ${$}: ${T}`),v||await _e.stat(N).then(()=>!0).catch(()=>!1)&&k(`${N} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await _e.mkdir(Ur(N),{recursive:!0}),await _e.writeFile(N,P)},y=`# ${m.title||"App change request"}
|
|
4187
|
+
`),"utf8"),_(`wrote ${O}${E?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${_s.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>Jb(d)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>Xb(d)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Qb(d,h)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>ew(d,h)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>tw(d)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>rw(d,h)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>nw(d,h)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>(d.publish&&!d.from&&k("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),d.from?cw({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):ow(d))),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>xw(d)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Sw(d,h)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>$w(d,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Rw(d)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Tw(d,h)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Ew(d,h));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async d=>{let h;try{h=yr("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let v=ge(process.cwd(),h.relativePath);await to(v,h.content)==="skipped"&&k(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let h;try{h=yr("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let v=ge(process.cwd(),h.relativePath);await to(v,h.content)==="skipped"&&k(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let h;try{h=yr("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(x){k(x instanceof Error?x.message:String(x))}let v=ge(process.cwd(),h.relativePath);await to(v,h.content)==="skipped"&&k(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(d,h)=>{let v=pg(h.reporter),T=await ms(ge(process.cwd(),d)),x=ge(process.cwd(),h.samples),y=await hs(x);y.length===0&&!v&&_(`no samples found under ${x} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await ia(T,y.map(j=>j.fixture),{resolveDir:Ur(ge(process.cwd(),d))})}catch(j){k(`bundle failed: ${j instanceof Error?j.message:String(j)}`)}if(v){let j=wq(S);_(ca(j,v)),wl(j.cases.some(M=>M.status==="failed")?1:0)}let E=0;for(let j of S){let M=j.pass?g.green("PASS"):g.red("FAIL");j.pass||(E+=1);let re=j.error?` (error: ${j.error})`:j.observed!==j.expected?` (expected ${j.expected}, observed ${j.observed})`:j.rejection?` (rejected: ${j.rejection.code??"rejected"})`:"";_(` ${M} ${j.name}${re}`)}let O=`${S.length-E}/${S.length} sample(s) passed.`;_(`
|
|
4188
|
+
${E===0?g.green(O):g.yellow(O)}`),wl(E>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,h)=>{if(h.to){let S=await hg(),{baseUrl:E,token:O}=await G(h.baseUrl),j=new K({baseUrl:E,token:O});try{let M=await ie(`applying bundle to ${h.to}`,()=>j.configApply(S,{prune:h.prune}));_(`applied bundle to ${h.to}: +${M.applied.add} ~${M.applied.change} -${M.applied.destroy}`+(M.backfillsQueued.length?` (${M.backfillsQueued.length} backfill(s) queued)`:""));let re=M.skippedDestroys??[];if(re.length>0){q(`${re.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let U of re)q(` ${U.kind} ${U.id}`);q("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(M){M instanceof se&&M.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin.");let re=M instanceof se?Eu(M.body):null;re&&k(`bundle apply failed \u2014 ${re}`),k(`bundle apply failed: ${M instanceof Error?M.message:String(M)}`)}return}d||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:T}=await G(h.baseUrl),x=await bq(ge(process.cwd(),d)),y=new K({baseUrl:v,token:T});try{let S=await ie(`deploying ${VT(d)}`,()=>y.deploy(x)),E=zb(S.outcome);nt()?_(Wr("Deployed",[`${g.bold(S.id)} ${go(S.status)} ${g.dim(E)}`])):_(`deployed ${S.id} \u2192 status=${S.status} (${E}).`)}catch(S){S instanceof se&&S.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin.");let E=S instanceof se?Eu(S.body,d):null;E&&k(E),k(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,h,v)=>{let T=!!(v.preview||v.replace||v.replaceLabel);v.replace&&v.replaceLabel&&k("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let x=ge(process.cwd(),h??".");await be.mkdir(x,{recursive:!0});let y=v.proposal??await $(x),{baseUrl:S,token:E}=await G(v.baseUrl),O=new K({baseUrl:S,token:E}),j=!1;try{j=(await O.appsList()).some(we=>we.slug===d||we.id===d)}catch(we){ee(we,"extensions:deploy","deploy"),k(`could not reach ${S}: ${we instanceof Error?we.message:String(we)}`)}if(!j){v.create||k(`no app "${d}" on ${S} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let we=await ie(`creating app ${d}`,()=>p(S,E,{slug:d},{tolerateExisting:!0}));we.existed||_(`created ${we.slug??d}.`)}let M;if(v.replace)if(typeof v.replace=="string")M=v.replace;else{let{previews:we}=await W(S,E,d);if(we.length===0&&k(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),we.length>1){for(let Xe of we)_(` ${Xe.previewId} v${Xe.version}${Xe.label?` ${Xe.label}`:""} ${Xe.url}`);k(`${d} has ${we.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${we[0].previewId}\`.`)}M=we[0].previewId}let re;if(v.replaceLabel){let we=v.replaceLabel,{previews:Xe}=await W(S,E,d),hr=Xe.filter(xl=>xl.label===we);hr.length>0?(M=hr[0].previewId,hr.length>1&&q(`${hr.length} open previews carry the label "${we}"; replacing the newest (${M}). Close the others with \`turbobase apps preview discard\`.`)):_(`no open preview labelled "${we}" \u2014 opening one.`),re=we}let U=we=>be.stat(Ot(x,we)).then(()=>!0).catch(()=>!1),ne=d,Ee=x,le=v.build!==!1;if(le&&!await U("package.json"))if(await U("index.html"))_("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),le=!1;else if(v.pull===!1)k(`${x} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let we=await ie(`pulling ${d}`,()=>b(S,E,d));ne=we.slug??d,await f(x,we.files,!0),_(`pulled generated source (rev ${we.rev}).`)}let Ce;if(le){let we=Cw();if(Ce={buildId:we,assetBase:Iw(we)},v.install!==!1&&!await U("node_modules")){_("installing dependencies\u2026");try{await A(["install"],x)}catch(Xe){k(`npm install failed: ${Xe instanceof Error?Xe.message:String(Xe)}`)}}_("building\u2026");try{await A(["run","build"],x,{TURBOBASE_ASSET_BASE:Ce.assetBase})}catch(Xe){k(`build failed: ${Xe instanceof Error?Xe.message:String(Xe)}`)}await U("dist")||k(`no dist/ after build in ${x} \u2014 check the app's build script.`),Ee=Ot(x,"dist")}T&&!Ce&&k(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${ne}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let Pe=await Ke(S,E,ne,Ee,v.entry,y,Ce,T?{label:v.label??re,replacePreviewId:M}:void 0);if(T){let we=Pe.previewUrl??"(no url returned)",Xe=Pe.expiresAt?new Date(Pe.expiresAt).toLocaleDateString():`${Ow} days`,hr=Pe.replacedVersion==null?null:`replaced v${Pe.replacedVersion} \u2014 same URL`;if(nt())_(Wr(hr?"Preview replaced":"Preview deployed",[`${g.bold(ne)} ${g.green(`v${Pe.version??"?"}`)} ${g.dim("not live")}`,`${g.bold(we)}`,...hr?[g.dim(hr)]:[],g.dim(`expires ${Xe}`)]));else{let xl=hr?`; ${hr}`:"";_(`preview ${ne} v${Pe.version??"?"} \u2192 ${we} (expires ${Xe}; /a/${ne} unchanged${xl}).`)}zt(Pe),_(`next: turbobase apps promote ${ne} ${Pe.previewId??"<preview-id>"} # make it live`),_(` turbobase apps preview discard ${Pe.previewId??"<preview-id>"}`);return}nt()?_(Wr("Deployed",[`${g.bold(ne)} ${g.green(`v${Pe.version??"?"}`)} ${g.dim(Pe.url??`/a/${ne}`)}`])):_(`deployed ${ne} \u2192 v${Pe.version??"?"} (${Pe.url??`/a/${ne}`}).`),zt(Pe),qr(Pe),await dr(Pe,x)}),c.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(d,h)=>{let v=h.as?.startsWith("app:")?h.as.slice(4).trim():"";h.app!==void 0&&h.app.trim()===""&&k("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let T=h.app?.trim()??"";T&&v&&T!==v&&k(`--app ${T} and --as app:${v} name two different apps \u2014 pass one slug.`);let x=T||v||null,y=await xq(d??".");y||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`);let S=Array.isArray(y.manifest.tables)?y.manifest.tables:[],E=Array.isArray(y.manifest.writes)?y.manifest.writes:[],O=Array.isArray(y.manifest.roles)?y.manifest.roles:null,j=O??[],M=Array.isArray(y.manifest.labels)?y.manifest.labels:[],re=O!==null&&O.length===0;if(S.length===0&&E.length===0&&j.length===0&&M.length===0){if(!re)return _(`${y.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(x===null){for(let le of ku({app:null,roles:O}))_(le.text);return}}let{baseUrl:U,token:ne}=await G(h.baseUrl),Ee=new K({baseUrl:U,token:ne});if(S.length>0){let le;try{le=await ie("planning tables",()=>Ee.tablesPlan({claimedBy:h.as,tables:S}))}catch(Ce){ee(Ce,"extensions:deploy","plan tables"),Ci(Ce)}_(`claiming as ${g.bold(le.claimedBy)}`);for(let Ce of le.tables)Ai(Ce,{showClaimants:!0})}if(E.length>0||j.length>0||M.length>0||re&&x!==null){let le;try{le=await ie("checking declared writes, roles and labels",()=>Ee.appsPlan({writes:E,...O!==null?{roles:O}:{},labels:M,...x!==null?{app:x}:{}}))}catch(Ce){ee(Ce,"extensions:deploy","plan writes"),k(`plan writes failed: ${Ce instanceof Error?Ce.message:String(Ce)}`)}le.roles&&Je("plan",le.roles.verdicts,le.roles.retired);for(let Ce of ku({app:x,roles:O,retired:le.roles?.retired??null}))_(Ce.text);if(le.labels&&le.labels.verdicts.length>0){_(""),_(g.bold("labels"));let Ce=Math.max(...le.labels.verdicts.map(Pe=>Pe.name.length));for(let Pe of le.labels.verdicts){let we=Pe.name.padEnd(Ce);if(Pe.action==="create")_(` create ${we} ${g.dim(Pe.color)}`);else{let Xe=Pe.declaredColor?`${Pe.color} \u2014 declared ${Pe.declaredColor}, the instance's colour is kept`:Pe.color;_(` ${g.dim("ok")} ${we} ${g.dim(Xe)}`)}}_(g.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}E.length>0&&_("");for(let Ce of le.verdicts){let Pe=`${Ce.source} ${Ce.recordType}.${Ce.op}`;Ce.allowed?Ce.heldForApproval?_(`${g.dim("HELD")} ${Pe} \u2014 allowed, but each write waits for operator approval.`):_(`${g.dim("ok")} ${Pe}`):q(`${g.bold("DENIED")} ${Pe}${Ce.rule?` \u2014 guardrail "${Ce.rule}"`:""} (${Ce.reason})`)}le.ok||(_(""),k(le.message??(le.roles&&!le.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}_(""),_(g.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),c.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,v)=>{let{baseUrl:T,token:x}=await G(v.baseUrl),y=await ie(`promoting ${h}`,()=>F(T,x,d,"promote",{previewId:h}));nt()?_(Wr("Promoted",[`${g.bold(d)} ${g.green(`v${y.version??"?"}`)} ${g.dim(y.url??`/a/${d}`)}`])):_(`promoted ${d} \u2192 v${y.version??"?"} is now live at ${y.url??`/a/${d}`}.`);let S=Sb(y);Je("applied",S.verdicts,S.retired),qr({labels:y.labels?{applied:!0,verdicts:y.labels}:null}),await dr(y)});let l=c.command("preview").description("Inspect and manage an app's open previews.");l.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=await W(v,T,d);if(h.json)return _(JSON.stringify(x.previews,null,2));if(x.previews.length===0){_(`no open previews for ${d}.`);return}for(let y of x.previews){let S=y.label?` ${y.label}`:"",E=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";_(`v${y.version} ${y.previewId}${S} ${y.url} (expires ${E})`)}}),l.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,v)=>{let{baseUrl:T,token:x}=await G(v.baseUrl);await ie(`discarding ${h}`,()=>F(T,x,d,"discard",{previewId:h})),_(`discarded ${h}.`)}),c.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=await ie(`creating ${d}`,()=>p(v,T,{slug:d,name:h.name,description:h.description})),y=x.slug??d;nt()?_(Wr("Created",[`${g.bold(y)} ${g.dim(x.url??`/a/${y}`)}`])):_(`created ${y} (${x.url??`/a/${y}`}).`),_(`next: turbobase apps push ${y} . # store the source`),_(` turbobase apps deploy ${y} # build + go live`)});let u=Qi(fetch);async function p(d,h,v,T={}){let x=`${d.replace(/\/+$/,"")}/v1/apps`,y;try{y=await u(x,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:v.slug,name:v.name??v.slug,description:v.description})})}catch(S){k(`create request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),y.status===409){if(T.tolerateExisting)return{slug:v.slug,existed:!0};k(`an app with slug "${v.slug}" already exists.`)}return y.ok||k(`create failed: HTTP ${y.status} ${(await y.text().catch(()=>"")).slice(0,200)}`),await y.json().catch(()=>({}))}async function b(d,h,v){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,x;try{x=await u(T,{headers:{Authorization:`Bearer ${h}`}})}catch(y){k(`pull request failed: ${y instanceof Error?y.message:String(y)}`)}return x.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),x.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),x.status===404&&k(`no generated source for "${v}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),x.ok||k(`pull failed: HTTP ${x.status} ${(await x.text().catch(()=>"")).slice(0,200)}`),await x.json()}async function f(d,h,v){let T=ge(d),x=0;for(let[y,S]of Object.entries(h)){let E=ge(T,y);E!==T&&!E.startsWith(T+gg)&&k(`refusing to write outside ${T}: ${y}`),v||await be.stat(E).then(()=>!0).catch(()=>!1)&&k(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Ur(E),{recursive:!0}),await be.writeFile(E,S,"utf8"),x+=1}return x}function m(d){let h=d.indexOf(","),v=d.startsWith("data:")?h>=0?d.slice(h+1):"":d;if(!v)return null;try{let T=Buffer.from(v,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function w(d,h,v){let T=ge(d),x=async(S,E)=>{let O=ge(T,S);O!==T&&!O.startsWith(T+gg)&&k(`refusing to write outside ${T}: ${S}`),v||await be.stat(O).then(()=>!0).catch(()=>!1)&&k(`${O} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Ur(O),{recursive:!0}),await be.writeFile(O,E)},y=`# ${h.title||"App change request"}
|
|
4186
4189
|
|
|
4187
|
-
> Widget proposal \`${
|
|
4188
|
-
> \`turbobase apps deploy ${
|
|
4190
|
+
> Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
|
|
4191
|
+
> \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
|
|
4189
4192
|
|
|
4190
|
-
${
|
|
4193
|
+
${h.bodyMarkdown||"_No description provided._"}
|
|
4191
4194
|
|
|
4192
4195
|
## Screen context
|
|
4193
4196
|
|
|
4194
|
-
`+(
|
|
4195
|
-
`);if(await x("PROPOSAL.md",y),
|
|
4196
|
-
`)}async function S(d){try{let m=await _e.readFile(Ot(d,".turbobase","proposal.json"),"utf8"),v=JSON.parse(m);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function R(d,m,v,$,x,y){let T=new K({baseUrl:d,token:m});try{return await T.appsPush(v,$,{note:x,proposalId:y})}catch(P){if(P instanceof le){let N=P.body;if(P.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),P.status===403&&N?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),P.status===403&&te(P,"extensions:deploy","push app source"),P.status===404&&k(`no app "${v}" on this instance \u2014 create it with \`turbobase apps create ${v}\`.`),P.status===413&&(N?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${N?.error??"too large"} (limit ${N?.limit??"?"}).`)),P.status===400){let z=N?.path?` in ${N.path}`:"",M=N?.reason?` (${N.reason})`:"";k(`push rejected: ${N?.error??"bad request"}${M}${z}.`)}}k(`push failed: ${P instanceof Error?P.message:String(P)}`)}}function A(d,m,v){return new Promise(($,x)=>{let y=gg("npm",d,{cwd:m,stdio:"inherit",...v?{env:{...process.env,...v}}:{}});y.on("error",x),y.on("exit",T=>T===0?$():x(new Error(`npm ${d.join(" ")} exited ${T??"?"}`)))})}async function L(d,m,v,$){let x=`${d.replace(/\/+$/,"")}${v}`,y;try{y=await u(x,{method:$.method,headers:{Authorization:`Bearer ${m}`,...$.body?{"content-type":"application/json"}:{}},...$.body?{body:JSON.stringify($.body)}:{}})}catch(T){k(`request failed: ${T instanceof Error?T.message:String(T)}`)}if(y.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!y.ok){let T=await y.text().catch(()=>""),P=T.slice(0,300);try{let N=JSON.parse(T);P=N.message??N.error??P}catch{}k(`failed: HTTP ${y.status} ${P}`)}return await y.json().catch(()=>({}))}async function F(d,m,v,$,x){return await L(d,m,`/v1/apps/${encodeURIComponent(v)}/preview/${$}`,{method:"POST",body:x})}async function W(d,m,v){return{previews:(await L(d,m,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Ke(d,m,v,$,x,y,T,P){let N;try{N=await se(`zipping ${$}`,()=>Gy($))}catch(U){k(`could not zip ${$}: ${U instanceof Error?U.message:String(U)}`)}N.fileCount===0&&k(`${$} is empty \u2014 the build produced nothing.`),N.buffer.byteLength>Mu&&k(`${$} zips to ${UT(N.buffer.byteLength)} \u2014 over the ${UT(Mu)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let z={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};x&&(z["x-app-entry"]=x),y&&(z["x-proposal-id"]=y),T&&(z["x-app-build-id"]=T.buildId,z["x-app-asset-base"]=T.assetBase),P&&(z["x-app-channel"]="preview",P.label&&(z["x-app-preview-label"]=encodeURIComponent(P.label)),P.replacePreviewId&&(z["x-app-preview-replace"]=P.replacePreviewId));let M=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,re;try{re=await se(`deploying ${v} (${N.fileCount} file${N.fileCount===1?"":"s"})`,()=>u(M,{method:"POST",headers:z,body:new Uint8Array(N.buffer)}))}catch(U){k(`deploy request failed: ${U instanceof Error?U.message:String(U)}`)}if(re.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),re.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),re.status===404){let U=await re.text().catch(()=>""),ne={};try{ne=JSON.parse(U)}catch{}ne.error==="no_preview"&&k(`${ne.message??`no open preview to replace on ${v}`} \u2014 list them with \`turbobase apps preview list ${v}\`.`),k(`no app "${v}" on ${d} \u2014 create it with \`turbobase apps create ${v}\`.`)}if(!re.ok){let U=await re.text().catch(()=>""),ne=U.slice(0,300);try{let Ee=JSON.parse(U);ne=Ee.message??Ee.error??ne}catch{}k(`deploy failed: HTTP ${re.status} ${ne}`)}return await re.json().catch(()=>({}))}function Je(d,m,v){for(let $ of _b({mode:d,verdicts:m,retired:v}))($.stream==="err"?q:_)($.text)}function jt(d){let m=d.roles;m&&Je(m.applied?"applied":"preview",m.verdicts??[],m.retired)}function qr(d){let m=d.labels;if(!m||m.verdicts.length===0)return;let v=m.verdicts.filter(x=>x.action!=="noop");if(v.length===0)return;_(""),_(g.bold(m.applied?"labels":"labels (preview \u2014 not applied)"));let $=Math.max(...v.map(x=>x.name.length));for(let x of v){let y=x.name.padEnd($);if(x.action==="detach")_(` removed ${y} ${g.dim("no longer declared in the manifest")}`);else if(x.action==="create")_(` created ${y} ${g.dim(x.color)}`);else{let T=x.declaredColor?`${x.color} \u2014 declared ${x.declaredColor}, the instance's colour is kept`:x.color;_(` added ${y} ${g.dim(T)}`)}}_(g.dim(m.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function dr(d,m){let v=hb(d,{localDocsModifiedAt:await mn(m)});v&&_(v.level==="warn"?g.yellow(v.message):g.dim(v.message))}async function mn(d){if(!d)return null;let m=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let $=await _e.stat(Ot(d,v));(m===null||$.mtimeMs>m)&&(m=$.mtimeMs)}catch{}return m===null?null:new Date(m)}c.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(d,m,v)=>{let{baseUrl:$,token:x}=await Y(v.baseUrl);if(v.proposal){let N=new K({baseUrl:$,token:x}),z;try{z=await se(`fetching proposal ${v.proposal}`,()=>N.appPullContext(v.proposal))}catch(Ee){te(Ee,"extensions:deploy","pull proposal"),Ee instanceof le&&Ee.status===404&&k(`no widget proposal "${v.proposal}" on ${$}.`),k(`could not fetch proposal ${v.proposal}: ${Ee instanceof Error?Ee.message:String(Ee)}`)}let M=await se(`pulling ${z.appSlug}`,()=>b($,x,z.appSlug)),re=m??d,U=ye(process.cwd(),re??z.appSlug);await _e.mkdir(U,{recursive:!0});let ne=await f(U,M.files,!!v.force);await w(U,z,!!v.force),_(`pulled ${ne} file${ne===1?"":"s"} \u2192 ${U} (rev ${M.rev}), linked to proposal ${z.proposalId}.`),_(`next: cd ${wl(process.cwd(),U)||"."} && turbobase apps deploy ${z.appSlug}`);return}d||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await se(`pulling ${d}`,()=>b($,x,d)),T=ye(process.cwd(),m??y.slug??d);await _e.mkdir(T,{recursive:!0});let P=await f(T,y.files,!!v.force);_(`pulled ${P} file${P===1?"":"s"} \u2192 ${T} (rev ${y.rev}).`),_(`next: cd ${wl(process.cwd(),T)||"."} && turbobase apps deploy ${y.slug}`)}),c.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(d,m,v)=>{let $=ye(process.cwd(),m??d),x=await Qt(v.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:T}=await Promise.resolve().then(()=>(c_(),a_)),P=v.title??d,N=y({slug:d,title:P,appTsx:T(P),instanceOrigin:x?.baseUrl});await _e.mkdir($,{recursive:!0});let z=await f($,N,!!v.force);if(_(`scaffolded ${z} file${z===1?"":"s"} \u2192 ${$}`),v.claude!==!1){let re=Su({baseUrl:x?.baseUrl,token:x?.token,appSlug:d}),U=0;for(let ne of re){let Ee=await MT(Ot($,ne.path),ne);(Ee==="wrote"||Ee==="merged")&&(U+=1)}_(`wired Claude Code: ${U} file${U===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),x||q("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let M=wl(process.cwd(),$)||".";_(`next: cd ${M} && npm install && npm run dev`),_(` turbobase apps create ${d}`),_(` turbobase apps push ${d} .`),_(` turbobase apps deploy ${d} .`)}),c.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:m,token:v}=await Y(d.baseUrl),$=new K({baseUrl:m,token:v}),x;try{x=await $.appsList()}catch(y){te(y,"extensions:deploy","list apps"),k(`list apps failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(x,null,2));if(x.length===0)return _("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");_(tr(x.map(y=>[y.slug,y.name,y.deployed?"yes":"no",y.sourceRev===null?"\u2014":`rev ${y.sourceRev}`,y.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),c.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(d,m,v)=>{let $=ye(process.cwd(),m??".");await _e.stat($).then(ce=>ce.isDirectory()).catch(()=>!1)||k(`${$} is not a directory.`);let{baseUrl:y,token:T}=await Y(v.baseUrl),P=v.proposal??await S($),{files:N,skipped:z,secrets:M,unstorable:re}=await Tw($),U=Object.keys(N).length;if(U===0&&k(`no source files found under ${$} (build output and node_modules are skipped).`),re.length>0){for(let ce of re)q(`${ce} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${re.length} ${re.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let ce of z)q(g.dim(`skipped binary file ${ce}`));for(let ce of M)q(g.dim(`skipped ${ce} (holds credentials \u2014 never pushed)`));let ne=await se(`pushing ${U} file${U===1?"":"s"}`,()=>R(y,T,d,N,v.note,P));_(`pushed ${ne.files} file${ne.files===1?"":"s"} \u2192 ${ne.slug} rev ${ne.rev} (source only, nothing deployed).`);let Ee=await ws(new K({baseUrl:y,token:T}),ne.slug);Ee&&Ee.entriesAdded>0&&_(`${Ee.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),_(`next: turbobase apps deploy ${ne.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let m=await pg(),{baseUrl:v,token:$}=await Y(d.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await se(`planning against ${d.to??v}`,()=>x.configPlan(m))}catch(T){k(`plan failed: ${T instanceof Error?T.message:String(T)}`)}bq(y,d.to??v)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let m=await pg(),{baseUrl:v,token:$}=await Y(d.baseUrl),x=m.tenant??wq(v),y=Cb(d.confirm,x);y.ok||k(`promote refused (fail-closed): ${y.reason}`);let T=new K({baseUrl:v,token:$});try{let P=await se(`promoting ${d.from} \u2192 ${d.to} (${x})`,()=>T.configApply(m,{prune:d.prune}));if(nt()){let z=[`${g.bold(`${d.from} \u2192 ${d.to}`)} ${g.dim(x??"")}`,`${Kr.add(String(P.applied.add))} ${Kr.change(String(P.applied.change))} ${Kr.destroy(String(P.applied.destroy))}`];P.backfillsQueued.length&&z.push(g.dim(`${P.backfillsQueued.length} backfill(s) queued`)),_(Wr("Promoted",z))}else _(`promoted ${d.from} \u2192 ${d.to} (${x}): +${P.applied.add} ~${P.applied.change} -${P.applied.destroy}`+(P.backfillsQueued.length?` (${P.backfillsQueued.length} backfill(s) queued)`:""));let N=P.skippedDestroys??[];if(N.length>0){q(`${N.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let z of N)q(` ${z.kind} ${z.id}`);q("Re-run with --prune to remove them, or add them to this repo.")}}catch(P){P instanceof le&&P.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${P instanceof Error?P.message:String(P)}`)}}),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(d,m)=>{let v=dg(m.reporter),$=ye(process.cwd(),d),x=await ps($),y=Yy(x);v?_(aa(hq(d,y),v)):_(Xy(d,y,{warn:g.yellow,ok:g.green,dim:g.dim})),m.ci&&y.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(d,m)=>{let v=dg(m.reporter),$=await By(ye(process.cwd(),d));if(m.against){m.against!=="sandbox"&&k(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await qy(fu($))}catch(T){k(T instanceof Error?T.message:String(T))}return}m.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let x;try{x=await Fy(ye(process.cwd(),m.fixture))}catch(T){k(`could not read fixture ${m.fixture}: ${T instanceof Error?T.message:String(T)}`)}let y=await Uy($,x,m.fixture,{resolveDir:Ur(ye(process.cwd(),d))});if(v){let T=mq(y);_(aa(T,v)),bl(T.cases.some(P=>P.status==="failed")?1:0)}_(Zy(y,!!m.trace)),bl(y.error?1:0)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async d=>{let{baseUrl:m,token:v}=await Y(d.baseUrl),$=new K({baseUrl:m,token:v});try{await sb($,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:_})}catch(x){x instanceof le&&x.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),x instanceof le&&x.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${x instanceof Error?x.message:String(x)}`)}});let fn=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");fn.command("list").description("List hook proposals and the evidence behind each (defaults to the pending queue).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <list>","proposed | active | rejected (comma-joined). Default: proposed.").option("--provenance <list>","mechanic | operator | learning | code-baseline (comma-joined).").option("--record-type <type>","Only proposals for this record type.").option("--source <system>","Only proposals for this adapter id.").option("--limit <n>","Max rows listed (default 200).").option("--json","Emit raw JSON instead of a table.").action(async d=>{await dw(d)}),fn.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,m)=>{await pw(d??[],m)}),fn.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{await hw(d,m)}),fn.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,m)=>{await mw(d,m)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,m)=>{await fw(d,m)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,m)=>{await gw(d,m)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,m)=>{await yw(d,m)}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(d,m)=>{let v=d.lastIndexOf("@"),$=v>0?d.slice(0,v):d,x=v>0?d.slice(v+1):void 0,y=uu();y||k(`marketplace not configured \u2014 set ${po} and ${Qi}.
|
|
4197
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
4198
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
4199
|
-
project init: ${
|
|
4200
|
-
project ci: ${
|
|
4201
|
-
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),_("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),_("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async d=>{let{baseUrl:
|
|
4202
|
-
`;d.force?(await
|
|
4203
|
-
samples init: ${
|
|
4204
|
-
`+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(tr(x.map(_l),{head:FT})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),pr.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await x.guardrailCreate({name:d,source:m.source,record:m.record,decision:m.decision,...m.op?{op:m.op}:{},...m.target?{target:m.target}:{},...m.actor?{actor:m.actor}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when?{when:m.when}:{},...m.reason?{reason:m.reason}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(T){te(T,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${T instanceof Error?T.message:String(T)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),_(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),pr.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{m.decision===void 0&&m.priority===void 0&&m.when===void 0&&m.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await x.guardrailUpdate(d,{...m.decision!==void 0?{decision:m.decision}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when!==void 0?{when:m.when}:{},...m.reason!==void 0?{reason:m.reason}:{}})}catch(T){te(T,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${T instanceof Error?T.message:String(T)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,m,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])pr.command(`${d} <name>`).description(m==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async($,x)=>{let{baseUrl:y,token:T}=await Y(x.baseUrl),P=new K({baseUrl:y,token:T});try{await P.guardrailUpdate($,{status:m})}catch(N){te(N,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${N instanceof Error?N.message:String(N)}`)}_(`${g.green("\u2713")} guardrail ${g.bold($)} ${v}`),m==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});pr.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$});try{await x.guardrailDelete(d)}catch(y){te(y,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),pr.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$}),y=N=>N==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let N;try{N=await x.guardrailPostureGet()}catch(z){te(z,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${z instanceof Error?z.message:String(z)}`)}_(`guardrail posture: ${g.bold(y(N.mode))}`),_(g.dim(N.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let T=d.trim().toLowerCase();T!=="allow"&&T!=="deny"&&k("posture must be 'allow' or 'deny'.");let P;try{P=await x.guardrailPostureSet(T)}catch(N){te(N,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${N instanceof Error?N.message:String(N)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(P.mode))}`),P.mode==="deny"&&_(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),pr.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let m;if(d.fields)try{m=JSON.parse(d.fields)}catch(P){k(`--fields must be valid JSON: ${P instanceof Error?P.message:String(P)}`)}let{baseUrl:v,token:$}=await Y(d.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await x.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...m?{fields:m}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(P){te(P,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${P instanceof Error?P.message:String(P)}`)}if(d.json)return _(JSON.stringify(y,null,2));let T=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${g.red("\u2717")} ${T} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(g.dim(` ${y.reason}`))):y.allowed?_(`${g.green("\u2713")} ${T} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(_(`${g.red("\u2717")} ${T} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&_(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&_(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let Xo=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Ei=(d,m={})=>{let v=`${g.bold(d.table)} ${g.dim(d.displayName)}`;_(d.exists===!1?`${v} ${g.dim("(new)")}`:v);for(let $ of d.fields){let x=[$.required?"required":null].filter(Boolean).join(", "),y=m.showClaimants&&$.claimedBy?.length?` ${g.dim(`\u2190 ${$.claimedBy.join(", ")}`)}`:"";_(` ${$.column.padEnd(28)} ${$.type}${x?` (${x})`:""}${y}`)}m.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Pi(d){if(d instanceof le&&d.status===409){let m=d.body;m?.error==="table_conflict"&&m.message&&(q(m.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let bg=async d=>{let m=Ot(ye(process.cwd(),d),"public","turbobase.json"),v=await _e.readFile(m,"utf8").catch(()=>null);if(v===null)return null;let $;try{$=JSON.parse(v)}catch(y){k(`${m} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let x=$.tables;return x===void 0?{tables:[],manifestPath:m}:(Array.isArray(x)||k(`${m}: "tables" must be an array.`),{tables:x,manifestPath:m})};Xo.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:m,token:v}=await Y(d.baseUrl),$=new K({baseUrl:m,token:v}),x;try{x=await $.tablesList()}catch(y){te(y,"extensions:deploy","list tables"),k(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(x,null,2));if(x.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(tr(x.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Xo.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,m)=>{let v=await bg(d??".");if(v||k(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:$,token:x}=await Y(m.baseUrl),y=new K({baseUrl:$,token:x}),T;try{T=await se("planning tables",()=>y.tablesPlan({claimedBy:m.as,tables:v.tables}))}catch(P){te(P,"extensions:deploy","plan tables"),Pi(P)}_(`claiming as ${g.bold(T.claimedBy)}`);for(let P of T.tables)Ei(P,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Xo.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,m)=>{let v=await bg(d??".");if(v||k(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:$,token:x}=await Y(m.baseUrl),y=new K({baseUrl:$,token:x}),T;try{T=await se("applying tables",()=>y.tablesApply({claimedBy:m.as,tables:v.tables}))}catch(P){te(P,"extensions:deploy","apply tables"),Pi(P)}for(let P of T.tables)Ei(P,{showClaimants:!0});_(`applied ${T.tables.length} table${T.tables.length===1?"":"s"} as ${T.claimedBy}.`)}),Xo.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,m)=>[...m??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{let v=m.field.map(P=>{let[N,z,M]=P.split(":");return(!N||!z)&&k(`--field "${P}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&k(`--field "${P}": the third part may only be "required".`),{name:N,type:z,...M==="required"?{required:!0}:{}}}),{baseUrl:$,token:x}=await Y(m.baseUrl),y=new K({baseUrl:$,token:x}),T;try{T=await se(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:m.name??d,fields:v,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(P){te(P,"extensions:deploy","create a table"),Pi(P)}for(let P of T.tables)Ei(P);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Xo.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,m)=>{m.confirm!==d&&k(`drop refused: --confirm "${m.confirm}" does not match "${d}".`);let{baseUrl:v,token:$}=await Y(m.baseUrl),x=new K({baseUrl:v,token:$}),y;try{y=await se(`dropping cr_${d}`,()=>x.tablesDrop(d,m.confirm))}catch(T){te(T,"extensions:deploy","drop a table"),k(`drop failed: ${T instanceof Error?T.message:String(T)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let vl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");vl.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let m=hg(),v;try{v=await jw(m,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch($){$ instanceof vs&&k($.message),k(`sandbox create failed: ${$ instanceof Error?$.message:String($)}`)}_(`sandbox ${v.name} ready.`),_(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),_(` url: ${v.url}`),_(` expires: ${v.expiresAt}`)}),vl.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let m=hg();await Gu(m).catch(()=>[]);let v;try{v=await Dw(m,d)}catch($){k(`sandbox destroy failed: ${$ instanceof Error?$.message:String($)}`)}v||k(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),vl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=hg(),m=await Gu(d).catch(()=>[]),v=await Sa(),{active:$}=Wu(v);if($.length===0)_("no active sandboxes.");else{for(let x of $)_(` ${x.name} from=${x.fromTenant} expires=${x.expiresAt} ${x.url}`);_(`
|
|
4205
|
-
${
|
|
4206
|
-
`,
|
|
4207
|
-
`).length} lines).`)});let
|
|
4208
|
-
run \`${
|
|
4197
|
+
`+(h.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
|
|
4198
|
+
`);if(await x("PROPOSAL.md",y),h.screenshot){let S=m(h.screenshot);S&&await x("proposal-screenshot.png",S)}await x(Ot(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
|
|
4199
|
+
`)}async function $(d){try{let h=await be.readFile(Ot(d,".turbobase","proposal.json"),"utf8"),v=JSON.parse(h);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function R(d,h,v,T,x,y){let S=new K({baseUrl:d,token:h});try{return await S.appsPush(v,T,{note:x,proposalId:y})}catch(E){if(E instanceof se){let O=E.body;if(E.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&O?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&ee(E,"extensions:deploy","push app source"),E.status===404&&k(`no app "${v}" on this instance \u2014 create it with \`turbobase apps create ${v}\`.`),E.status===413&&(O?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${O?.error??"too large"} (limit ${O?.limit??"?"}).`)),E.status===400){let j=O?.path?` in ${O.path}`:"",M=O?.reason?` (${O.reason})`:"";k(`push rejected: ${O?.error??"bad request"}${M}${j}.`)}}k(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function A(d,h,v){return new Promise((T,x)=>{let y=yg("npm",d,{cwd:h,stdio:"inherit",...v?{env:{...process.env,...v}}:{}});y.on("error",x),y.on("exit",S=>S===0?T():x(new Error(`npm ${d.join(" ")} exited ${S??"?"}`)))})}async function L(d,h,v,T){let x=`${d.replace(/\/+$/,"")}${v}`,y;try{y=await u(x,{method:T.method,headers:{Authorization:`Bearer ${h}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch(S){k(`request failed: ${S instanceof Error?S.message:String(S)}`)}if(y.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!y.ok){let S=await y.text().catch(()=>""),E=S.slice(0,300);try{let O=JSON.parse(S);E=O.message??O.error??E}catch{}k(`failed: HTTP ${y.status} ${E}`)}return await y.json().catch(()=>({}))}async function F(d,h,v,T,x){return await L(d,h,`/v1/apps/${encodeURIComponent(v)}/preview/${T}`,{method:"POST",body:x})}async function W(d,h,v){return{previews:(await L(d,h,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Ke(d,h,v,T,x,y,S,E){let O;try{O=await ie(`zipping ${T}`,()=>Jy(T))}catch(U){k(`could not zip ${T}: ${U instanceof Error?U.message:String(U)}`)}O.fileCount===0&&k(`${T} is empty \u2014 the build produced nothing.`),O.buffer.byteLength>Uu&&k(`${T} zips to ${ZT(O.buffer.byteLength)} \u2014 over the ${ZT(Uu)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let j={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};x&&(j["x-app-entry"]=x),y&&(j["x-proposal-id"]=y),S&&(j["x-app-build-id"]=S.buildId,j["x-app-asset-base"]=S.assetBase),E&&(j["x-app-channel"]="preview",E.label&&(j["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(j["x-app-preview-replace"]=E.replacePreviewId));let M=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,re;try{re=await ie(`deploying ${v} (${O.fileCount} file${O.fileCount===1?"":"s"})`,()=>u(M,{method:"POST",headers:j,body:new Uint8Array(O.buffer)}))}catch(U){k(`deploy request failed: ${U instanceof Error?U.message:String(U)}`)}if(re.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),re.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),re.status===404){let U=await re.text().catch(()=>""),ne={};try{ne=JSON.parse(U)}catch{}ne.error==="no_preview"&&k(`${ne.message??`no open preview to replace on ${v}`} \u2014 list them with \`turbobase apps preview list ${v}\`.`),k(`no app "${v}" on ${d} \u2014 create it with \`turbobase apps create ${v}\`.`)}if(!re.ok){let U=await re.text().catch(()=>""),ne=U.slice(0,300);try{let Ee=JSON.parse(U);ne=Ee.message??Ee.error??ne}catch{}k(`deploy failed: HTTP ${re.status} ${ne}`)}return await re.json().catch(()=>({}))}function Je(d,h,v){for(let T of xb({mode:d,verdicts:h,retired:v}))(T.stream==="err"?q:_)(T.text)}function zt(d){let h=d.roles;h&&Je(h.applied?"applied":"preview",h.verdicts??[],h.retired)}function qr(d){let h=d.labels;if(!h||h.verdicts.length===0)return;let v=h.verdicts.filter(x=>x.action!=="noop");if(v.length===0)return;_(""),_(g.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let T=Math.max(...v.map(x=>x.name.length));for(let x of v){let y=x.name.padEnd(T);if(x.action==="detach")_(` removed ${y} ${g.dim("no longer declared in the manifest")}`);else if(x.action==="create")_(` created ${y} ${g.dim(x.color)}`);else{let S=x.declaredColor?`${x.color} \u2014 declared ${x.declaredColor}, the instance's colour is kept`:x.color;_(` added ${y} ${g.dim(S)}`)}}_(g.dim(h.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function dr(d,h){let v=gb(d,{localDocsModifiedAt:await mn(h)});v&&_(v.level==="warn"?g.yellow(v.message):g.dim(v.message))}async function mn(d){if(!d)return null;let h=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await be.stat(Ot(d,v));(h===null||T.mtimeMs>h)&&(h=T.mtimeMs)}catch{}return h===null?null:new Date(h)}c.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(d,h,v)=>{let{baseUrl:T,token:x}=await G(v.baseUrl);if(v.proposal){let O=new K({baseUrl:T,token:x}),j;try{j=await ie(`fetching proposal ${v.proposal}`,()=>O.appPullContext(v.proposal))}catch(Ee){ee(Ee,"extensions:deploy","pull proposal"),Ee instanceof se&&Ee.status===404&&k(`no widget proposal "${v.proposal}" on ${T}.`),k(`could not fetch proposal ${v.proposal}: ${Ee instanceof Error?Ee.message:String(Ee)}`)}let M=await ie(`pulling ${j.appSlug}`,()=>b(T,x,j.appSlug)),re=h??d,U=ge(process.cwd(),re??j.appSlug);await be.mkdir(U,{recursive:!0});let ne=await f(U,M.files,!!v.force);await w(U,j,!!v.force),_(`pulled ${ne} file${ne===1?"":"s"} \u2192 ${U} (rev ${M.rev}), linked to proposal ${j.proposalId}.`),_(`next: cd ${_l(process.cwd(),U)||"."} && turbobase apps deploy ${j.appSlug}`);return}d||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await ie(`pulling ${d}`,()=>b(T,x,d)),S=ge(process.cwd(),h??y.slug??d);await be.mkdir(S,{recursive:!0});let E=await f(S,y.files,!!v.force);_(`pulled ${E} file${E===1?"":"s"} \u2192 ${S} (rev ${y.rev}).`),_(`next: cd ${_l(process.cwd(),S)||"."} && turbobase apps deploy ${y.slug}`)}),c.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(d,h,v)=>{let T=ge(process.cwd(),h??d),x=await Qt(v.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:S}=await Promise.resolve().then(()=>(p_(),d_)),E=v.title??d,O=y({slug:d,title:E,appTsx:S(E),instanceOrigin:x?.baseUrl});await be.mkdir(T,{recursive:!0});let j=await f(T,O,!!v.force);if(_(`scaffolded ${j} file${j===1?"":"s"} \u2192 ${T}`),v.claude!==!1){let re=Su({baseUrl:x?.baseUrl,token:x?.token,appSlug:d}),U=0;for(let ne of re){let Ee=await BT(Ot(T,ne.path),ne);(Ee==="wrote"||Ee==="merged")&&(U+=1)}_(`wired Claude Code: ${U} file${U===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),x||q("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let M=_l(process.cwd(),T)||".";_(`next: cd ${M} && npm install && npm run dev`),_(` turbobase apps create ${d}`),_(` turbobase apps push ${d} .`),_(` turbobase apps deploy ${d} .`)}),c.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),x;try{x=await T.appsList()}catch(y){ee(y,"extensions:deploy","list apps"),k(`list apps failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(x,null,2));if(x.length===0)return _("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");_(tr(x.map(y=>[y.slug,y.name,y.deployed?"yes":"no",y.sourceRev===null?"\u2014":`rev ${y.sourceRev}`,y.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),c.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(d,h,v)=>{let T=ge(process.cwd(),h??".");await be.stat(T).then(le=>le.isDirectory()).catch(()=>!1)||k(`${T} is not a directory.`);let{baseUrl:y,token:S}=await G(v.baseUrl),E=v.proposal??await $(T),{files:O,skipped:j,secrets:M,unstorable:re}=await Aw(T),U=Object.keys(O).length;if(U===0&&k(`no source files found under ${T} (build output and node_modules are skipped).`),re.length>0){for(let le of re)q(`${le} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${re.length} ${re.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let le of j)q(g.dim(`skipped binary file ${le}`));for(let le of M)q(g.dim(`skipped ${le} (holds credentials \u2014 never pushed)`));let ne=await ie(`pushing ${U} file${U===1?"":"s"}`,()=>R(y,S,d,O,v.note,E));_(`pushed ${ne.files} file${ne.files===1?"":"s"} \u2192 ${ne.slug} rev ${ne.rev} (source only, nothing deployed).`);let Ee=await vs(new K({baseUrl:y,token:S}),ne.slug);Ee&&Ee.entriesAdded>0&&_(`${Ee.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),_(`next: turbobase apps deploy ${ne.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let h=await hg(),{baseUrl:v,token:T}=await G(d.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await ie(`planning against ${d.to??v}`,()=>x.configPlan(h))}catch(S){k(`plan failed: ${S instanceof Error?S.message:String(S)}`)}$q(y,d.to??v)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let h=await hg(),{baseUrl:v,token:T}=await G(d.baseUrl),x=h.tenant??Tq(v),y=Nb(d.confirm,x);y.ok||k(`promote refused (fail-closed): ${y.reason}`);let S=new K({baseUrl:v,token:T});try{let E=await ie(`promoting ${d.from} \u2192 ${d.to} (${x})`,()=>S.configApply(h,{prune:d.prune}));if(nt()){let j=[`${g.bold(`${d.from} \u2192 ${d.to}`)} ${g.dim(x??"")}`,`${Kr.add(String(E.applied.add))} ${Kr.change(String(E.applied.change))} ${Kr.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&j.push(g.dim(`${E.backfillsQueued.length} backfill(s) queued`)),_(Wr("Promoted",j))}else _(`promoted ${d.from} \u2192 ${d.to} (${x}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""));let O=E.skippedDestroys??[];if(O.length>0){q(`${O.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let j of O)q(` ${j.kind} ${j.id}`);q("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof se&&E.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(d,h)=>{let v=pg(h.reporter),T=ge(process.cwd(),d),x=await ms(T),y=Xy(x);v?_(ca(_q(d,y),v)):_(Qy(d,y,{warn:g.yellow,ok:g.green,dim:g.dim})),h.ci&&y.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(d,h)=>{let v=pg(h.reporter),T=await Zy(ge(process.cwd(),d));if(h.against){h.against!=="sandbox"&&k(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Fy(gu(T))}catch(S){k(S instanceof Error?S.message:String(S))}return}h.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let x;try{x=await By(ge(process.cwd(),h.fixture))}catch(S){k(`could not read fixture ${h.fixture}: ${S instanceof Error?S.message:String(S)}`)}let y=await qy(T,x,h.fixture,{resolveDir:Ur(ge(process.cwd(),d))});if(v){let S=vq(y);_(ca(S,v)),wl(S.cases.some(E=>E.status==="failed")?1:0)}_(Vy(y,!!h.trace)),wl(y.error?1:0)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v});try{await ib(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:_})}catch(x){x instanceof se&&x.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),x instanceof se&&x.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${x instanceof Error?x.message:String(x)}`)}});let fn=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");fn.command("list").description("List hook proposals and the evidence behind each (defaults to the pending queue).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <list>","proposed | active | rejected (comma-joined). Default: proposed.").option("--provenance <list>","mechanic | operator | learning | code-baseline (comma-joined).").option("--record-type <type>","Only proposals for this record type.").option("--source <system>","Only proposals for this adapter id.").option("--limit <n>","Max rows listed (default 200).").option("--json","Emit raw JSON instead of a table.").action(async d=>{await fw(d)}),fn.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,h)=>{await gw(d??[],h)}),fn.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{await yw(d,h)}),fn.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,h)=>{await bw(d,h)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await ww(d,h)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await _w(d,h)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await vw(d,h)}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(d,h)=>{let v=d.lastIndexOf("@"),T=v>0?d.slice(0,v):d,x=v>0?d.slice(v+1):void 0,y=du();y||k(`marketplace not configured \u2014 set ${ho} and ${ea}.
|
|
4200
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=pu(y.registryUrl);S&&k(S);let{baseUrl:E,token:O}=await G(h.baseUrl),j=new ds(y),M;try{M=await ie(`fetching ${d}`,()=>j.fetchBundle(T,x))}catch(le){k(`marketplace fetch failed for ${d}: ${le instanceof Error?le.message:String(le)}`)}let re=Zi(M.manifest),U=null;if(re.length>0){if(!h.connection){let le=re.map(Ce=>Ce.source_system).join(", ");k(`${M.name}@${M.version} declares a connection input (source: ${le}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}U=h.connection}let ne=kq(M.bundle,M.name,M.kind),Ee=new K({baseUrl:E,token:O});try{let le=await ie(`installing ${M.name}@${M.version}`,()=>Ee.deploy({...ne,provenance:"marketplace",...U?{connectionId:U}:{}}));_(`installed ${M.name}@${M.version} \u2192 ${le.id} (status=${le.status}, ${le.outcome})`+(U?` bound to connection ${U}.`:"."))}catch(le){le instanceof se&&le.status===403&&k("install forbidden (403) \u2014 the stored PAT is not for an admin."),k(`install failed: ${le instanceof Error?le.message:String(le)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(d,h)=>{let v=du();v||k(`marketplace not configured \u2014 set ${ho} and ${ea}.
|
|
4201
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=pu(v.registryUrl);T&&k(T);let x=ge(process.cwd(),d),y=await ms(x),S=/\bdefineConduit\s*[<(]/.test(y)?"conduit":"hook",E={};if(h.manifest){let M=ge(process.cwd(),h.manifest),re;try{re=await be.readFile(M,"utf8")}catch{k(`manifest not found at ${h.manifest}.`)}let U;try{U=JSON.parse(re)}catch{k(`manifest is not valid JSON: ${h.manifest}.`)}(typeof U!="object"||U===null||Array.isArray(U))&&k("manifest must be a JSON object."),E=U}try{Hl(E,y)}catch(M){M instanceof Hr&&k(M.message),k(`manifest validation failed: ${M instanceof Error?M.message:String(M)}`)}let O=new ds(v);try{await ie(`publishing ${h.name}@${h.pkgVersion}`,()=>O.publish({name:h.name,version:h.pkgVersion,kind:S,bundle:y,manifest:E}))}catch(M){M instanceof se&&M.status===403&&k("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),M instanceof se&&M.status===409&&k(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),k(`publish failed: ${M instanceof Error?M.message:String(M)}`)}let j=Zi(E);_(`published ${h.name}@${h.pkgVersion} (kind=${S}) to the marketplace.`),j.length>0&&_(` declares ${j.length} connection input(s): ${j.map(M=>M.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async d=>{let h=await Qt(d.baseUrl).catch(()=>null),v=Su({baseUrl:h?.baseUrl,token:h?.token}),T=0,x=0,y=0;for(let S of v){let E=ge(process.cwd(),S.path),O=await BT(E,S);O==="wrote"?(T+=1,_(` wrote ${S.path}`)):O==="merged"?(y+=1,_(` merged ${S.path} (added the .mcp.json rule)`)):(x+=1,_(` skipped ${S.path} (exists)`))}_(`
|
|
4202
|
+
project init: ${T} written, ${y} merged, ${x} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${xu} (non-destructive).`).action(async()=>{let d=$b(),h=0,v=0;for(let T of d){let x=ge(process.cwd(),T.path);await to(x,T.content,T.executable)==="wrote"?(h+=1,_(` wrote ${T.path}`)):(v+=1,_(` skipped ${T.path} (exists)`))}_(`
|
|
4203
|
+
project ci: ${h} written, ${v} skipped.`),h>0&&(_(`
|
|
4204
|
+
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),_("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),_("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),x;try{x=await T.catalogRecords()}catch(j){j instanceof se&&(j.status===401||j.status===403)&&k("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),k(`catalog fetch failed: ${j instanceof Error?j.message:String(j)}`)}if(x.length===0){_("no records in the instance catalog \u2014 nothing to generate.");return}let y=ge(process.cwd(),d.out),S=Ky(x,{event:d.event}),E=0,O=0;for(let{recordType:j,fixture:M}of S){let re=Ot(y,`${j}.json`),U=`${JSON.stringify(M,null,2)}
|
|
4205
|
+
`;d.force?(await be.mkdir(Ur(re),{recursive:!0}),await be.writeFile(re,U,{mode:420}),E+=1,_(` wrote ${d.out}/${j}.json`)):await to(re,U)==="wrote"?(E+=1,_(` wrote ${d.out}/${j}.json`)):(O+=1,_(` skipped ${d.out}/${j}.json (exists \u2014 use --force to overwrite)`))}_(`
|
|
4206
|
+
samples init: ${E} written, ${O} skipped.`)});let pr=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),vl=d=>[d.name??g.dim(d.id.slice(0,8)),d.status==="active"?g.green("active"):d.status==="proposed"?g.yellow("proposed"):g.dim("inactive"),d.decision==="deny"?g.red(d.decision):d.decision==="require_confirm"?g.yellow(d.decision):g.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??g.dim("any"),d.when||g.dim("(always)"),d.reason??""],HT=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];pr.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),x;try{x=await T.guardrailsList()}catch(y){ee(y,"extensions:deploy","list guardrails"),k(`list guardrails failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(x,null,2));if(x.length===0)return _(`no write guardrails \u2014 every record the admin entitlement allows is writable.
|
|
4207
|
+
`+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(tr(x.map(vl),{head:HT})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),pr.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await x.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){ee(S,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} created${y.status==="active"?"":g.dim(` (${y.status} \u2014 activate it to take effect)`)}`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),_(g.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),pr.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await x.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(S){ee(S,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(y.name??y.id)} updated`),_(g.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,h,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])pr.command(`${d} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(T,x)=>{let{baseUrl:y,token:S}=await G(x.baseUrl),E=new K({baseUrl:y,token:S});try{await E.guardrailUpdate(T,{status:h})}catch(O){ee(O,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${O instanceof Error?O.message:String(O)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(T)} ${v}`),h==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});pr.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T});try{await x.guardrailDelete(d)}catch(y){ee(y,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),pr.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y=O=>O==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let O;try{O=await x.guardrailPostureGet()}catch(j){ee(j,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${j instanceof Error?j.message:String(j)}`)}_(`guardrail posture: ${g.bold(y(O.mode))}`),_(g.dim(O.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&k("posture must be 'allow' or 'deny'.");let E;try{E=await x.guardrailPostureSet(S)}catch(O){ee(O,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${O instanceof Error?O.message:String(O)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(y(E.mode))}`),E.mode==="deny"&&_(g.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),pr.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let h;if(d.fields)try{h=JSON.parse(d.fields)}catch(E){k(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:v,token:T}=await G(d.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await x.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){ee(E,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return _(JSON.stringify(y,null,2));let S=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${g.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(g.dim(` ${y.reason}`))):y.allowed?_(`${g.green("\u2713")} ${S} \u2014 ${y.decision}`+(y.blockedBy?g.dim(` (rule ${y.blockedBy})`):g.dim(" (no rule matched)"))):(_(`${g.red("\u2717")} ${S} \u2014 ${y.decision} by ${g.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&_(g.dim(` ${y.message}`))),y.decision==="require_confirm"&&_(g.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let es=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Ai=(d,h={})=>{let v=`${g.bold(d.table)} ${g.dim(d.displayName)}`;_(d.exists===!1?`${v} ${g.dim("(new)")}`:v);for(let T of d.fields){let x=[T.required?"required":null].filter(Boolean).join(", "),y=h.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${x?` (${x})`:""}${y}`)}h.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ci(d){if(d instanceof se&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(q(h.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let wg=async d=>{let h=Ot(ge(process.cwd(),d),"public","turbobase.json"),v=await be.readFile(h,"utf8").catch(()=>null);if(v===null)return null;let T;try{T=JSON.parse(v)}catch(y){k(`${h} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let x=T.tables;return x===void 0?{tables:[],manifestPath:h}:(Array.isArray(x)||k(`${h}: "tables" must be an array.`),{tables:x,manifestPath:h})};es.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),x;try{x=await T.tablesList()}catch(y){ee(y,"extensions:deploy","list tables"),k(`list tables failed: ${y instanceof Error?y.message:String(y)}`)}if(d.json)return _(JSON.stringify(x,null,2));if(x.length===0)return _("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");_(tr(x.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),es.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,h)=>{let v=await wg(d??".");if(v||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:x}=await G(h.baseUrl),y=new K({baseUrl:T,token:x}),S;try{S=await ie("planning tables",()=>y.tablesPlan({claimedBy:h.as,tables:v.tables}))}catch(E){ee(E,"extensions:deploy","plan tables"),Ci(E)}_(`claiming as ${g.bold(S.claimedBy)}`);for(let E of S.tables)Ai(E,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),es.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,h)=>{let v=await wg(d??".");if(v||k(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:x}=await G(h.baseUrl),y=new K({baseUrl:T,token:x}),S;try{S=await ie("applying tables",()=>y.tablesApply({claimedBy:h.as,tables:v.tables}))}catch(E){ee(E,"extensions:deploy","apply tables"),Ci(E)}for(let E of S.tables)Ai(E,{showClaimants:!0});_(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),es.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let v=h.field.map(E=>{let[O,j,M]=E.split(":");return(!O||!j)&&k(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&k(`--field "${E}": the third part may only be "required".`),{name:O,type:j,...M==="required"?{required:!0}:{}}}),{baseUrl:T,token:x}=await G(h.baseUrl),y=new K({baseUrl:T,token:x}),S;try{S=await ie(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:v,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){ee(E,"extensions:deploy","create a table"),Ci(E)}for(let E of S.tables)Ai(E);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),es.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.confirm!==d&&k(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await ie(`dropping cr_${d}`,()=>x.tablesDrop(d,h.confirm))}catch(S){ee(S,"extensions:deploy","drop a table"),k(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let kl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");kl.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let h=mg(),v;try{v=await qw(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof xs&&k(T.message),k(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}_(`sandbox ${v.name} ready.`),_(` source: ${v.fromTenant} (sampled ${Math.round(v.sampleFraction*100)}%, redacted)`),_(` url: ${v.url}`),_(` expires: ${v.expiresAt}`)}),kl.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let h=mg();await Ju(h).catch(()=>[]);let v;try{v=await Fw(h,d)}catch(T){k(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}v||k(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),kl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=mg(),h=await Ju(d).catch(()=>[]),v=await $a(),{active:T}=Gu(v);if(T.length===0)_("no active sandboxes.");else{for(let x of T)_(` ${x.name} from=${x.fromTenant} expires=${x.expiresAt} ${x.url}`);_(`
|
|
4208
|
+
${T.length} active sandbox(es).`)}h.length>0&&_(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",ma).action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),x;try{x=await ie("exporting instance config",()=>T.configExport())}catch(E){E instanceof se&&(E.status===401||E.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let y=typeof x.serialized=="string"?x.serialized:`${JSON.stringify(x.manifest??x,null,2)}
|
|
4209
|
+
`,S=ge(process.cwd(),d.out,bs);await be.mkdir(Ur(S),{recursive:!0}),await be.writeFile(S,y,"utf8"),_(`wrote ${d.out}/${bs} (${y.split(`
|
|
4210
|
+
`).length} lines).`)});let _g=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),KT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],vg=()=>process.env.TURBOBASE_HOME?.trim()||Ot(hq(),".turbobase"),WT=()=>"1.40.0",Ii=async()=>Promise.all(KT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));_g.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ii();for(let h of d)_(`${h.present?Le.success("installed"):Le.warn("missing")} ${g.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&_(`
|
|
4211
|
+
run \`${wo} ext extras install\` to fetch them into ${vg()}.`)}),_g.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ii();if(d.every(O=>O.present)){_(Le.success("extras already installed \u2014 nothing to do."));return}let h=vg();await be.mkdir(h,{recursive:!0});let v=d.filter(O=>!O.present).map(O=>O.name),T=Bu(process.platform,process.arch),x=async(O,j)=>{let{code:M,stderr:re}=await Pi("npm",["install","--prefix",h,"--no-audit","--no-fund",...O]);M!==0&&k(`extras install failed while installing ${j} (npm exited ${M}).
|
|
4209
4212
|
${re.trim()}
|
|
4210
|
-
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(
|
|
4211
|
-
${Object.keys(y.owned).length} owned file(s), ${Object.keys(y.context).length} context file(s), ${
|
|
4213
|
+
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=v.filter(O=>O!=="isolated-vm");if(y.length>0){let O=y.map(j=>`${j}@${qu[j]??"latest"}`);_(`installing ${O.join(", ")} \u2192 ${h}/node_modules \u2026`),await x(O,y.join(", "))}if(v.includes("isolated-vm")){let O=`isolated-vm@${qu["isolated-vm"]}`;if(_(`installing ${O} \u2192 ${h}/node_modules \u2026`),await x(["--ignore-scripts",O],"isolated-vm"),Nw.includes(T)){let M=`${Fu}@${WT()}`;_(`fetching ${M} (no upstream binary for ${T}) \u2026`);let{code:re}=await Pi("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",M]);re!==0&&_(Le.warn(`could not fetch ${M} \u2014 falling back to a source build.`))}let j=await Lw({home:h});j.length>0&&_(` ${Le.success("prebuilt")} ${j.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await Ii(),E=S.filter(O=>!O.present).map(O=>O.name);if(E.includes("isolated-vm")){_(Le.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${Zu()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:O}=await Pi("npm",["rebuild","--prefix",h,"isolated-vm"]);O===0&&(S=await Ii(),E=S.filter(j=>!j.present).map(j=>j.name))}E.length>0&&k(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${Zu()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(Le.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let ro=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");ro.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let v=await Rq(ge(process.cwd(),d.project??".")),T=Object.keys(v).length;!d.solution&&T===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let y=(d.ref?await fg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await fg(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await fg(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,O=d.prUrl??process.env.PR_URL??null,{baseUrl:j,token:M}=await G(d.baseUrl),re=new K({baseUrl:j,token:M}),U;try{U=await re.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:T>0?v:null,gitRepo:S,gitRef:E,gitSha:y,prUrl:O})}catch(ne){ee(ne,"releases:write","release deploy"),ne instanceof se&&ne.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}_(`release ${U.releaseId} enqueued \u2192 taskId=${U.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Cu(()=>re.releaseStatus(U.releaseId),`release ${U.releaseId}`,d.intervalMs)}),ro.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await x.releaseFiles(d)}catch(O){O instanceof se&&O.status===404&&k(`release ${d} not found.`),O instanceof se&&O.status===409&&k(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),ee(O,"releases:write","pull a release"),k(`release pull failed: ${O instanceof Error?O.message:String(O)}`)}let S=ge(process.cwd(),h.dir),E=0;for(let[O,j]of[["owned",y.owned],["context",y.context]])for(let[M,re]of Object.entries(j)){let U=Ot(S,O,M);await be.mkdir(Ur(U),{recursive:!0}),await be.writeFile(U,re,"utf8"),E++}await be.writeFile(Ot(S,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),_(`pulled release ${y.releaseId} (${y.status}) \u2192 ${S}
|
|
4214
|
+
${Object.keys(y.owned).length} owned file(s), ${Object.keys(y.context).length} context file(s), ${E} total
|
|
4212
4215
|
`+(y.logTail?`
|
|
4213
4216
|
the failure these bytes produced:
|
|
4214
4217
|
${y.logTail.trim()}
|
|
4215
4218
|
`:"")+`
|
|
4216
4219
|
edit the files under owned/, then:
|
|
4217
|
-
turbobase release push ${y.releaseId} --dir ${
|
|
4218
|
-
`+
|
|
4219
|
-
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let
|
|
4220
|
+
turbobase release push ${y.releaseId} --dir ${h.dir}`)}),ro.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y=ge(process.cwd(),h.dir),S;try{S=await x.releaseFiles(d)}catch(U){U instanceof se&&U.status===404&&k(`release ${d} not found.`),ee(U,"releases:write","push a release"),k(`release push failed: ${U instanceof Error?U.message:String(U)}`)}let E=async(U,ne)=>{try{return await be.readFile(Ot(y,U,ne),"utf8")}catch{return null}},O=[];for(let[U,ne]of Object.entries(S.context)){let Ee=await E("context",U);Ee!==null&&Ee!==ne&&O.push(U)}O.length>0&&k(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
|
|
4221
|
+
`+O.map(U=>` context/${U}`).join(`
|
|
4222
|
+
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let j={...S.context},M=0;for(let[U,ne]of Object.entries(S.owned)){let Ee=await E("owned",U);j[U]=Ee??ne,Ee!==null&&Ee!==ne&&M++}M===0&&_("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let re=h.target==="approved"?"approved":"auto";try{let U=await x.releasePush(d,{files:j,target:re,...h.approvedBy?{approvedBy:h.approvedBy}:{}});_(`pushed ${Object.keys(j).length} file(s) (${M} edited) \u2192 release ${U.releaseId} (task ${U.taskId}).
|
|
4220
4223
|
follow it with:
|
|
4221
|
-
turbobase release status ${U.releaseId} --follow`)}catch(U){U instanceof
|
|
4222
|
-
${x.length} release(s).`)});let
|
|
4223
|
-
`)),t&&void 0,e}function
|
|
4224
|
-
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return
|
|
4225
|
-
${t.add.length} to add, ${t.change.length} to change, ${t.destroy.length} to destroy.`+(t.add.length+t.change.length+t.destroy.length===0?" (no changes \u2014 up to date.)":""))}function
|
|
4224
|
+
turbobase release status ${U.releaseId} --follow`)}catch(U){U instanceof se&&U.status===403&&k("an approved target needs --approved-by (the deploy gate fails closed)."),U instanceof se&&U.status===409&&k("that solution already has an active release \u2014 roll it back or wait for it."),ee(U,"releases:write","push a release"),k(`release push failed: ${U instanceof Error?U.message:String(U)}`)}}),ro.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T});if(h.follow){await Cu(()=>x.releaseStatus(d),`release ${d}`,h.intervalMs);return}let y;try{y=await x.releaseStatus(d)}catch(S){ee(S,"releases:write","release status"),S instanceof se&&S.status===404&&k(`release ${d} not found.`),k(`release status failed: ${S instanceof Error?S.message:String(S)}`)}_(`release ${d}: status=${y.releaseStatus??"?"} stage=${y.stage} ${y.percent}%`+(y.runStatus?` (${y.runStatus})`:"")),y.outputTail&&_(y.outputTail.replace(/\n+$/,""))}),ro.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T}),y;try{y=await x.releaseRollback(d)}catch(S){ee(S,"releases:write","release rollback"),S instanceof se&&S.status===404&&k(`release ${d} not found.`),S instanceof se&&S.status===409&&k(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),k(`release rollback failed: ${S instanceof Error?S.message:String(S)}`)}_(`release ${y.releaseId} rolled back \u2192 status=${y.release?.status??"rolled_back"}.`)}),ro.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),x;try{x=await T.releaseList()}catch(y){ee(y,"releases:write","release list"),k(`release list failed: ${y instanceof Error?y.message:String(y)}`)}if(x.length===0){_("no releases.");return}if(nt())_(tr(x.map(y=>[y.id,go(y.status),y.target,y.backend,y.solutionTitles?.length?y.solutionTitles.map(S=>`"${S}"`).join(", "):g.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let y of x){let S=y.solutionTitles?.length?` "${y.solutionTitles.join('", "')}"`:"";_(` ${y.id} ${y.status.padEnd(11)} target=${y.target} backend=${y.backend}${S}`)}_(`
|
|
4225
|
+
${x.length} release(s).`)});let no=e.command("processes").description("See what processes are deployed, how they are triggered, and what they have done.");return no.command("list").description("Every deployed process with its trigger, its schedule and its last runs.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v});try{let x=await T.processes();d.json?_(JSON.stringify(x,null,2)):ub(x,_)}catch(x){k(`processes list failed: ${x instanceof Error?x.message:String(x)}`)}}),no.command("runs").description("One process's run history, newest first.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T});try{let y=await x.processRuns(d);h.json?_(JSON.stringify(y,null,2)):db(d,y,_)}catch(y){k(`processes runs failed: ${y instanceof Error?y.message:String(y)}`)}}),no.command("run").description("One run and its step ledger.").argument("<run-id>","The run id the invoke answered with.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T});try{let y=await x.processRun(d);h.json?_(JSON.stringify(y,null,2)):da(y,_)}catch(y){k(`processes run failed: ${y instanceof Error?y.message:String(y)}`)}}),no.command("invoke").description("Start a run of a deployed process \u2014 queued by default, or waited for with --sync.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--input <json>",`The process input as a JSON object, e.g. '{"customerId":"42"}'.`).option("--input-file <path>","Read the process input from a JSON file instead.").option("--sync","Wait for the run to settle (bounded by the instance's budget) and print its outcome.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the response as JSON.").action(async(d,h)=>{h.input!==void 0&&h.inputFile!==void 0&&k("pass --input or --input-file, not both.");let v={};if(h.input!==void 0||h.inputFile!==void 0){let S,E=h.input!==void 0?"--input":"--input-file";if(h.input!==void 0)S=h.input;else try{S=await be.readFile(ge(process.cwd(),h.inputFile),"utf8")}catch{k(`input file not found at ${h.inputFile}.`)}let O=hb(S,E);O.ok||k(O.message),v=O.input}let{baseUrl:T,token:x}=await G(h.baseUrl),y=new K({baseUrl:T,token:x});try{let S=await y.invokeProcess(d,v,h.sync?"sync":"async");h.json?_(JSON.stringify(S,null,2)):mb(S,d,wo,_)}catch(S){S instanceof se&&S.status===403&&S.body?.reason==="admin_required"&&k("processes invoke forbidden (403) \u2014 the token's owner must be an administrator to start a process."),ee(S,"extensions:deploy","processes invoke"),k(`processes invoke failed: ${S instanceof Error?S.message:String(S)}`)}}),no.command("cancel").description("Stop one run \u2014 a queued run never executes, a running one stops at its next step.").argument("<run-id>","The run to stop.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T});try{let y=await x.cancelProcessRun(d);_(`cancelled ${y.runId??d} (${y.state??"cancelled"}).`),_("A run already going stops at its next step boundary; writes it has already made stay.")}catch(y){k(`processes cancel failed: ${y instanceof Error?y.message:String(y)}`)}}),no.command("rollback").description("Undo a finished run \u2014 delete, newest first, the records its ledger proves it created.").argument("<run-id>","The finished run to roll back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:v,token:T}=await G(h.baseUrl),x=new K({baseUrl:v,token:T});try{let y=await x.rollbackProcessRun(d);if(!y.queued){_(`${y.runId??d} is already rolled back \u2014 nothing to do.`);return}_(`rollback queued for ${y.runId??d} (was ${y.state}).`),_(`Only records this run created are deleted; records it updated are left alone. Source deletes are paced by the rollback cap \u2014 follow with \`turbobase processes run ${y.runId??d}\`.`)}catch(y){k(`processes rollback failed: ${y instanceof Error?y.message:String(y)}`)}}),e.command("data").description("Act on one record in your instance \u2014 today, link a row after a settle conflict.").command("settle").description("Link a row to the record the connected system already created, after a write_settle_conflict.").argument("<record-type>","The record type, e.g. salesOrder or nonInventorySaleItem.").argument("<pg-row-id>","The row's pg_row_id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the answer as JSON.").action(async(d,h,v)=>{let{baseUrl:T,token:x}=await G(v.baseUrl),y=new K({baseUrl:T,token:x});try{let S=await y.settleRow(d,h);if(v.json){_(JSON.stringify(S,null,2));return}_(`linked ${d} ${S.pgRowId} to ${S.externalId}.`),S.discarded.length>0&&_(`discarded the inbound copy of the same record: ${S.discarded.join(", ")}.`)}catch(S){k(`data settle failed: ${S instanceof Error?S.message:String(S)}`)}}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--process-run <runId>","One process run's step ledger. With --follow it streams and EXITS when the run finishes.").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:h,token:v}=await G(d.baseUrl),T=new K({baseUrl:h,token:v}),x=d.limit?Number(d.limit):void 0,y=d.intervalMs?Number(d.intervalMs):void 0;if(d.processRun){try{await pb(T,d.processRun,{...d.follow?{follow:!0}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch(S){k(`logs --process-run failed: ${S instanceof Error?S.message:String(S)}`)}return}if(d.conduit){try{await sb(T,d.conduit,{...d.follow?{follow:!0}:{},...x!==void 0?{limit:x}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch(S){k(`logs --conduit failed: ${S instanceof Error?S.message:String(S)}`)}return}if(d.extension){try{let S=await T.logs(d.extension,x);S.length===0&&_(`no logs for ${d.extension}.`);for(let E of S)_(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(S){k(`logs --extension failed: ${S instanceof Error?S.message:String(S)}`)}return}try{await ab(T,{...d.subsystem?{subsystem:d.subsystem}:{},...d.severity?{severity:d.severity}:{},...d.code?{code:d.code}:{},...d.since?{since:d.since}:{},...d.correlationId?{correlationId:d.correlationId}:{},...d.follow?{follow:!0}:{},...d.json?{json:!0}:{},...x!==void 0?{limit:x}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch(S){k(`logs failed: ${S instanceof Error?S.message:String(S)}`)}}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(FT(),qT));await h({baseUrl:d.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
|
|
4226
|
+
`)),t&&void 0,e}function kq(t,e,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return s?s[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function xq(t){let e=Ot(ge(process.cwd(),t),"public","turbobase.json"),r=await be.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){k(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&k(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function Sq(){let t=ge(process.cwd(),ma,bs),e;try{e=await be.readFile(t,"utf8")}catch{k(`no config found \u2014 this project authors none (no ${ga}/, ${ya}/, ${Gr} or ${Jr}) and there is no ${ma}/${bs}.
|
|
4227
|
+
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Ob(e)}catch(r){k(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function hg(){let t=process.cwd();if(!await Db(t))return Sq();let e;try{e=await Mb(t,{inline:hu})}catch(r){k(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)q(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&k(`${e.unparsed.length} extension file(s) could not be identified. Every hook/conduit needs a literal \`id:\`, \`recordType:\` and \`event:\`/\`on:\` \u2014 run \`turbobase ext lint <file>\` on each.`),e.manifest}function $q(t,e){_(`plan against ${e}:`);for(let r of t.add)_(` ${Kr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)_(` ${Kr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)_(` ${Kr.destroy(`${r.kind} ${r.id}`)}`);_(`
|
|
4228
|
+
${t.add.length} to add, ${t.change.length} to change, ${t.destroy.length} to destroy.`+(t.add.length+t.change.length+t.destroy.length===0?" (no changes \u2014 up to date.)":""))}function Tq(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function Pi(t,e,r){return new Promise(n=>{let o=yg(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),s="";o.stderr?.on("data",i=>{let a=i.toString();s+=a,process.stderr.write(a)}),o.on("error",i=>n({code:-1,stderr:i.message})),o.on("exit",i=>n({code:i??-1,stderr:s}))})}function mg(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let o=n?t.replace(/\/[^/]*$/,`/${n}`):t,s=await Pi("psql",[o,"-v","ON_ERROR_STOP=1","-c",r]);if(s.code!==0)throw new Error(`psql failed (exit ${s.code}): ${s.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),o=await Pi("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(c=>a[c]===null||a[c]===void 0?"NULL":`'${String(a[c]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function Rq(t){let e=ge(t,"src"),r={},n=async o=>{let s;try{s=await be.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=Ot(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=_l(e,a).split(gg).join("/");r[c]=await be.readFile(a,"utf8")}}};return await n(e),r}function fg(t){return new Promise(e=>{let r=yg("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("exit",o=>e(o===0&&n.trim()?n.trim():null))})}var Eq=!1;Eq&&bg().parseAsync(process.argv).catch(t=>k(t instanceof Error?t.message:String(t)));bg().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
|
|
4226
4229
|
`),process.exit(1)});
|