@turbobase/cli 1.1.7
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/LICENSE +48 -0
- package/README.md +119 -0
- package/dist/turbobase-standalone.mjs +1635 -0
- package/dist/turbobase.js +1588 -0
- package/package.json +37 -0
|
@@ -0,0 +1,1635 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __tbCreateRequire } from 'node:module';
|
|
3
|
+
const require = __tbCreateRequire(import.meta.url);
|
|
4
|
+
var L$=Object.create;var vc=Object.defineProperty;var D$=Object.getOwnPropertyDescriptor;var Z$=Object.getOwnPropertyNames;var U$=Object.getPrototypeOf,q$=Object.prototype.hasOwnProperty;var Ro=(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 E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Po=(t,e)=>{for(var r in e)vc(t,r,{get:e[r],enumerable:!0})},F$=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Z$(e))!q$.call(t,o)&&o!==r&&vc(t,o,{get:()=>e[o],enumerable:!(n=D$(e,o))||n.enumerable});return t};var xc=(t,e,r)=>(r=t!=null?L$(U$(t)):{},F$(e||!t||!t.__esModule?vc(r,"default",{value:t,enumerable:!0}):r,t));var Ao=Z(kc=>{var ti=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}},$c=class extends ti{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};kc.CommanderError=ti;kc.InvalidArgumentError=$c});var ri=Z(Tc=>{var{InvalidArgumentError:B$}=Ao(),Sc=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 B$(`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 V$(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Tc.Argument=Sc;Tc.humanReadableArgName=V$});var Rc=Z(Wh=>{var{humanReadableArgName:H$}=ri(),Ec=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=>H$(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(p,m){if(m){let b=`${p.padEnd(n+i)}${m}`;return r.wrap(b,o-s,n+i)}return p}function c(p){return p.join(`
|
|
5
|
+
`).replace(/^/gm," ".repeat(s))}let u=[`Usage: ${r.commandUsage(e)}`,""],d=r.commandDescription(e);d.length>0&&(u=u.concat([r.wrap(d,o,0),""]));let l=r.visibleArguments(e).map(p=>a(r.argumentTerm(p),r.argumentDescription(p)));l.length>0&&(u=u.concat(["Arguments:",c(l),""]));let f=r.visibleOptions(e).map(p=>a(r.optionTerm(p),r.optionDescription(p)));if(f.length>0&&(u=u.concat(["Options:",c(f),""])),this.showGlobalOptions){let p=r.visibleGlobalOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));p.length>0&&(u=u.concat(["Global Options:",c(p),""]))}let h=r.visibleCommands(e).map(p=>a(r.subcommandTerm(p),r.subcommandDescription(p)));return h.length>0&&(u=u.concat(["Commands:",c(h),""])),u.join(`
|
|
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),u=e.slice(n).replace(`\r
|
|
7
|
+
`,`
|
|
8
|
+
`),d=" ".repeat(n),f="\\s\u200B",h=new RegExp(`
|
|
9
|
+
|.{1,${a-1}}([${f}]|$)|[^${f}]+?([${f}]|$)`,"g"),p=u.match(h)||[];return c+p.map((m,b)=>m===`
|
|
10
|
+
`?"":(b>0?d:"")+m.trimEnd()).join(`
|
|
11
|
+
`)}};Wh.Help=Ec});var Ic=Z(ni=>{var{InvalidArgumentError:K$}=Ao(),Pc=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=Gh(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 K$(`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 W$(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ac=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 W$(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Gh(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}}ni.Option=Pc;ni.splitOptionFlags=Gh;ni.DualOptions=Ac});var Yh=Z(Jh=>{function G$(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 J$(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=G$(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
|
+
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
13
|
+
(Did you mean ${n[0]}?)`:""}Jh.suggestSimilar=J$});var nm=Z(rm=>{var Y$=Ro("events").EventEmitter,Oc=Ro("child_process"),lr=Ro("path"),Cc=Ro("fs"),Oe=Ro("process"),{Argument:X$,humanReadableArgName:Q$}=ri(),{CommanderError:zc}=Ao(),{Help:ek}=Rc(),{Option:Xh,splitOptionFlags:tk,DualOptions:rk}=Ic(),{suggestSimilar:Qh}=Yh(),Nc=class t extends Y${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=>Oe.stdout.write(r),writeErr:r=>Oe.stderr.write(r),getOutHelpWidth:()=>Oe.stdout.isTTY?Oe.stdout.columns:void 0,getErrHelpWidth:()=>Oe.stderr.isTTY?Oe.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 ek,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 X$(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 zc(e,r,n)),Oe.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 Xh(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 Xh)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,u)=>{let d=a.exec(c);return d?d[0]:u},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=Oe.argv,Oe.versions&&Oe.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":Oe.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(d,l){let f=lr.resolve(d,l);if(Cc.existsSync(f))return f;if(o.includes(lr.extname(l)))return;let h=o.find(p=>Cc.existsSync(`${f}${p}`));if(h)return`${f}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=Cc.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=lr.resolve(lr.dirname(d),a)}if(a){let d=s(a,i);if(!d&&!e._executableFile&&this._scriptPath){let l=lr.basename(this._scriptPath,lr.extname(this._scriptPath));l!==this._name&&(d=s(a,`${l}-${e._name}`))}i=d||i}n=o.includes(lr.extname(i));let c;Oe.platform!=="win32"?n?(r.unshift(i),r=tm(Oe.execArgv).concat(r),c=Oc.spawn(Oe.argv[0],r,{stdio:"inherit"})):c=Oc.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=tm(Oe.execArgv).concat(r),c=Oc.spawn(Oe.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(l=>{Oe.on(l,()=>{c.killed===!1&&c.exitCode===null&&c.kill(l)})});let u=this._exitCallback;u?c.on("close",()=>{u(new zc(Oe.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Oe.exit.bind(Oe)),c.on("error",d=>{if(d.code==="ENOENT"){let l=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",f=`'${i}' does not exist
|
|
16
|
+
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
17
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
18
|
+
- ${l}`;throw new Error(f)}else if(d.code==="EACCES")throw new Error(`'${i}' not executable`);if(!u)Oe.exit(1);else{let l=new zc(1,"commander.executeSubCommandAsync","(error)");l.nestedError=d,u(l)}}),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 em(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),em(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 u=this._findOption(c);if(u){if(u.required){let d=s.shift();d===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,d)}else if(u.optional){let d=null;s.length>0&&!i(s[0])&&(d=s.shift()),this.emit(`option:${u.name()}`,d)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let u=this._findOption(`-${c[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,c.slice(2)):(this.emit(`option:${u.name()}`),s.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let u=c.indexOf("="),d=this._findOption(c.slice(0,u));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,c.slice(u+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
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
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 Oe.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()}`,Oe.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new rk(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),u=this.options.find(l=>l.negate&&a===l.attributeName()),d=this.options.find(l=>!l.negate&&a===l.attributeName());return u&&(u.presetArg===void 0&&c===!1||u.presetArg!==void 0&&c===u.presetArg)?u:d||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=Qh(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=Qh(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=>Q$(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=lr.basename(e,lr.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=tk(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=Oe.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
|
+
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 em(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function tm(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})}rm.Command=Nc});var am=Z((Ut,im)=>{var{Argument:nk}=ri(),{Command:om}=nm(),{CommanderError:ok,InvalidArgumentError:sm}=Ao(),{Help:sk}=Rc(),{Option:ik}=Ic();Ut=im.exports=new om;Ut.program=Ut;Ut.Command=om;Ut.Option=ik;Ut.Argument=nk;Ut.Help=sk;Ut.CommanderError=ok;Ut.InvalidArgumentError=sm;Ut.InvalidOptionArgumentError=sm});function Io(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var oi=E(()=>{});var ue,jc,q,Yt,Oo=E(()=>{(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})(ue||(ue={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(jc||(jc={}));q=ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Yt=t=>{switch(typeof t){case"undefined":return q.undefined;case"string":return q.string;case"number":return Number.isNaN(t)?q.nan:q.number;case"boolean":return q.boolean;case"function":return q.function;case"bigint":return q.bigint;case"symbol":return q.symbol;case"object":return Array.isArray(t)?q.array:t===null?q.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?q.promise:typeof Map<"u"&&t instanceof Map?q.map:typeof Set<"u"&&t instanceof Set?q.set:typeof Date<"u"&&t instanceof Date?q.date:q.object;default:return q.unknown}}});var z,ak,pt,si=E(()=>{Oo();z=ue.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"]),ak=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),pt=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 u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],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,ue.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()}};pt.create=t=>new pt(t)});var ck,dr,Mc=E(()=>{si();Oo();ck=(t,e)=>{let r;switch(t.code){case z.invalid_type:t.received===q.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case z.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ue.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:r=`Unrecognized key(s) in object: ${ue.joinValues(t.keys,", ")}`;break;case z.invalid_union:r="Invalid input";break;case z.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ue.joinValues(t.options)}`;break;case z.invalid_enum_value:r=`Invalid enum value. Expected ${ue.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}"`:ue.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,ue.assertNever(t)}return{message:r}},dr=ck});function uk(t){lm=t}function Nn(){return lm}var lm,ii=E(()=>{Mc();lm=dr});function U(t,e){let r=Nn(),n=Co({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===dr?void 0:dr].filter(o=>!!o)});t.common.issues.push(n)}var Co,lk,Ye,Y,Gr,nt,ai,ci,xr,jn,Lc=E(()=>{ii();Mc();Co=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(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},lk=[];Ye=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 Y;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 Y;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}}},Y=Object.freeze({status:"aborted"}),Gr=t=>({status:"dirty",value:t}),nt=t=>({status:"valid",value:t}),ai=t=>t.status==="aborted",ci=t=>t.status==="dirty",xr=t=>t.status==="valid",jn=t=>typeof Promise<"u"&&t instanceof Promise});var dm=E(()=>{});var V,pm=E(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(V||(V={}))});function re(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 gm(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 Ek(t){return new RegExp(`^${gm(t)}$`)}function ym(t){let e=`${mm}T${gm(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 Rk(t,e){return!!((e==="v4"||!e)&&wk.test(t)||(e==="v6"||!e)&&xk.test(t))}function Pk(t,e){if(!gk.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 Ak(t,e){return!!((e==="v4"||!e)&&vk.test(t)||(e==="v6"||!e)&&$k.test(t))}function Ik(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 Mn(t){if(t instanceof ht){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ft.create(Mn(n))}return new ht({...t._def,shape:()=>e})}else return t instanceof hr?new hr({...t._def,type:Mn(t.element)}):t instanceof ft?ft.create(Mn(t.unwrap())):t instanceof Qt?Qt.create(Mn(t.unwrap())):t instanceof Xt?Xt.create(t.items.map(e=>Mn(e))):t}function Zc(t,e){let r=Yt(t),n=Yt(e);if(t===e)return{valid:!0,data:t};if(r===q.object&&n===q.object){let o=ue.objectKeys(e),s=ue.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Zc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===q.array&&n===q.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=Zc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===q.date&&n===q.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function bm(t,e){return new an({values:t,typeName:N.ZodEnum,...re(e)})}function hm(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function _m(t,e={},r){return t?kr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=hm(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=hm(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):kr.create()}var Rt,fm,oe,dk,pk,fk,hk,mk,gk,yk,bk,_k,Dc,wk,vk,xk,$k,kk,Sk,mm,Tk,$r,Jr,Yr,Xr,Qr,Ln,en,tn,kr,fr,qt,Dn,hr,ht,rn,pr,ui,nn,Xt,li,Zn,Un,di,on,sn,an,cn,Sr,Pt,ft,Qt,un,ln,qn,Ok,zo,No,dn,Ck,N,zk,wm,vm,Nk,jk,xm,Mk,Lk,Dk,Zk,Uk,qk,Fk,Bk,Vk,Uc,Hk,Kk,Wk,Gk,Jk,Yk,Xk,Qk,eS,tS,rS,nS,oS,sS,iS,aS,cS,uS,lS,dS,pS,fS,hS,mS,$m=E(()=>{si();ii();pm();Lc();Oo();Rt=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}},fm=(t,e)=>{if(xr(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 pt(t.common.issues);return this._error=r,this._error}}};oe=class{get description(){return this._def.description}_getType(e){return Yt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ye,ctx:{common:e.parent.common,data:e.data,parsedType:Yt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(jn(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:Yt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return fm(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Yt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return xr(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=>xr(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:Yt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(jn(o)?o:Promise.resolve(o));return fm(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 Pt({schema:this,typeName:N.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 ft.create(this,this._def)}nullable(){return Qt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return hr.create(this)}promise(){return Sr.create(this,this._def)}or(e){return rn.create([this,e],this._def)}and(e){return nn.create(this,e,this._def)}transform(e){return new Pt({...re(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new un({...re(this._def),innerType:this,defaultValue:r,typeName:N.ZodDefault})}brand(){return new zo({typeName:N.ZodBranded,type:this,...re(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new ln({...re(this._def),innerType:this,catchValue:r,typeName:N.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return No.create(this,e)}readonly(){return dn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},dk=/^c[^\s-]{8,}$/i,pk=/^[0-9a-z]+$/,fk=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hk=/^[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,mk=/^[a-z0-9_-]{21}$/i,gk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yk=/^[-+]?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)?)??$/,bk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_k="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",wk=/^(?:(?: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])$/,vk=/^(?:(?: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])$/,xk=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,$k=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,kk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Sk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mm="((\\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])))",Tk=new RegExp(`^${mm}$`);$r=class t extends oe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==q.string){let s=this._getOrReturnCtx(e);return U(s,{code:z.invalid_type,expected:q.string,received:s.parsedType}),Y}let n=new Ye,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),U(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),U(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?U(o,{code:z.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&U(o,{code:z.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")bk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"email",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Dc||(Dc=new RegExp(_k,"u")),Dc.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"emoji",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")hk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"uuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")mk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"nanoid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")dk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"cuid",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")pk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"cuid2",code:z.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")fk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(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),U(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),U(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),U(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),U(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),U(o,{code:z.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?ym(s).test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{code:z.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Tk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{code:z.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Ek(s).test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{code:z.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?yk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"duration",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Rk(e.data,s.version)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"ip",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Pk(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"jwt",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Ak(e.data,s.version)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"cidr",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?kk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"base64",code:z.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Sk.test(e.data)||(o=this._getOrReturnCtx(e,o),U(o,{validation:"base64url",code:z.invalid_string,message:s.message}),n.dirty()):ue.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,...V.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...V.errToObj(e)})}url(e){return this._addCheck({kind:"url",...V.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...V.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...V.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...V.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...V.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...V.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...V.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...V.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...V.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...V.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...V.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,...V.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,...V.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...V.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...V.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...V.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...V.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...V.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...V.errToObj(r)})}nonempty(e){return this.min(1,V.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}};$r.create=t=>new $r({checks:[],typeName:N.ZodString,coerce:t?.coerce??!1,...re(t)});Jr=class t extends oe{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)!==q.number){let s=this._getOrReturnCtx(e);return U(s,{code:z.invalid_type,expected:q.number,received:s.parsedType}),Y}let n,o=new Ye;for(let s of this._def.checks)s.kind==="int"?ue.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),U(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),U(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),U(n,{code:z.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Ik(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),U(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),U(n,{code:z.not_finite,message:s.message}),o.dirty()):ue.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:V.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:V.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:V.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.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"&&ue.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)}};Jr.create=t=>new Jr({checks:[],typeName:N.ZodNumber,coerce:t?.coerce||!1,...re(t)});Yr=class t extends oe{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)!==q.bigint)return this._getInvalidInput(e);let n,o=new Ye;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),U(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),U(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),U(n,{code:z.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ue.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return U(r,{code:z.invalid_type,expected:q.bigint,received:r.parsedType}),Y}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:V.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:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.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}};Yr.create=t=>new Yr({checks:[],typeName:N.ZodBigInt,coerce:t?.coerce??!1,...re(t)});Xr=class extends oe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==q.boolean){let n=this._getOrReturnCtx(e);return U(n,{code:z.invalid_type,expected:q.boolean,received:n.parsedType}),Y}return nt(e.data)}};Xr.create=t=>new Xr({typeName:N.ZodBoolean,coerce:t?.coerce||!1,...re(t)});Qr=class t extends oe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==q.date){let s=this._getOrReturnCtx(e);return U(s,{code:z.invalid_type,expected:q.date,received:s.parsedType}),Y}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return U(s,{code:z.invalid_date}),Y}let n=new Ye,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),U(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),U(o,{code:z.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ue.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:V.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:V.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}};Qr.create=t=>new Qr({checks:[],coerce:t?.coerce||!1,typeName:N.ZodDate,...re(t)});Ln=class extends oe{_parse(e){if(this._getType(e)!==q.symbol){let n=this._getOrReturnCtx(e);return U(n,{code:z.invalid_type,expected:q.symbol,received:n.parsedType}),Y}return nt(e.data)}};Ln.create=t=>new Ln({typeName:N.ZodSymbol,...re(t)});en=class extends oe{_parse(e){if(this._getType(e)!==q.undefined){let n=this._getOrReturnCtx(e);return U(n,{code:z.invalid_type,expected:q.undefined,received:n.parsedType}),Y}return nt(e.data)}};en.create=t=>new en({typeName:N.ZodUndefined,...re(t)});tn=class extends oe{_parse(e){if(this._getType(e)!==q.null){let n=this._getOrReturnCtx(e);return U(n,{code:z.invalid_type,expected:q.null,received:n.parsedType}),Y}return nt(e.data)}};tn.create=t=>new tn({typeName:N.ZodNull,...re(t)});kr=class extends oe{constructor(){super(...arguments),this._any=!0}_parse(e){return nt(e.data)}};kr.create=t=>new kr({typeName:N.ZodAny,...re(t)});fr=class extends oe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return nt(e.data)}};fr.create=t=>new fr({typeName:N.ZodUnknown,...re(t)});qt=class extends oe{_parse(e){let r=this._getOrReturnCtx(e);return U(r,{code:z.invalid_type,expected:q.never,received:r.parsedType}),Y}};qt.create=t=>new qt({typeName:N.ZodNever,...re(t)});Dn=class extends oe{_parse(e){if(this._getType(e)!==q.undefined){let n=this._getOrReturnCtx(e);return U(n,{code:z.invalid_type,expected:q.void,received:n.parsedType}),Y}return nt(e.data)}};Dn.create=t=>new Dn({typeName:N.ZodVoid,...re(t)});hr=class t extends oe{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==q.array)return U(r,{code:z.invalid_type,expected:q.array,received:r.parsedType}),Y;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(U(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&&(U(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&&(U(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 Rt(r,i,r.path,a)))).then(i=>Ye.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Rt(r,i,r.path,a)));return Ye.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:V.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:V.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:V.toString(r)}})}nonempty(e){return this.min(1,e)}};hr.create=(t,e)=>new hr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...re(e)});ht=class t extends oe{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=ue.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==q.object){let u=this._getOrReturnCtx(e);return U(u,{code:z.invalid_type,expected:q.object,received:u.parsedType}),Y}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof qt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let d=s[u],l=o.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new Rt(o,l,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof qt){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(u==="strict")a.length>0&&(U(o,{code:z.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=o.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new Rt(o,l,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,f=await d.value;u.push({key:l,value:f,alwaysSet:d.alwaysSet})}return u}).then(u=>Ye.mergeObjectSync(n,u)):Ye.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return V.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:V.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:N.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 ue.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 ue.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Mn(this)}partial(e){let r={};for(let n of ue.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 ue.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ft;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return bm(ue.objectKeys(this.shape))}};ht.create=(t,e)=>new ht({shape:()=>t,unknownKeys:"strip",catchall:qt.create(),typeName:N.ZodObject,...re(e)});ht.strictCreate=(t,e)=>new ht({shape:()=>t,unknownKeys:"strict",catchall:qt.create(),typeName:N.ZodObject,...re(e)});ht.lazycreate=(t,e)=>new ht({shape:t,unknownKeys:"strip",catchall:qt.create(),typeName:N.ZodObject,...re(e)});rn=class extends oe{_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 pt(a.ctx.common.issues));return U(r,{code:z.invalid_union,unionErrors:i}),Y}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 u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!s&&(s={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new pt(c));return U(r,{code:z.invalid_union,unionErrors:a}),Y}}get options(){return this._def.options}};rn.create=(t,e)=>new rn({options:t,typeName:N.ZodUnion,...re(e)});pr=t=>t instanceof on?pr(t.schema):t instanceof Pt?pr(t.innerType()):t instanceof sn?[t.value]:t instanceof an?t.options:t instanceof cn?ue.objectValues(t.enum):t instanceof un?pr(t._def.innerType):t instanceof en?[void 0]:t instanceof tn?[null]:t instanceof ft?[void 0,...pr(t.unwrap())]:t instanceof Qt?[null,...pr(t.unwrap())]:t instanceof zo||t instanceof dn?pr(t.unwrap()):t instanceof ln?pr(t._def.innerType):[],ui=class t extends oe{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.object)return U(r,{code:z.invalid_type,expected:q.object,received:r.parsedType}),Y;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}):(U(r,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Y)}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=pr(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:N.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...re(n)})}};nn=class extends oe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(ai(s)||ai(i))return Y;let a=Zc(s.value,i.value);return a.valid?((ci(s)||ci(i))&&r.dirty(),{status:r.value,value:a.data}):(U(n,{code:z.invalid_intersection_types}),Y)};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}))}};nn.create=(t,e,r)=>new nn({left:t,right:e,typeName:N.ZodIntersection,...re(r)});Xt=class t extends oe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.array)return U(n,{code:z.invalid_type,expected:q.array,received:n.parsedType}),Y;if(n.data.length<this._def.items.length)return U(n,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y;!this._def.rest&&n.data.length>this._def.items.length&&(U(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 Rt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ye.mergeArray(r,i)):Ye.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Xt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xt({items:t,typeName:N.ZodTuple,rest:null,...re(e)})};li=class t extends oe{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!==q.object)return U(n,{code:z.invalid_type,expected:q.object,received:n.parsedType}),Y;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Rt(n,a,n.path,a)),value:i._parse(new Rt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ye.mergeObjectAsync(r,o):Ye.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof oe?new t({keyType:e,valueType:r,typeName:N.ZodRecord,...re(n)}):new t({keyType:$r.create(),valueType:e,typeName:N.ZodRecord,...re(r)})}},Zn=class extends oe{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!==q.map)return U(n,{code:z.invalid_type,expected:q.map,received:n.parsedType}),Y;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Rt(n,a,n.path,[u,"key"])),value:s._parse(new Rt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return Y;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return Y;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Zn.create=(t,e,r)=>new Zn({valueType:e,keyType:t,typeName:N.ZodMap,...re(r)});Un=class t extends oe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==q.set)return U(n,{code:z.invalid_type,expected:q.set,received:n.parsedType}),Y;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(U(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&&(U(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 u=new Set;for(let d of c){if(d.status==="aborted")return Y;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Rt(n,c,n.path,u)));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:V.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:V.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Un.create=(t,e)=>new Un({valueType:t,minSize:null,maxSize:null,typeName:N.ZodSet,...re(e)});di=class t extends oe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.function)return U(r,{code:z.invalid_type,expected:q.function,received:r.parsedType}),Y;function n(a,c){return Co({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Nn(),dr].filter(u=>!!u),issueData:{code:z.invalid_arguments,argumentsError:c}})}function o(a,c){return Co({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Nn(),dr].filter(u=>!!u),issueData:{code:z.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Sr){let a=this;return nt(async function(...c){let u=new pt([]),d=await a._def.args.parseAsync(c,s).catch(h=>{throw u.addIssue(n(c,h)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,s).catch(h=>{throw u.addIssue(o(l,h)),u})})}else{let a=this;return nt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new pt([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,s);if(!l.success)throw new pt([o(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Xt.create(e).rest(fr.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||Xt.create([]).rest(fr.create()),returns:r||fr.create(),typeName:N.ZodFunction,...re(n)})}},on=class extends oe{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})}};on.create=(t,e)=>new on({getter:t,typeName:N.ZodLazy,...re(e)});sn=class extends oe{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return U(r,{received:r.data,code:z.invalid_literal,expected:this._def.value}),Y}return{status:"valid",value:e.data}}get value(){return this._def.value}};sn.create=(t,e)=>new sn({value:t,typeName:N.ZodLiteral,...re(e)});an=class t extends oe{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return U(r,{expected:ue.joinValues(n),received:r.parsedType,code:z.invalid_type}),Y}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 U(r,{received:r.data,code:z.invalid_enum_value,options:n}),Y}return nt(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})}};an.create=bm;cn=class extends oe{_parse(e){let r=ue.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==q.string&&n.parsedType!==q.number){let o=ue.objectValues(r);return U(n,{expected:ue.joinValues(o),received:n.parsedType,code:z.invalid_type}),Y}if(this._cache||(this._cache=new Set(ue.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ue.objectValues(r);return U(n,{received:n.data,code:z.invalid_enum_value,options:o}),Y}return nt(e.data)}get enum(){return this._def.values}};cn.create=(t,e)=>new cn({values:t,typeName:N.ZodNativeEnum,...re(e)});Sr=class extends oe{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==q.promise&&r.common.async===!1)return U(r,{code:z.invalid_type,expected:q.promise,received:r.parsedType}),Y;let n=r.parsedType===q.promise?r.data:Promise.resolve(r.data);return nt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Sr.create=(t,e)=>new Sr({type:t,typeName:N.ZodPromise,...re(e)});Pt=class extends oe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.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=>{U(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 Y;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?Y:c.status==="dirty"?Gr(c.value):r.value==="dirty"?Gr(c.value):c});{if(r.value==="aborted")return Y;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?Y:a.status==="dirty"?Gr(a.value):r.value==="dirty"?Gr(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"?Y:(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"?Y:(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(!xr(i))return Y;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=>xr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):Y);ue.assertNever(o)}};Pt.create=(t,e,r)=>new Pt({schema:t,typeName:N.ZodEffects,effect:e,...re(r)});Pt.createWithPreprocess=(t,e,r)=>new Pt({schema:e,effect:{type:"preprocess",transform:t},typeName:N.ZodEffects,...re(r)});ft=class extends oe{_parse(e){return this._getType(e)===q.undefined?nt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ft.create=(t,e)=>new ft({innerType:t,typeName:N.ZodOptional,...re(e)});Qt=class extends oe{_parse(e){return this._getType(e)===q.null?nt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Qt.create=(t,e)=>new Qt({innerType:t,typeName:N.ZodNullable,...re(e)});un=class extends oe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===q.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};un.create=(t,e)=>new un({innerType:t,typeName:N.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});ln=class extends oe{_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 jn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new pt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new pt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ln.create=(t,e)=>new ln({innerType:t,typeName:N.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});qn=class extends oe{_parse(e){if(this._getType(e)!==q.nan){let n=this._getOrReturnCtx(e);return U(n,{code:z.invalid_type,expected:q.nan,received:n.parsedType}),Y}return{status:"valid",value:e.data}}};qn.create=t=>new qn({typeName:N.ZodNaN,...re(t)});Ok=Symbol("zod_brand"),zo=class extends oe{_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}},No=class t extends oe{_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"?Y:s.status==="dirty"?(r.dirty(),Gr(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"?Y: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:N.ZodPipeline})}},dn=class extends oe{_parse(e){let r=this._def.innerType._parse(e),n=o=>(xr(o)&&(o.value=Object.freeze(o.value)),o);return jn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};dn.create=(t,e)=>new dn({innerType:t,typeName:N.ZodReadonly,...re(e)});Ck={object:ht.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"})(N||(N={}));zk=(t,e={message:`Input not instance of ${t.name}`})=>_m(r=>r instanceof t,e),wm=$r.create,vm=Jr.create,Nk=qn.create,jk=Yr.create,xm=Xr.create,Mk=Qr.create,Lk=Ln.create,Dk=en.create,Zk=tn.create,Uk=kr.create,qk=fr.create,Fk=qt.create,Bk=Dn.create,Vk=hr.create,Uc=ht.create,Hk=ht.strictCreate,Kk=rn.create,Wk=ui.create,Gk=nn.create,Jk=Xt.create,Yk=li.create,Xk=Zn.create,Qk=Un.create,eS=di.create,tS=on.create,rS=sn.create,nS=an.create,oS=cn.create,sS=Sr.create,iS=Pt.create,aS=ft.create,cS=Qt.create,uS=Pt.createWithPreprocess,lS=No.create,dS=()=>wm().optional(),pS=()=>vm().optional(),fS=()=>xm().optional(),hS={string:(t=>$r.create({...t,coerce:!0})),number:(t=>Jr.create({...t,coerce:!0})),boolean:(t=>Xr.create({...t,coerce:!0})),bigint:(t=>Yr.create({...t,coerce:!0})),date:(t=>Qr.create({...t,coerce:!0}))},mS=Y});var j={};Po(j,{BRAND:()=>Ok,DIRTY:()=>Gr,EMPTY_PATH:()=>lk,INVALID:()=>Y,NEVER:()=>mS,OK:()=>nt,ParseStatus:()=>Ye,Schema:()=>oe,ZodAny:()=>kr,ZodArray:()=>hr,ZodBigInt:()=>Yr,ZodBoolean:()=>Xr,ZodBranded:()=>zo,ZodCatch:()=>ln,ZodDate:()=>Qr,ZodDefault:()=>un,ZodDiscriminatedUnion:()=>ui,ZodEffects:()=>Pt,ZodEnum:()=>an,ZodError:()=>pt,ZodFirstPartyTypeKind:()=>N,ZodFunction:()=>di,ZodIntersection:()=>nn,ZodIssueCode:()=>z,ZodLazy:()=>on,ZodLiteral:()=>sn,ZodMap:()=>Zn,ZodNaN:()=>qn,ZodNativeEnum:()=>cn,ZodNever:()=>qt,ZodNull:()=>tn,ZodNullable:()=>Qt,ZodNumber:()=>Jr,ZodObject:()=>ht,ZodOptional:()=>ft,ZodParsedType:()=>q,ZodPipeline:()=>No,ZodPromise:()=>Sr,ZodReadonly:()=>dn,ZodRecord:()=>li,ZodSchema:()=>oe,ZodSet:()=>Un,ZodString:()=>$r,ZodSymbol:()=>Ln,ZodTransformer:()=>Pt,ZodTuple:()=>Xt,ZodType:()=>oe,ZodUndefined:()=>en,ZodUnion:()=>rn,ZodUnknown:()=>fr,ZodVoid:()=>Dn,addIssueToContext:()=>U,any:()=>Uk,array:()=>Vk,bigint:()=>jk,boolean:()=>xm,coerce:()=>hS,custom:()=>_m,date:()=>Mk,datetimeRegex:()=>ym,defaultErrorMap:()=>dr,discriminatedUnion:()=>Wk,effect:()=>iS,enum:()=>nS,function:()=>eS,getErrorMap:()=>Nn,getParsedType:()=>Yt,instanceof:()=>zk,intersection:()=>Gk,isAborted:()=>ai,isAsync:()=>jn,isDirty:()=>ci,isValid:()=>xr,late:()=>Ck,lazy:()=>tS,literal:()=>rS,makeIssue:()=>Co,map:()=>Xk,nan:()=>Nk,nativeEnum:()=>oS,never:()=>Fk,null:()=>Zk,nullable:()=>cS,number:()=>vm,object:()=>Uc,objectUtil:()=>jc,oboolean:()=>fS,onumber:()=>pS,optional:()=>aS,ostring:()=>dS,pipeline:()=>lS,preprocess:()=>uS,promise:()=>sS,quotelessJson:()=>ak,record:()=>Yk,set:()=>Qk,setErrorMap:()=>uk,strictObject:()=>Hk,string:()=>wm,symbol:()=>Lk,transformer:()=>iS,tuple:()=>Jk,undefined:()=>Dk,union:()=>Kk,unknown:()=>qk,util:()=>ue,void:()=>Bk});var pi=E(()=>{ii();Lc();dm();Oo();$m();si()});var Fn=E(()=>{pi();pi()});function fi(t){let e=qc.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Fc(t,e){let r=qc.safeParse(t);if(!r.success)throw new Tr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(km.test(e))throw new Tr('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(km.test(n))throw new Tr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Sm,Tm,qc,Tr,km,Em=E(()=>{Fn();Sm=j.object({type:j.literal("connection"),source_system:j.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:j.string().min(1).max(200).optional()}),Tm=j.discriminatedUnion("type",[Sm]),qc=j.object({inputs:j.array(Tm).optional()}).passthrough(),Tr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};km=/\bconnection[_-]?id\b["']?\s*[:=]/i});var hi,Bc=E(()=>{hi=["before_read","before_save","after_save","before_sync","after_sync","on_sync_failure"]});var Vc,Rm,Pm=E(()=>{Fn();oi();Bc();Vc=j.object({id:j.string().min(1,"hook id must be non-empty"),recordType:j.union([j.string().min(1),j.array(j.string().min(1)).min(1),j.literal("*")]),event:j.enum(hi),source:j.string().min(1).optional(),when:j.unknown().optional(),run:j.unknown(),failClosed:j.boolean().optional(),timeoutMs:j.number().int().positive().optional(),description:j.string().optional(),systemReserved:j.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"})}),Rm=Io({kind:"hook",schema:Vc,factoryName:"defineHook"})});var Am=E(()=>{Pm();Bc()});var mi,Hc=E(()=>{mi=["after_canonicalize_inbound","after_sync_success_outbound"]});var Kc,Im,Om=E(()=>{Fn();oi();Hc();Kc=j.object({id:j.string().min(1,"conduit id must be non-empty"),on:j.enum(mi),from:j.object({source:j.string().min(1,"from.source must be non-empty"),recordType:j.string().min(1,"from.recordType must be non-empty"),when:j.unknown().optional()}),to:j.object({source:j.string().min(1,"to.source must be non-empty"),recordType:j.string().min(1,"to.recordType must be non-empty")}),mode:j.enum(["dual-bind","one-shot"]).optional(),transform:j.unknown(),idempotencyKey:j.unknown().optional(),cycleBudget:j.number().int().positive().optional(),conflictStrategy:j.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:j.number().int().positive().optional(),description:j.string().optional(),systemReserved:j.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let r=t.from?.when;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let n=t.idempotencyKey;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let o=t.from,s=t.to;o?.source&&s?.source&&o.source===s.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"})}),Im=Io({kind:"conduit",schema:Kc,factoryName:"defineConduit"})});var Cm=E(()=>{Om();Hc()});async function wS(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??wS)(t)}var Wc=E(()=>{});function Gc(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 zm(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Jc(t){return`${zm(t.source)}${zm(t.recordType)}`}function vS(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function xS(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.description&&e.push(t.description),e.join(" \xB7 ")}function Yc(t){let e=Jc(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
|
+
* ${r.join(`
|
|
26
|
+
* `)}
|
|
27
|
+
*/`;if(t.columns.length===0)return`${n}
|
|
28
|
+
export interface ${e} {
|
|
29
|
+
// no columns introspected
|
|
30
|
+
[key: string]: unknown;
|
|
31
|
+
}`;let o=t.columns.map(s=>{let i=Gc(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${xS(s)} */
|
|
32
|
+
${vS(s.name)}${a}: ${i}${c};`});return`${n}
|
|
33
|
+
export interface ${e} {
|
|
34
|
+
${o.join(`
|
|
35
|
+
`)}
|
|
36
|
+
}`}function yi(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Yc).join(`
|
|
37
|
+
|
|
38
|
+
`)}var Xc=E(()=>{});function $S(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Nm(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 Er(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=$S(t.baseUrl),n=await Nm(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=yi(n),s=[kS,"// ----- Record shapes (from /v1/catalog/records) -----",o];if(!t.recordsOnly){let i=await Nm(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(`
|
|
39
|
+
|
|
40
|
+
`)+`
|
|
41
|
+
`}var kS,jm=E(()=>{Wc();Xc();Xc();Wc();kS=["/**"," * 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(`
|
|
42
|
+
`)});var Qc=E(()=>{oi();Em();Am();Cm();jm()});import{homedir as SS}from"node:os";import{join as Mm}from"node:path";import{promises as eu}from"node:fs";function At(t){return t.trim().replace(/\/+$/,"")}function Dm(){let t=process.env.TURBOBASE_HOME??Mm(SS(),".turbobase");return{dir:t,file:Mm(t,"credentials")}}function Lm(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function jo(){let{file:t}=Dm(),e;try{let s=await eu.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))Lm(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))Lm(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:TS(n),tenants:n}}function TS(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 tu(t){let{dir:e,file:r}=Dm();await eu.mkdir(e,{recursive:!0,mode:448}),await eu.writeFile(r,JSON.stringify(t,null,2)+`
|
|
43
|
+
`,{mode:384})}async function Zm(t){let e=At(t.baseUrl),r=await jo(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await tu(r),{baseUrl:e,token:t.token,updatedAt:n}}async function er(t){let e=await jo();if(t){let s=At(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 bi(t){let e=At(t),r=await jo(),n=r.tenants[e];return n?(r.active=e,await tu(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ru(t){let e=await jo(),r=t?At(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 tu(e),r}async function Rr(){let t=await jo();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var _i=E(()=>{});function Um(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim().slice(0,200):""}function qm(t){return t.replace(/\/+$/,"")}function nu(t=process.env){let e=(t[Bn]??"").trim(),r=(t[wi]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function ou(t){let e;try{e=new URL(t)}catch{return`${Bn} 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:`${Bn} 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 Ue,Re,Bn,wi,Mo,Lo=E(()=>{Ue=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};Re=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=qm(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=r}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){let c=Um(a);throw new Ue(`${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"})}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 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));let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}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}:{}})}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){return this.request("POST","/v1/config/apply",{bundle:e})}},Bn="TURBOBASE_REGISTRY_URL",wi="TURBOBASE_REGISTRY_TOKEN";Mo=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=qm(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=Um(a);throw new Ue(`${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}:{}})}}});function RS(t){if(ES.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function AS(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:RS(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||OS(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:PS,loader:"js"}))}}}function OS(t){let e=t.startsWith("node:")?t.slice(5):t;return IS.has(e.split("/")[0])}function Fm(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 CS(){try{return(await import("esbuild")).build}catch(t){throw Fm("esbuild",t)}}async function zS(){try{return(await import("isolated-vm")).default}catch(t){throw Fm("isolated-vm",t)}}async function vi(t){let e=await CS(),r;try{r=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[AS()]})}catch(n){let s=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new su(s||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function Do(t,e,r={}){let n=r.timeoutMs??200,o=r.memoryLimitMb??16,s=r.member??"run",i={patches:[],logs:[]},a=await zS(),c=new a.Isolate({memoryLimit:o});try{let u=await c.createContext(),d=u.global,l=new a.Callback(R=>{let C=JSON.parse(String(R));i.rejection||(i.rejection=C)}),f=new a.Callback(R=>{i.patches.push(JSON.parse(String(R)))}),h=new a.Callback(R=>{let C=JSON.parse(String(R));i.logs.push(C)}),p=new a.Callback(R=>{i.result=JSON.parse(String(R))});await d.set("__tb_reject",l),await d.set("__tb_patch",f),await d.set("__tb_log",h),await d.set("__tb_result",p),await d.set("__tb_ctx_json",JSON.stringify(NS(e)));let m=jS(t,s),S=await(await c.compileScript(m)).run(u,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!S}:{effects:i}}finally{c.isDisposed||c.dispose()}}function NS(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}}function jS(t,e){return`
|
|
44
|
+
"use strict";
|
|
45
|
+
(async () => {
|
|
46
|
+
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
47
|
+
// Rebuild the documented HookContext. reject/patch/log marshal their
|
|
48
|
+
// argument to JSON and call the bridged host callback. No other host
|
|
49
|
+
// surface is reachable.
|
|
50
|
+
//
|
|
51
|
+
// Conduit (#572): a conduit's ctx also carries read-only \`bindings\` +
|
|
52
|
+
// \`atlas.resolve\` + \`canonicalStatus\`. These are pure over the
|
|
53
|
+
// copied-in snapshot (no live host call) \u2014 bindings + a pre-resolved
|
|
54
|
+
// atlasLinks map. A hook never reads them, so the extra fields are inert
|
|
55
|
+
// for the hook path. \`atlas.resolve\` returns null on a miss (untrusted
|
|
56
|
+
// conduits get pre-resolved atlas only \u2014 the documented v1 limit).
|
|
57
|
+
const __tb_atlasLinks = __tb_ctx.atlasLinks || {};
|
|
58
|
+
const ctx = {
|
|
59
|
+
recordType: __tb_ctx.recordType,
|
|
60
|
+
event: __tb_ctx.event,
|
|
61
|
+
direction: __tb_ctx.direction,
|
|
62
|
+
origin: __tb_ctx.origin,
|
|
63
|
+
source: __tb_ctx.source,
|
|
64
|
+
// A conduit authors against \`ctx.fromSource\`; \`ctx.source\` carries the
|
|
65
|
+
// same value, so expose both off the one serialized field.
|
|
66
|
+
fromSource: __tb_ctx.source,
|
|
67
|
+
externalId: __tb_ctx.metadata && __tb_ctx.metadata.externalId,
|
|
68
|
+
payload: __tb_ctx.payload,
|
|
69
|
+
prior: __tb_ctx.prior == null ? undefined : __tb_ctx.prior,
|
|
70
|
+
user: __tb_ctx.user == null ? undefined : __tb_ctx.user,
|
|
71
|
+
tenantConfig: __tb_ctx.tenantConfig,
|
|
72
|
+
metadata: __tb_ctx.metadata == null ? undefined : __tb_ctx.metadata,
|
|
73
|
+
lines: (__tb_ctx.metadata && __tb_ctx.metadata.lines) || [],
|
|
74
|
+
bindings: __tb_ctx.bindings || [],
|
|
75
|
+
atlas: {
|
|
76
|
+
resolve(args) {
|
|
77
|
+
const k = (args.entityType || '') + '|' + (args.targetSource || '') + '|' + (args.sourceExternalId || '');
|
|
78
|
+
return Object.prototype.hasOwnProperty.call(__tb_atlasLinks, k) ? __tb_atlasLinks[k] : null;
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
canonicalStatus(args) {
|
|
82
|
+
return String((args && args.raw) || '').trim().toLowerCase();
|
|
83
|
+
},
|
|
84
|
+
reject(envelope) { __tb_reject(JSON.stringify(envelope)); },
|
|
85
|
+
patch(updates) { __tb_patch(JSON.stringify(updates)); },
|
|
86
|
+
log(level, message, meta) {
|
|
87
|
+
__tb_log(JSON.stringify({ level, message, meta }));
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// ---- bundled extension module (IIFE assigns __tb_extension_module) ----
|
|
92
|
+
${t}
|
|
93
|
+
|
|
94
|
+
const def = (typeof __tb_extension_module !== 'undefined' && __tb_extension_module)
|
|
95
|
+
? __tb_extension_module.default
|
|
96
|
+
: undefined;
|
|
97
|
+
if (!def || typeof def !== 'object') {
|
|
98
|
+
throw new Error('extension bundle has no default export (use export default defineHook({...}))');
|
|
99
|
+
}
|
|
100
|
+
// 'when' resolves the kind's gate: a hook's is top-level \`def.when\`; a
|
|
101
|
+
// conduit's is the nested \`def.from.when\` (#572). A conduit has no
|
|
102
|
+
// top-level \`when\` (and a hook has no \`from\`), so the \`??\` picks the
|
|
103
|
+
// right one without a kind discriminator. 'run'/'transform' are the body.
|
|
104
|
+
const fn = ${e==="when"?"(def.when || (def.from && def.from.when))":`def[${JSON.stringify(e)}]`};
|
|
105
|
+
if (typeof fn !== 'function') {
|
|
106
|
+
${e==="when"?"return true;":e==="transform"?"throw new Error('conduit default export has no transform() function');":"throw new Error('extension default export has no run() function');"}
|
|
107
|
+
}
|
|
108
|
+
const out = await fn(ctx);
|
|
109
|
+
${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
|
|
110
|
+
return ${e==="when"?"out":"undefined"};
|
|
111
|
+
})()
|
|
112
|
+
`}var ES,PS,su,IS,iu=E(()=>{ES=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);PS=`
|
|
113
|
+
export const defineHook = (def) => def;
|
|
114
|
+
export const defineConduit = (def) => def;
|
|
115
|
+
export default defineHook;
|
|
116
|
+
`,su=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};IS=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 au}from"node:fs";import{join as MS}from"node:path";function LS(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 DS(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await Do(t,LS(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 xi(t,e){let r=await vi(t),n=[];for(let o=0;o<e.length;o+=1)n.push(await DS(r,e[o],`sample[${o}]`));return n}async function Zo(t){let e;try{e=await au.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 au.readFile(MS(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 Uo(t){return au.readFile(t,"utf8")}var cu=E(()=>{iu()});function Ir(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function g0(t){let e=t.recordType;if(!e)throw new Ct("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
|
|
117
|
+
source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
|
|
118
|
+
run: (ctx) => {
|
|
119
|
+
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
120
|
+
// with ctx.patch({...}); observe with ctx.log('info', '...').
|
|
121
|
+
},`,a="custom";else if(n==="require-field"){let f=t.field;if(!f)throw new Ct("require-field template needs --field=<name>");i=`
|
|
122
|
+
run: (ctx) => {
|
|
123
|
+
const v = ctx.payload[${JSON.stringify(f)}];
|
|
124
|
+
if (v === undefined || v === null || v === '') {
|
|
125
|
+
ctx.reject({
|
|
126
|
+
code: 'MANDATORY_FIELD_MISSING',
|
|
127
|
+
field: ${JSON.stringify(f)},
|
|
128
|
+
message: ${JSON.stringify(`${f} is required`)},
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
},`,a=`require-field-${f}`}else if(n==="enforce-format"){let f=t.field;if(!f)throw new Ct("enforce-format template needs --field=<name>");if(!t.regex)throw new Ct("enforce-format template needs --regex=<pattern>");i=`
|
|
132
|
+
run: (ctx) => {
|
|
133
|
+
const v = ctx.payload[${JSON.stringify(f)}];
|
|
134
|
+
if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
|
|
135
|
+
ctx.reject({
|
|
136
|
+
code: 'INVALID_FORMAT',
|
|
137
|
+
field: ${JSON.stringify(f)},
|
|
138
|
+
message: ${JSON.stringify(`${f} does not match expected format`)},
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
},`,a=`enforce-format-${f}`}else throw new Ct(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${Ir(t.regex).slice(0,24)}`:""}`,d=`/**
|
|
142
|
+
* ${t.description??`${a} on ${e}.${r}`}
|
|
143
|
+
*
|
|
144
|
+
* Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
|
|
145
|
+
* \`turbobase ext deploy\`.
|
|
146
|
+
*/
|
|
147
|
+
import { defineHook } from '@turbobase/extensions';
|
|
148
|
+
|
|
149
|
+
export default defineHook<Record<string, unknown>>({
|
|
150
|
+
id: ${JSON.stringify(c)},
|
|
151
|
+
recordType: ${JSON.stringify(e)},
|
|
152
|
+
event: ${JSON.stringify(r)},${s}${i}
|
|
153
|
+
});
|
|
154
|
+
`;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:d}}function y0(t){let e=t.recordType;if(!e)throw new Ct("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Ct("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Ct("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Ct(`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??`${Ir(r)}2${Ir(n)}:${Ir(e)}`,c=`/**
|
|
155
|
+
* ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
|
|
156
|
+
*
|
|
157
|
+
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
158
|
+
* transform: read ctx, RETURN a { patch, createdFrom } \u2014 never call a source API
|
|
159
|
+
* and never hold credentials. The engine writes the canonical master row and the
|
|
160
|
+
* writeback worker fans it out to the target. Keep this file self-contained:
|
|
161
|
+
* inline any shared mapping logic; the ONLY allowed import is the SDK factory.
|
|
162
|
+
*
|
|
163
|
+
* Edit freely, then \`turbobase ext test\` and \`turbobase ext deploy\`.
|
|
164
|
+
*/
|
|
165
|
+
import { defineConduit } from '@turbobase/extensions';
|
|
166
|
+
|
|
167
|
+
export default defineConduit<Record<string, unknown>>({
|
|
168
|
+
id: ${JSON.stringify(i)},
|
|
169
|
+
on: ${JSON.stringify(s)},
|
|
170
|
+
from: {
|
|
171
|
+
source: ${JSON.stringify(r)},
|
|
172
|
+
recordType: ${JSON.stringify(e)},
|
|
173
|
+
// when: (ctx) => true, // optional gate on the inbound payload
|
|
174
|
+
},
|
|
175
|
+
to: {
|
|
176
|
+
source: ${JSON.stringify(n)},
|
|
177
|
+
recordType: ${JSON.stringify(o)},
|
|
178
|
+
},
|
|
179
|
+
mode: 'dual-bind',
|
|
180
|
+
conflictStrategy: 'merge',
|
|
181
|
+
cycleBudget: 4,
|
|
182
|
+
transform: async (ctx) => {
|
|
183
|
+
// Map ctx.payload / ctx.lines into the target's canonical shape here.
|
|
184
|
+
return {
|
|
185
|
+
patch: {
|
|
186
|
+
// ...mapped canonical fields...
|
|
187
|
+
},
|
|
188
|
+
createdFrom: {
|
|
189
|
+
source: ${JSON.stringify(r)},
|
|
190
|
+
recordType: ${JSON.stringify(e)},
|
|
191
|
+
externalId: ctx.externalId,
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
},
|
|
195
|
+
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
196
|
+
});
|
|
197
|
+
`;return{relativePath:`conduits/${Ir(r)}-${Ir(e)}-to-${Ir(n)}-${Ir(o)}.ts`,content:c}}function Hn(t,e){let r=b0[t];if(!r)throw new Ct(`unknown extension kind '${t}'. Scaffoldable kinds: ${fg.join(", ")}.`);return r(e)}var fg,Ct,b0,mu=E(()=>{fg=["hook","conduit"];Ct=class extends Error{};b0={hook:g0,conduit:y0}});function AT(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 IT(t){return qg[AT(t)%qg.length]}function OT(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 Fg(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Bg(t,e){let[r,n]=IT(t),o=Fg(OT(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Fg(e)}">
|
|
198
|
+
<defs>
|
|
199
|
+
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
200
|
+
<stop offset="0" stop-color="${r}"/>
|
|
201
|
+
<stop offset="1" stop-color="${n}"/>
|
|
202
|
+
</linearGradient>
|
|
203
|
+
</defs>
|
|
204
|
+
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
205
|
+
<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>
|
|
206
|
+
</svg>
|
|
207
|
+
`}var qg,Vg=E(()=>{qg=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Hg,Kg=E(()=>{Hg=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var ty={};Po(ty,{MAIN_TSX:()=>Qg,STYLES_CSS:()=>ey,TSCONFIG:()=>Yg,TURBOBASE_CLIENT:()=>Wg,indexHtml:()=>Xg,instanceOriginFromEnv:()=>LT,packageJson:()=>Gg,scaffoldAppFiles:()=>ZT,starterApp:()=>UT,viteConfig:()=>Jg});function zT(t){let e={name:t.title},r=(t.description??"").trim().slice(0,CT);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Hg},JSON.stringify(e,null,2)+`
|
|
208
|
+
`}function Gg(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview"},dependencies:{react:"^18.3.1","react-dom":"^18.3.1"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
|
|
209
|
+
`}function MT(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 LT(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Jg(t,e={}){let r=MT(e.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
210
|
+
import react from '@vitejs/plugin-react';
|
|
211
|
+
|
|
212
|
+
// A same-origin static SPA served at /a/${t}. \`base\` MUST match that mount
|
|
213
|
+
// path \u2014 assets are requested absolutely, so a wrong base 404s every chunk and
|
|
214
|
+
// renders a blank page.
|
|
215
|
+
//
|
|
216
|
+
// DEV ONLY, below: the dev server is its own origin, so the instance's session
|
|
217
|
+
// cookie is not same-origin with it. Proxying every instance path the client
|
|
218
|
+
// touches makes http://localhost:3000 behave exactly like /a/${t} does in
|
|
219
|
+
// production \u2014 an unauthenticated load is forwarded to the instance's /login,
|
|
220
|
+
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
221
|
+
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
222
|
+
// them at boot; restart the dev server after changing one).
|
|
223
|
+
const TENANT = process.env.SUPABASE_URL || '${r??NT}'; // /rest + the Realtime WS
|
|
224
|
+
const API = process.env.TURBOBASE_API_URL || '${r??jT}'; // /v1, /auth, /login, /_app
|
|
225
|
+
|
|
226
|
+
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
227
|
+
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
228
|
+
// page URL \u2014 that is what lets the same bytes serve at /a/${t}/ and at a
|
|
229
|
+
// preview URL, and be promoted from one to the other without a rebuild.
|
|
230
|
+
// Unset (a hand-run \`npm run build\`) falls back to the production mount path.
|
|
231
|
+
const ASSET_BASE = process.env.TURBOBASE_ASSET_BASE || '/a/${t}/';
|
|
232
|
+
|
|
233
|
+
export default defineConfig({
|
|
234
|
+
base: ASSET_BASE,
|
|
235
|
+
plugins: [react()],
|
|
236
|
+
server: {
|
|
237
|
+
port: 3000,
|
|
238
|
+
proxy: {
|
|
239
|
+
'/rest': { target: TENANT, changeOrigin: true },
|
|
240
|
+
'/realtime': { target: TENANT, changeOrigin: true, ws: true },
|
|
241
|
+
'/v1': { target: API, changeOrigin: true },
|
|
242
|
+
'/auth': { target: API, changeOrigin: true },
|
|
243
|
+
'/login': { target: API, changeOrigin: true },
|
|
244
|
+
// The sign-in page is the instance's own SvelteKit app, and it loads its
|
|
245
|
+
// JS + CSS from /_app/immutable/*. Without this entry those 404 through
|
|
246
|
+
// the proxy: the login HTML arrives, never hydrates, and the form is
|
|
247
|
+
// inert with NOTHING in the console. The app then loads unauthenticated
|
|
248
|
+
// and PostgREST answers as the anonymous role \u2014 which surfaces as
|
|
249
|
+
// "permission denied for table <x>" and reads like an RLS problem rather
|
|
250
|
+
// than "you were never signed in". Do not remove this line.
|
|
251
|
+
'/_app': { target: API, changeOrigin: true },
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
build: { outDir: 'dist' },
|
|
255
|
+
});
|
|
256
|
+
`}function Xg(t){return`<!doctype html>
|
|
257
|
+
<html lang="en">
|
|
258
|
+
<head>
|
|
259
|
+
<meta charset="UTF-8" />
|
|
260
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
261
|
+
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
|
|
262
|
+
<title>${t}</title>
|
|
263
|
+
</head>
|
|
264
|
+
<body>
|
|
265
|
+
<div id="root"></div>
|
|
266
|
+
<script type="module" src="/src/main.tsx"></script>
|
|
267
|
+
</body>
|
|
268
|
+
</html>
|
|
269
|
+
`}function ZT(t){return{"package.json":Gg(t.slug),"vite.config.ts":Jg(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":DT,"tsconfig.json":Yg,"index.html":Xg(t.title),"public/turbobase.json":zT(t),"public/favicon.svg":Bg(t.slug,t.title),"src/main.tsx":Qg,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Wg,"src/styles.css":ey,"README.md":`# ${t.title}
|
|
270
|
+
|
|
271
|
+
\`\`\`sh
|
|
272
|
+
npm install
|
|
273
|
+
npm run dev # http://localhost:3000/a/${t.slug}/ (NOT /, Vite serves under \`base\`)
|
|
274
|
+
|
|
275
|
+
turbobase apps push ${t.slug} . # store the source on your instance
|
|
276
|
+
turbobase apps deploy ${t.slug} # build + go live at /a/${t.slug}
|
|
277
|
+
\`\`\`
|
|
278
|
+
|
|
279
|
+
The dev server proxies \`/rest\`, \`/realtime\`, \`/v1\`, \`/auth\`, \`/login\` and \`/_app\`
|
|
280
|
+
to your instance so localhost behaves same-origin \u2014 sign in on first load and the
|
|
281
|
+
session cookie applies exactly as it will in production. Point it elsewhere with
|
|
282
|
+
\`SUPABASE_URL\` / \`TURBOBASE_API_URL\` (Vite reads them at boot; restart after).
|
|
283
|
+
|
|
284
|
+
\`/_app\` is not optional: the sign-in page loads its JS/CSS from there, and
|
|
285
|
+
without it the login form renders but never hydrates \u2014 you stay signed out and
|
|
286
|
+
every read comes back "permission denied", which looks like an RLS problem.
|
|
287
|
+
|
|
288
|
+
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
289
|
+
live access token and is gitignored \u2014 keep it that way.
|
|
290
|
+
`}}function UT(t){return`import React from 'react';
|
|
291
|
+
import { select } from './lib/turbobase';
|
|
292
|
+
|
|
293
|
+
/** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has. */
|
|
294
|
+
const RECORD_TYPE = 'customer';
|
|
295
|
+
|
|
296
|
+
export default function App() {
|
|
297
|
+
const [rows, setRows] = React.useState<Record<string, unknown>[]>([]);
|
|
298
|
+
const [error, setError] = React.useState<string | null>(null);
|
|
299
|
+
|
|
300
|
+
React.useEffect(() => {
|
|
301
|
+
// Reads are RLS-scoped to the signed-in user \u2014 no key, no token handling.
|
|
302
|
+
select<Record<string, unknown>>(\`\${RECORD_TYPE}?select=*&limit=25\`)
|
|
303
|
+
.then(setRows)
|
|
304
|
+
.catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
|
|
305
|
+
}, []);
|
|
306
|
+
|
|
307
|
+
return (
|
|
308
|
+
<main style={{ padding: 24 }}>
|
|
309
|
+
<h1>${t}</h1>
|
|
310
|
+
{error && <p style={{ color: 'crimson' }}>{error}</p>}
|
|
311
|
+
<p>{rows.length} {RECORD_TYPE} row(s), scoped to you.</p>
|
|
312
|
+
<pre>{JSON.stringify(rows.slice(0, 3), null, 2)}</pre>
|
|
313
|
+
</main>
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
`}var CT,Wg,NT,jT,DT,Yg,Qg,ey,ry=E(()=>{Vg();Kg();CT=200;Wg=`// Same-origin TurboBase client \u2014 the one file you copy (build-apps/auth).
|
|
317
|
+
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
318
|
+
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
319
|
+
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
320
|
+
// The signed-in session cookie is the only credential \u2014 no app-owned keys.
|
|
321
|
+
|
|
322
|
+
const jwt = (): string =>
|
|
323
|
+
document.cookie.split('; ').find((c) => c.startsWith('tb_jwt='))?.slice('tb_jwt='.length) ?? '';
|
|
324
|
+
|
|
325
|
+
async function req(path: string, init: RequestInit = {}): Promise<Response> {
|
|
326
|
+
const headers = new Headers(init.headers);
|
|
327
|
+
const token = jwt();
|
|
328
|
+
// supabase-js convention: the JWT rides in the apikey position for PostgREST.
|
|
329
|
+
if (token) {
|
|
330
|
+
headers.set('apikey', token);
|
|
331
|
+
headers.set('Authorization', \`Bearer \${token}\`);
|
|
332
|
+
}
|
|
333
|
+
return fetch(path, { ...init, headers, credentials: 'same-origin' });
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** PostgREST's server-side row cap (supabase config \`max_rows\`). A read with no
|
|
337
|
+
* explicit \`limit\` is silently truncated at this many rows \u2014 see select(). */
|
|
338
|
+
const SERVER_MAX_ROWS = 1000;
|
|
339
|
+
/** selectPage() defaults: page 100 rows at a time, never probe for more than the
|
|
340
|
+
* server would return in one shot anyway. */
|
|
341
|
+
const DEFAULT_PAGE_SIZE = 100;
|
|
342
|
+
const MAX_PAGE_SIZE = 1000;
|
|
343
|
+
|
|
344
|
+
/** Thrown (by name) when a read is silently capped by the server row limit \u2014 or,
|
|
345
|
+
* when \`embedAlias\` is given, when an EMBEDDED result came back short. select()
|
|
346
|
+
* WARNS with this message by default so existing callers keep working; throw it
|
|
347
|
+
* yourself if you'd rather fail hard than page. */
|
|
348
|
+
export class TurbobaseTruncationError extends Error {
|
|
349
|
+
constructor(
|
|
350
|
+
readonly pathAndQuery: string,
|
|
351
|
+
readonly cap: number,
|
|
352
|
+
readonly embedAlias?: string,
|
|
353
|
+
) {
|
|
354
|
+
super(
|
|
355
|
+
embedAlias
|
|
356
|
+
? \`select("\${pathAndQuery}") embedded "\${embedAlias}" hit a server-side bound \u2014 \` +
|
|
357
|
+
\`some related rows were dropped. Narrow the parent page (selectPage with a \` +
|
|
358
|
+
\`smaller pageSize) or filter the parent so fewer related rows are pulled.\`
|
|
359
|
+
: \`select("\${pathAndQuery}") returned exactly \${cap} rows \u2014 the PostgREST row cap. \` +
|
|
360
|
+
\`Rows beyond the first \${cap} were dropped. Page the full result set with \` +
|
|
361
|
+
\`selectPage("\${pathAndQuery}", { pageSize }) instead.\`,
|
|
362
|
+
);
|
|
363
|
+
this.name = 'TurbobaseTruncationError';
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Thrown when a keyset cursor is malformed, or is replayed against a different
|
|
368
|
+
* table / query than the one that minted it. */
|
|
369
|
+
export class TurbobaseCursorError extends Error {
|
|
370
|
+
constructor(message: string) {
|
|
371
|
+
super(message);
|
|
372
|
+
this.name = 'TurbobaseCursorError';
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Does this path already carry an explicit \`limit=\`? Such a caller opted into a
|
|
377
|
+
* bounded read, so the truncation warning below stays quiet for it. */
|
|
378
|
+
function hasExplicitLimit(pathAndQuery: string): boolean {
|
|
379
|
+
const q = pathAndQuery.indexOf('?');
|
|
380
|
+
if (q === -1) return false;
|
|
381
|
+
return new URLSearchParams(pathAndQuery.slice(q + 1)).has('limit');
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// ---------------------------------------------------------------------------
|
|
385
|
+
// Embeds \u2014 write ONE thing, get the right path automatically.
|
|
386
|
+
//
|
|
387
|
+
// A relationship declared in your app's public/turbobase.json:
|
|
388
|
+
//
|
|
389
|
+
// { "relationships": [
|
|
390
|
+
// { "name": "inbound_shipment", "sourceTable": "item_receipt",
|
|
391
|
+
// "sourceJsonbKey": "custbody_inbound_shipment",
|
|
392
|
+
// "targetTable": "cr_inbound_shipment" } ] }
|
|
393
|
+
//
|
|
394
|
+
// is read as \`select('item_receipt?select=*,inbound_shipment(*)')\` \u2014 the same
|
|
395
|
+
// call whether or not the instance has finished creating the SQL resolver for it.
|
|
396
|
+
// Once the relationship is ARMED, PostgREST does the embedding in one request
|
|
397
|
+
// (the fast path, straight to /rest/v1). Until then the instance resolves it
|
|
398
|
+
// server-side through POST /v1/batch \u2014 a parent read plus one keyed read of the
|
|
399
|
+
// target, joined for you, RLS-scoped exactly the same way. Same call, same rows.
|
|
400
|
+
//
|
|
401
|
+
// The client discovers which path applies the only way a browser can: it tries
|
|
402
|
+
// the native embed first and, if PostgREST answers "no such relationship",
|
|
403
|
+
// remembers that alias for the rest of the session and goes through /v1/batch.
|
|
404
|
+
// One cheap 400 per alias per page-load, then never again.
|
|
405
|
+
// ---------------------------------------------------------------------------
|
|
406
|
+
|
|
407
|
+
/** Split on top-level commas only \u2014 commas inside \`rel(a,b)\` belong to the embed. */
|
|
408
|
+
function splitTopLevel(s: string): string[] {
|
|
409
|
+
const out: string[] = [];
|
|
410
|
+
let depth = 0;
|
|
411
|
+
let start = 0;
|
|
412
|
+
for (let i = 0; i < s.length; i++) {
|
|
413
|
+
const c = s[i];
|
|
414
|
+
if (c === '(') depth++;
|
|
415
|
+
else if (c === ')') depth = Math.max(0, depth - 1);
|
|
416
|
+
else if (c === ',' && depth === 0) {
|
|
417
|
+
out.push(s.slice(start, i));
|
|
418
|
+
start = i + 1;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
out.push(s.slice(start));
|
|
422
|
+
return out.map((p) => p.trim()).filter((p) => p.length > 0);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** The embed aliases a query asks for (\`[]\` when it asks for none). */
|
|
426
|
+
function embedAliases(pathAndQuery: string): string[] {
|
|
427
|
+
const q = pathAndQuery.indexOf('?');
|
|
428
|
+
if (q === -1) return [];
|
|
429
|
+
const select = new URLSearchParams(pathAndQuery.slice(q + 1)).get('select');
|
|
430
|
+
if (!select || !select.includes('(')) return [];
|
|
431
|
+
return splitTopLevel(select)
|
|
432
|
+
.filter((t) => t.includes('('))
|
|
433
|
+
.map((t) => {
|
|
434
|
+
const head = t.slice(0, t.indexOf('('));
|
|
435
|
+
const colon = head.indexOf(':');
|
|
436
|
+
return (colon === -1 ? head : head.slice(colon + 1)).replace(/!.*$/, '').trim();
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** Aliases whose native embed PostgREST could not resolve \u2014 read through the
|
|
441
|
+
* instance for the rest of this session instead of re-failing every time. */
|
|
442
|
+
const stitchedAliases = new Set<string>();
|
|
443
|
+
|
|
444
|
+
/** PostgREST's code for "could not find a relationship \u2026 in the schema cache" \u2014
|
|
445
|
+
* i.e. this embed has no resolver yet, which is the whole reason /v1/batch has
|
|
446
|
+
* a fallback. Anything else (permission, syntax, a real 500) is a genuine error
|
|
447
|
+
* and is thrown, never retried. */
|
|
448
|
+
function isMissingRelationship(status: number, body: string): boolean {
|
|
449
|
+
return status === 400 && (body.includes('PGRST200') || /find a relationship/i.test(body));
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** What one read produced: the rows, plus whatever the instance reported about
|
|
453
|
+
* resolving embeds server-side. */
|
|
454
|
+
interface ReadResult<T> {
|
|
455
|
+
rows: T[];
|
|
456
|
+
/** Present only when the instance stitched one or more embeds for this read. */
|
|
457
|
+
stitched?: { aliases: string[]; truncated: string[] };
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Read one path+query through POST /v1/batch (the server-resolved embed path). */
|
|
461
|
+
async function readThroughInstance<T>(pathAndQuery: string): Promise<ReadResult<T>> {
|
|
462
|
+
const res = await req('/v1/batch', {
|
|
463
|
+
method: 'POST',
|
|
464
|
+
headers: { 'content-type': 'application/json', Accept: 'application/json' },
|
|
465
|
+
body: JSON.stringify({ queries: [pathAndQuery] }),
|
|
466
|
+
});
|
|
467
|
+
if (!res.ok) throw new Error(await readError(res));
|
|
468
|
+
const json = (await res.json()) as {
|
|
469
|
+
results: {
|
|
470
|
+
ok: boolean;
|
|
471
|
+
status: number;
|
|
472
|
+
body: unknown;
|
|
473
|
+
stitched?: { aliases: string[]; truncated: string[] };
|
|
474
|
+
}[];
|
|
475
|
+
};
|
|
476
|
+
const r = json.results[0];
|
|
477
|
+
if (!r) throw new Error('read failed: the instance returned no result for this query');
|
|
478
|
+
if (!r.ok) {
|
|
479
|
+
throw new Error(
|
|
480
|
+
\`read failed (\${r.status}): \${typeof r.body === 'string' ? r.body : JSON.stringify(r.body)}\`,
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
return { rows: (r.body ?? []) as T[], stitched: r.stitched };
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* The one read primitive. Embed-free queries go straight to PostgREST, exactly as
|
|
488
|
+
* before. An embed-bearing query takes the native path unless this session has
|
|
489
|
+
* already learned the relationship has no resolver yet, in which case it goes
|
|
490
|
+
* through the instance.
|
|
491
|
+
*/
|
|
492
|
+
async function readRows<T>(pathAndQuery: string): Promise<ReadResult<T>> {
|
|
493
|
+
const aliases = embedAliases(pathAndQuery);
|
|
494
|
+
const table = pathAndQuery.split('?')[0]!;
|
|
495
|
+
const known = aliases.map((a) => \`\${table}.\${a}\`);
|
|
496
|
+
const mustStitch = known.some((k) => stitchedAliases.has(k));
|
|
497
|
+
|
|
498
|
+
if (!mustStitch) {
|
|
499
|
+
const res = await req(\`/rest/v1/\${pathAndQuery}\`, { headers: { Accept: 'application/json' } });
|
|
500
|
+
if (res.ok) return { rows: (await res.json()) as T[] };
|
|
501
|
+
const body = await res.text();
|
|
502
|
+
if (aliases.length === 0 || !isMissingRelationship(res.status, body)) {
|
|
503
|
+
throw new Error(await readErrorFromBody(res.status, body));
|
|
504
|
+
}
|
|
505
|
+
// Declared but not armed yet \u2014 remember, and fall through to the instance.
|
|
506
|
+
for (const k of known) stitchedAliases.add(k);
|
|
507
|
+
}
|
|
508
|
+
return readThroughInstance<T>(pathAndQuery);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Warn (loudly, by name) about anything the server silently shortened. */
|
|
512
|
+
function warnTruncation(pathAndQuery: string, result: ReadResult<unknown>): void {
|
|
513
|
+
if (
|
|
514
|
+
Array.isArray(result.rows) &&
|
|
515
|
+
result.rows.length === SERVER_MAX_ROWS &&
|
|
516
|
+
!hasExplicitLimit(pathAndQuery)
|
|
517
|
+
) {
|
|
518
|
+
console.warn(new TurbobaseTruncationError(pathAndQuery, SERVER_MAX_ROWS).message);
|
|
519
|
+
}
|
|
520
|
+
for (const alias of result.stitched?.truncated ?? []) {
|
|
521
|
+
console.warn(new TurbobaseTruncationError(pathAndQuery, SERVER_MAX_ROWS, alias).message);
|
|
522
|
+
}
|
|
523
|
+
// Native path: an embedded array at the server row cap was cut short the same
|
|
524
|
+
// way a top-level read is, and is just as invisible without this.
|
|
525
|
+
const first = result.rows?.[0] as Record<string, unknown> | undefined;
|
|
526
|
+
if (first) {
|
|
527
|
+
for (const alias of embedAliases(pathAndQuery)) {
|
|
528
|
+
if (Array.isArray(first[alias]) && (first[alias] as unknown[]).length >= SERVER_MAX_ROWS) {
|
|
529
|
+
console.warn(new TurbobaseTruncationError(pathAndQuery, SERVER_MAX_ROWS, alias).message);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Read rows from a PostgREST view/table (RLS-scoped).
|
|
537
|
+
*
|
|
538
|
+
* EMBEDS: \`select('item_receipt?select=*,inbound_shipment(*)')\` returns each
|
|
539
|
+
* receipt with its related rows attached under \`inbound_shipment\` \u2014 resolved by
|
|
540
|
+
* the instance in one round-trip either way, so you never fan out a lookup per
|
|
541
|
+
* row. A DECLARED-RELATIONSHIP embed is ALWAYS an array, including for a to-one
|
|
542
|
+
* link \u2014 the generated resolvers carry no \`ROWS 1\`, so PostgREST treats every
|
|
543
|
+
* one as to-many (it will even reject an order-by on the embed with PGRST118).
|
|
544
|
+
* A plain FOREIGN-KEY embed is different: it follows the FK's own cardinality,
|
|
545
|
+
* so \`item_receipt_line(*)\` is an array but \`subsidiary(name)\` is an object.
|
|
546
|
+
* Verified against PostgREST v12 and v14 in e2e/specs/108.
|
|
547
|
+
*
|
|
548
|
+
* LOUD TRUNCATION: an unbounded read (no \`limit=\`) that comes back at EXACTLY the
|
|
549
|
+
* server row cap was almost certainly cut short \u2014 a table with 1000+ rows returns
|
|
550
|
+
* a partial page indistinguishable from a complete one. When that happens we
|
|
551
|
+
* console.warn and tell you to paginate with selectPage(). The same warning fires
|
|
552
|
+
* when an EMBEDDED result was shortened. A caller that passed its own \`limit\`
|
|
553
|
+
* opted into a bounded read and is left alone.
|
|
554
|
+
*/
|
|
555
|
+
export async function select<T = unknown>(pathAndQuery: string): Promise<T[]> {
|
|
556
|
+
const result = await readRows<T>(pathAndQuery);
|
|
557
|
+
warnTruncation(pathAndQuery, result);
|
|
558
|
+
return result.rows;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Turn a failed PostgREST response into a message that names the ACTUAL
|
|
563
|
+
* problem.
|
|
564
|
+
*
|
|
565
|
+
* "permission denied for table X" is the same error whether your role is denied
|
|
566
|
+
* that table or you are not signed in at all \u2014 in the second case PostgREST is
|
|
567
|
+
* answering as the anonymous role, and the fix is a sign-in, not a grant. That
|
|
568
|
+
* ambiguity is the single most expensive one to debug from inside an app, so we
|
|
569
|
+
* disambiguate it here rather than making every caller learn it: no session
|
|
570
|
+
* cookie means not signed in, whatever the SQLSTATE says.
|
|
571
|
+
*/
|
|
572
|
+
async function readError(res: Response): Promise<string> {
|
|
573
|
+
return readErrorFromBody(res.status, await res.text());
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** Same disambiguation, for a body that has already been read (the embed path
|
|
577
|
+
* has to inspect the body before deciding whether the failure is retryable). */
|
|
578
|
+
function readErrorFromBody(status: number, body: string): string {
|
|
579
|
+
const signedIn = jwt() !== '';
|
|
580
|
+
// 42501 = insufficient_privilege. With no token we were the anon role.
|
|
581
|
+
if (!signedIn && (status === 401 || status === 403 || body.includes('42501'))) {
|
|
582
|
+
return (
|
|
583
|
+
\`not signed in (\${status}) \u2014 the request went to PostgREST as the anonymous \` +
|
|
584
|
+
'role, so every table denies it. In dev, sign in at http://localhost:3000/login ' +
|
|
585
|
+
'(proxied to the instance); in production the instance signs you in before the ' +
|
|
586
|
+
\`app loads. Underlying error: \${body}\`
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
return \`read failed (\${status}): \${body}\`;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** Write through the canonical boundary POST /v1/data/<recordType>. Never write a
|
|
593
|
+
* table directly. \`body\` is { parent, lines?, idempotencyKey?, externalId?, pgRowId?,
|
|
594
|
+
* expectedSyncVersion? } \u2014 the record-type goes in the PATH, not the body. */
|
|
595
|
+
export async function write<T = unknown>(recordType: string, body: unknown): Promise<T> {
|
|
596
|
+
const res = await req(\`/v1/data/\${recordType}\`, {
|
|
597
|
+
method: 'POST',
|
|
598
|
+
headers: { 'content-type': 'application/json' },
|
|
599
|
+
body: JSON.stringify(body),
|
|
600
|
+
});
|
|
601
|
+
if (!res.ok) throw new Error(await readError(res));
|
|
602
|
+
return (await res.json()) as T;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** One sub-result from batch(): its own status, so a 429/5xx on one query does
|
|
606
|
+
* not fail the others. \`ok\` is status 2xx; \`rows\` is the parsed body on
|
|
607
|
+
* success (undefined on failure \u2014 read \`status\`/\`error\`). */
|
|
608
|
+
export interface BatchResult<T = unknown> {
|
|
609
|
+
ok: boolean;
|
|
610
|
+
status: number;
|
|
611
|
+
rows?: T[];
|
|
612
|
+
error?: string;
|
|
613
|
+
/** Present when the instance resolved one or more embeds server-side for this
|
|
614
|
+
* query: the aliases it served, and any whose related rows were shortened by a
|
|
615
|
+
* server-side bound. */
|
|
616
|
+
stitched?: { aliases: string[]; truncated: string[] };
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** How many sub-queries ride in ONE /v1/batch request. The instance holds every
|
|
620
|
+
* result in a chunk in memory at once, so this bounds its peak footprint as well
|
|
621
|
+
* as ours. Chunks are sent one after another, not in parallel \u2014 firing them
|
|
622
|
+
* together would rebuild the very fan-out batch() exists to collapse. */
|
|
623
|
+
const BATCH_CHUNK = 8;
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* Multiplex many reads into ONE request (POST /v1/batch). Pass the SAME
|
|
627
|
+
* path+query strings you would give select(); get back results in the SAME
|
|
628
|
+
* order, each with its own status (partial success). Use this for first-paint
|
|
629
|
+
* fan-out instead of many select() calls \u2014 one request never trips the
|
|
630
|
+
* per-request rate limiter.
|
|
631
|
+
*
|
|
632
|
+
* const [orders, invoices] = await batch(['order?select=*&limit=100', 'invoice?select=*&limit=100']);
|
|
633
|
+
* if (orders.ok) render(orders.rows);
|
|
634
|
+
*
|
|
635
|
+
* ASK FOR LESS THAN YOU THINK. The instance caps each sub-query's response and
|
|
636
|
+
* the batch's total; a sub-query over the ceiling comes back as its OWN
|
|
637
|
+
* \`{ ok: false, status: 413 }\` slot (the siblings still return) with a message
|
|
638
|
+
* naming the limit. Two habits cause almost every 413:
|
|
639
|
+
* - \`select=*\` on a synced table \u2014 it drags the whole \`raw\` JSONB blob per
|
|
640
|
+
* row. List the columns you actually render.
|
|
641
|
+
* - a \`limit\` sized for a table scan rather than a screen. Page instead;
|
|
642
|
+
* \`contentRange\` on each result tells you the total.
|
|
643
|
+
*
|
|
644
|
+
* Long query lists are chunked automatically, so passing 40 queries is safe \u2014
|
|
645
|
+
* but 40 narrow queries is a very different request from 40 wide ones, and only
|
|
646
|
+
* the second kind 413s.
|
|
647
|
+
*/
|
|
648
|
+
export async function batch<T = unknown>(queries: string[]): Promise<BatchResult<T>[]> {
|
|
649
|
+
const out: BatchResult<T>[] = [];
|
|
650
|
+
for (let i = 0; i < queries.length; i += BATCH_CHUNK) {
|
|
651
|
+
out.push(...(await batchChunk<T>(queries.slice(i, i + BATCH_CHUNK))));
|
|
652
|
+
}
|
|
653
|
+
return out;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** One wire request. Order in === order out, so the caller's slice reassembles. */
|
|
657
|
+
async function batchChunk<T>(queries: string[]): Promise<BatchResult<T>[]> {
|
|
658
|
+
if (queries.length === 0) return [];
|
|
659
|
+
const res = await req('/v1/batch', {
|
|
660
|
+
method: 'POST',
|
|
661
|
+
headers: { 'content-type': 'application/json', Accept: 'application/json' },
|
|
662
|
+
body: JSON.stringify({ queries }),
|
|
663
|
+
});
|
|
664
|
+
if (!res.ok) throw new Error(await readError(res));
|
|
665
|
+
const json = (await res.json()) as {
|
|
666
|
+
results: {
|
|
667
|
+
ok: boolean;
|
|
668
|
+
status: number;
|
|
669
|
+
body: unknown;
|
|
670
|
+
stitched?: { aliases: string[]; truncated: string[] };
|
|
671
|
+
}[];
|
|
672
|
+
};
|
|
673
|
+
return json.results.map((r) =>
|
|
674
|
+
r.ok
|
|
675
|
+
? { ok: true, status: r.status, rows: r.body as T[], stitched: r.stitched }
|
|
676
|
+
: {
|
|
677
|
+
ok: false,
|
|
678
|
+
status: r.status,
|
|
679
|
+
error:
|
|
680
|
+
typeof r.body === 'object' && r.body && 'error' in r.body
|
|
681
|
+
? String((r.body as { error: unknown }).error)
|
|
682
|
+
: typeof r.body === 'object' && r.body && 'message' in r.body
|
|
683
|
+
? String((r.body as { message: unknown }).message)
|
|
684
|
+
: JSON.stringify(r.body),
|
|
685
|
+
},
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// ---------------------------------------------------------------------------
|
|
690
|
+
// Keyset pagination \u2014 page a table without draining it.
|
|
691
|
+
//
|
|
692
|
+
// select() is capped by the server at \${SERVER_MAX_ROWS} rows and warns when it
|
|
693
|
+
// truncates. selectPage() pages the FULL result set with a PostgREST-native
|
|
694
|
+
// keyset seek: order by the mirror sort key (\`pg_row_id\` when present, else
|
|
695
|
+
// \`external_id\` \u2014 pass { sortKey } for read-only masters), request one probe row
|
|
696
|
+
// beyond the page to detect a next page without a count, and seek the next page
|
|
697
|
+
// with \`<sortKey>=gt.<lastValue>\`. The opaque cursor pins itself to the exact
|
|
698
|
+
// query (table + filters + select) that minted it, so replaying it against a
|
|
699
|
+
// changed query throws instead of silently mixing two result sets.
|
|
700
|
+
// ---------------------------------------------------------------------------
|
|
701
|
+
|
|
702
|
+
/** One page of a keyset read: the trimmed rows, plus the token to fetch the next
|
|
703
|
+
* page (null when this was the last page). */
|
|
704
|
+
export interface Page<T = unknown> {
|
|
705
|
+
rows: T[];
|
|
706
|
+
nextCursor: string | null;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/** Opaque cursor payload \u2014 the same compact { t, k, v, h } shape TurboBase's
|
|
710
|
+
* server-side cursors use (table, sort key, last value, query hash). */
|
|
711
|
+
interface CursorToken {
|
|
712
|
+
t: string;
|
|
713
|
+
k: string;
|
|
714
|
+
v: string;
|
|
715
|
+
h: string;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** base64url-encode a UTF-8 string (no padding). */
|
|
719
|
+
function b64urlEncode(s: string): string {
|
|
720
|
+
const bytes = new TextEncoder().encode(s);
|
|
721
|
+
let bin = '';
|
|
722
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
|
|
723
|
+
return btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** base64url-decode back to a UTF-8 string. */
|
|
727
|
+
function b64urlDecode(s: string): string {
|
|
728
|
+
const b64 = s.replace(/-/g, '+').replace(/_/g, '/');
|
|
729
|
+
const pad = b64.length % 4 === 0 ? '' : '='.repeat(4 - (b64.length % 4));
|
|
730
|
+
const bytes = Uint8Array.from(atob(b64 + pad), (c) => c.charCodeAt(0));
|
|
731
|
+
return new TextDecoder().decode(bytes);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/** Mint an opaque next-page cursor. */
|
|
735
|
+
function encodeCursor(p: CursorToken): string {
|
|
736
|
+
return b64urlEncode(JSON.stringify({ t: p.t, k: p.k, v: p.v, h: p.h }));
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/** Decode a cursor token; throws TurbobaseCursorError on a malformed one. */
|
|
740
|
+
function decodeCursor(token: string): CursorToken {
|
|
741
|
+
let parsed: unknown;
|
|
742
|
+
try {
|
|
743
|
+
parsed = JSON.parse(b64urlDecode(token));
|
|
744
|
+
} catch {
|
|
745
|
+
throw new TurbobaseCursorError('cursor is malformed (not a valid token)');
|
|
746
|
+
}
|
|
747
|
+
const o = parsed as Record<string, unknown> | null;
|
|
748
|
+
if (
|
|
749
|
+
!o ||
|
|
750
|
+
typeof o.t !== 'string' ||
|
|
751
|
+
typeof o.k !== 'string' ||
|
|
752
|
+
typeof o.v !== 'string' ||
|
|
753
|
+
typeof o.h !== 'string'
|
|
754
|
+
) {
|
|
755
|
+
throw new TurbobaseCursorError('cursor is malformed (missing fields)');
|
|
756
|
+
}
|
|
757
|
+
return { t: o.t, k: o.k, v: o.v, h: o.h };
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** FNV-1a 32-bit hex \u2014 a tiny, dependency-free hash. Not cryptographic: it only
|
|
761
|
+
* pins a cursor to the query that minted it, so a stale cursor is rejected. */
|
|
762
|
+
function fnv1a(s: string): string {
|
|
763
|
+
let h = 0x811c9dc5;
|
|
764
|
+
for (let i = 0; i < s.length; i++) {
|
|
765
|
+
h ^= s.charCodeAt(i);
|
|
766
|
+
h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;
|
|
767
|
+
}
|
|
768
|
+
return h.toString(16).padStart(8, '0');
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** Hash the row-set-defining part of a query (table + sort key + every param
|
|
772
|
+
* except paging: order/limit/offset). Two pages of the same query hash equal;
|
|
773
|
+
* a changed filter/select hashes different and invalidates an old cursor. */
|
|
774
|
+
function queryHash(table: string, params: URLSearchParams, sortKey: string): string {
|
|
775
|
+
const parts: string[] = [];
|
|
776
|
+
for (const [k, v] of params) {
|
|
777
|
+
if (k === 'order' || k === 'limit' || k === 'offset') continue;
|
|
778
|
+
parts.push(\`\${k}=\${v}\`);
|
|
779
|
+
}
|
|
780
|
+
parts.sort();
|
|
781
|
+
return fnv1a(JSON.stringify([table, sortKey, parts]));
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* Read ONE keyset page from a PostgREST view/table (RLS-scoped), and return the
|
|
786
|
+
* cursor for the next page. Pass the SAME \`pathAndQuery\` you would give select()
|
|
787
|
+
* (filters, select, etc.) \u2014 selectPage() supplies the order + limit + seek.
|
|
788
|
+
*
|
|
789
|
+
* let { rows, nextCursor } = await selectPage('item_receipt?select=*', { pageSize: 50 });
|
|
790
|
+
* // \u2026later, load more:
|
|
791
|
+
* ({ rows, nextCursor } = await selectPage('item_receipt?select=*', { pageSize: 50, cursor: nextCursor }));
|
|
792
|
+
*
|
|
793
|
+
* \`sortKey\` defaults to \`pg_row_id\`; pass { sortKey: 'external_id' } for a
|
|
794
|
+
* read-only master table that has no \`pg_row_id\`.
|
|
795
|
+
*
|
|
796
|
+
* EMBEDS PAGE TOO: \`selectPage('purchase_order?select=*,receipt_lines(*)')\` keysets
|
|
797
|
+
* the PARENT (purchase_order) and carries the embed with each parent row, so a
|
|
798
|
+
* page is one request no matter how many related rows it pulls. If the instance
|
|
799
|
+
* had to shorten an embedded result it says so, and you get the same loud
|
|
800
|
+
* TurbobaseTruncationError warning select() gives \u2014 an embed that came back short
|
|
801
|
+
* is otherwise invisible, because the page's own row count is exactly what you
|
|
802
|
+
* asked for.
|
|
803
|
+
*/
|
|
804
|
+
export async function selectPage<T = unknown>(
|
|
805
|
+
pathAndQuery: string,
|
|
806
|
+
opts: { pageSize?: number; cursor?: string; sortKey?: string } = {},
|
|
807
|
+
): Promise<Page<T>> {
|
|
808
|
+
const pageSize = Math.max(1, Math.min(opts.pageSize ?? DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE));
|
|
809
|
+
const qIndex = pathAndQuery.indexOf('?');
|
|
810
|
+
const table = qIndex === -1 ? pathAndQuery : pathAndQuery.slice(0, qIndex);
|
|
811
|
+
const params = new URLSearchParams(qIndex === -1 ? '' : pathAndQuery.slice(qIndex + 1));
|
|
812
|
+
const sortKey = opts.sortKey ?? 'pg_row_id';
|
|
813
|
+
|
|
814
|
+
// Guarantee the sort key is projected so nextCursor can always be minted from
|
|
815
|
+
// the last row (mirrors the server's buildSelect). Split on TOP-LEVEL commas
|
|
816
|
+
// only: \`select=*,rel(a,b)\` must not be torn into \`rel(a\` + \`b)\`.
|
|
817
|
+
const sel = params.get('select');
|
|
818
|
+
if (sel && sel !== '*') {
|
|
819
|
+
const cols = splitTopLevel(sel);
|
|
820
|
+
if (!cols.includes(sortKey)) params.set('select', [...cols, sortKey].join(','));
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// Pin the cursor to the row-set-defining query BEFORE paging params are added.
|
|
824
|
+
const filterHash = queryHash(table, params, sortKey);
|
|
825
|
+
|
|
826
|
+
// Keyset order + one probe row beyond the page \u2192 has-more without a count.
|
|
827
|
+
params.set('order', \`\${sortKey}.asc\`);
|
|
828
|
+
params.set('limit', String(pageSize + 1));
|
|
829
|
+
params.delete('offset');
|
|
830
|
+
|
|
831
|
+
if (opts.cursor) {
|
|
832
|
+
const c = decodeCursor(opts.cursor);
|
|
833
|
+
if (c.t !== table) {
|
|
834
|
+
throw new TurbobaseCursorError(\`cursor is for table "\${c.t}", not "\${table}"\`);
|
|
835
|
+
}
|
|
836
|
+
if (c.h !== filterHash) {
|
|
837
|
+
throw new TurbobaseCursorError(
|
|
838
|
+
'cursor does not match this query (filters/select/sort key changed since it was minted)',
|
|
839
|
+
);
|
|
840
|
+
}
|
|
841
|
+
// Strict total-order seek past the last row of the previous page.
|
|
842
|
+
params.set(sortKey, \`gt.\${c.v}\`);
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
// Same read primitive as select(), so a page whose \`select\` carries an embed
|
|
846
|
+
// takes the native path when the relationship is armed and the instance-resolved
|
|
847
|
+
// path when it is not \u2014 the keyset is over the PARENT either way, and the embed
|
|
848
|
+
// rides along with each parent row.
|
|
849
|
+
const pageQuery = \`\${table}?\${params.toString()}\`;
|
|
850
|
+
const result = await readRows<T>(pageQuery);
|
|
851
|
+
const probe = result.rows;
|
|
852
|
+
// Truncation on an embedded result is invisible without this \u2014 the page itself
|
|
853
|
+
// looks complete because the PARENT row count is whatever you asked for.
|
|
854
|
+
for (const alias of result.stitched?.truncated ?? []) {
|
|
855
|
+
console.warn(new TurbobaseTruncationError(pageQuery, SERVER_MAX_ROWS, alias).message);
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// Trim the probe row; a next page exists iff the extra row came back.
|
|
859
|
+
const hasMore = probe.length > pageSize;
|
|
860
|
+
const rows = hasMore ? probe.slice(0, pageSize) : probe;
|
|
861
|
+
|
|
862
|
+
let nextCursor: string | null = null;
|
|
863
|
+
if (hasMore && rows.length > 0) {
|
|
864
|
+
const last = rows[rows.length - 1] as Record<string, unknown>;
|
|
865
|
+
const lastValue = last[sortKey];
|
|
866
|
+
if (lastValue != null) {
|
|
867
|
+
nextCursor = encodeCursor({ t: table, k: sortKey, v: String(lastValue), h: filterHash });
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
return { rows, nextCursor };
|
|
871
|
+
}
|
|
872
|
+
`;NT="http://localhost:54331",jT="http://localhost:4100";DT=`node_modules/
|
|
873
|
+
dist/
|
|
874
|
+
build/
|
|
875
|
+
|
|
876
|
+
# Holds a live personal access token (written by \`turbobase apps init\`).
|
|
877
|
+
.mcp.json
|
|
878
|
+
|
|
879
|
+
.env
|
|
880
|
+
.env.*
|
|
881
|
+
!.env.example
|
|
882
|
+
|
|
883
|
+
.DS_Store
|
|
884
|
+
`,Yg=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0},include:["src"]},null,2)}
|
|
885
|
+
`;Qg=`import React from 'react';
|
|
886
|
+
import { createRoot } from 'react-dom/client';
|
|
887
|
+
import App from './App';
|
|
888
|
+
import './styles.css';
|
|
889
|
+
|
|
890
|
+
createRoot(document.getElementById('root')!).render(
|
|
891
|
+
<React.StrictMode>
|
|
892
|
+
<App />
|
|
893
|
+
</React.StrictMode>,
|
|
894
|
+
);
|
|
895
|
+
`,ey=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
|
|
896
|
+
* { box-sizing: border-box; }
|
|
897
|
+
body { margin: 0; background: #f8fafc; color: #0f172a; }
|
|
898
|
+
`});var Jo=E(()=>{pi()});function k(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let d in i.prototype)d in a||Object.defineProperty(a,d,{value:i.prototype[d].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 u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}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 kt(t){return t&&Object.assign(Ii,t),Ii}var FT,gr,Ii,Wn=E(()=>{FT=Object.freeze({status:"aborted"});gr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ii={}});var de={};Po(de,{BIGINT_FORMAT_RANGES:()=>oy,Class:()=>Pu,NUMBER_FORMAT_RANGES:()=>ju,aborted:()=>yn,allowsEval:()=>Cu,assert:()=>WT,assertEqual:()=>BT,assertIs:()=>HT,assertNever:()=>KT,assertNotEqual:()=>VT,assignProp:()=>Ou,cached:()=>Qo,captureStackTrace:()=>Ci,cleanEnum:()=>aE,cleanRegex:()=>ts,clone:()=>St,createTransparentProxy:()=>eE,defineLazy:()=>Se,esc:()=>gn,escapeRegex:()=>Or,extend:()=>nE,finalizeIssue:()=>Ft,floatSafeRemainder:()=>Iu,getElementAtPath:()=>GT,getEnumValues:()=>Xo,getLengthableOrigin:()=>rs,getParsedType:()=>QT,getSizableOrigin:()=>sy,isObject:()=>Gn,isPlainObject:()=>Jn,issue:()=>Mu,joinValues:()=>Oi,jsonStringifyReplacer:()=>Au,merge:()=>oE,normalizeParams:()=>X,nullish:()=>es,numKeys:()=>XT,omit:()=>rE,optionalKeys:()=>Nu,partial:()=>sE,pick:()=>tE,prefixIssues:()=>tr,primitiveTypes:()=>ny,promiseAllObject:()=>JT,propertyKeyTypes:()=>zu,randomString:()=>YT,required:()=>iE,stringifyPrimitive:()=>zi,unwrapMessage:()=>Yo});function BT(t){return t}function VT(t){return t}function HT(t){}function KT(t){throw new Error}function WT(t){}function Xo(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 Oi(t,e="|"){return t.map(r=>zi(r)).join(e)}function Au(t,e){return typeof e=="bigint"?e.toString():e}function Qo(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 ts(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Iu(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 Se(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 Ou(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function GT(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function JT(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 YT(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function gn(t){return JSON.stringify(t)}function Gn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Jn(t){if(Gn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Gn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function XT(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Or(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function St(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function X(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 eE(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 zi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Nu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function tE(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 St(t,{...t._zod.def,shape:r,checks:[]})}function rE(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 St(t,{...t._zod.def,shape:r,checks:[]})}function nE(t,e){if(!Jn(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 Ou(this,"shape",n),n},checks:[]};return St(t,r)}function oE(t,e){return St(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Ou(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function sE(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 St(e,{...e._zod.def,shape:o,checks:[]})}function iE(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 St(e,{...e._zod.def,shape:o,checks:[]})}function yn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function tr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Yo(t){return typeof t=="string"?t:t?.message}function Ft(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Yo(t.inst?._zod.def?.error?.(t))??Yo(e?.error?.(t))??Yo(r.customError?.(t))??Yo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function sy(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function rs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Mu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function aE(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ci,Cu,QT,zu,ny,ju,oy,Pu,rr=E(()=>{Ci=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Cu=Qo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});QT=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}`)}},zu=new Set(["string","number","symbol"]),ny=new Set(["string","number","bigint","boolean","symbol","undefined"]);ju={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]},oy={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Pu=class{constructor(...e){}}});function Lu(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 Du(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 u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var iy,Ni,ns,Zu=E(()=>{Wn();rr();iy=(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,Au,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ni=k("$ZodError",iy),ns=k("$ZodError",iy,{Parent:Error})});var Uu,qu,Fu,Bu,Vu,bn,Hu,_n,Ku=E(()=>{Wn();Zu();rr();Uu=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 gr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Ft(c,s,kt())));throw Ci(a,o?.callee),a}return i.value},qu=Uu(ns),Fu=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=>Ft(c,s,kt())));throw Ci(a,o?.callee),a}return i.value},Bu=Fu(ns),Vu=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 gr;return s.issues.length?{success:!1,error:new(t??Ni)(s.issues.map(i=>Ft(i,o,kt())))}:{success:!0,data:s.value}},bn=Vu(ns),Hu=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=>Ft(i,o,kt())))}:{success:!0,data:s.value}},_n=Hu(ns)});function gy(){return new RegExp(uE,"u")}function Ty(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 Ey(t){return new RegExp(`^${Ty(t)}$`)}function Ry(t){let e=Ty({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(`^${ky}T(?:${n})$`)}var ay,cy,uy,ly,dy,py,fy,hy,Wu,my,uE,yy,by,_y,wy,vy,Gu,xy,$y,ky,Sy,Py,Ay,Iy,Oy,Cy,zy,Ny,Mi=E(()=>{ay=/^[cC][^\s-]{8,}$/,cy=/^[0-9a-z]+$/,uy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ly=/^[0-9a-vA-V]{20}$/,dy=/^[A-Za-z0-9]{27}$/,py=/^[a-zA-Z0-9_-]{21}$/,fy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,hy=/^([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})$/,Wu=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)$/,my=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,uE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";yy=/^(?:(?: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])$/,by=/^(([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})$/,_y=/^((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])$/,wy=/^(([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])$/,vy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Gu=/^[A-Za-z0-9_-]*$/,xy=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,$y=/^\+(?:[0-9]){6,14}[0-9]$/,ky="(?:(?:\\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])))",Sy=new RegExp(`^${ky}$`);Py=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Ay=/^\d+$/,Iy=/^-?\d+(?:\.\d+)?/i,Oy=/true|false/i,Cy=/null/i,zy=/^[^A-Z]*$/,Ny=/^[^a-z]*$/});var Xe,jy,Ju,Yu,My,Ly,Dy,Zy,Uy,os,qy,Fy,By,Vy,Hy,Ky,Wy,Li=E(()=>{Wn();Mi();rr();Xe=k("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),jy={number:"number",bigint:"bigint",object:"date"},Ju=k("$ZodCheckLessThan",(t,e)=>{Xe.init(t,e);let r=jy[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})}}),Yu=k("$ZodCheckGreaterThan",(t,e)=>{Xe.init(t,e);let r=jy[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})}}),My=k("$ZodCheckMultipleOf",(t,e)=>{Xe.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):Iu(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})}}),Ly=k("$ZodCheckNumberFormat",(t,e)=>{Xe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=ju[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=Ay)}),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})}}),Dy=k("$ZodCheckMaxLength",(t,e)=>{var r;Xe.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=rs(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Zy=k("$ZodCheckMinLength",(t,e)=>{var r;Xe.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=rs(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Uy=k("$ZodCheckLengthEquals",(t,e)=>{var r;Xe.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=rs(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})}}),os=k("$ZodCheckStringFormat",(t,e)=>{var r,n;Xe.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=()=>{})}),qy=k("$ZodCheckRegex",(t,e)=>{os.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})}}),Fy=k("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=zy),os.init(t,e)}),By=k("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ny),os.init(t,e)}),Vy=k("$ZodCheckIncludes",(t,e)=>{Xe.init(t,e);let r=Or(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})}}),Hy=k("$ZodCheckStartsWith",(t,e)=>{Xe.init(t,e);let r=new RegExp(`^${Or(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})}}),Ky=k("$ZodCheckEndsWith",(t,e)=>{Xe.init(t,e);let r=new RegExp(`.*${Or(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})}}),Wy=k("$ZodCheckOverwrite",(t,e)=>{Xe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Di,Xu=E(()=>{Di=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(`
|
|
899
|
+
`).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(`
|
|
900
|
+
`))}}});var Jy,Qu=E(()=>{Jy={major:4,minor:0,patch:0}});function lb(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function lE(t){if(!Gu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return lb(r)}function dE(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 Yy(t,e,r){t.issues.length&&e.issues.push(...tr(r,t.issues)),e.value[r]=t.value}function Zi(t,e,r){t.issues.length&&e.issues.push(...tr(r,t.issues)),e.value[r]=t.value}function Xy(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(...tr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Qy(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=>Ft(s,n,kt())))}),e}function el(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(Jn(t)&&Jn(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=el(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=el(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 eb(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),yn(t))return t;let n=el(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 tb(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function rb(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 nb(t,e,r){return yn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function ob(t){return t.value=Object.freeze(t.value),t}function sb(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(Mu(o))}}var ve,ss,Te,tl,rl,nl,ol,sl,il,al,cl,ul,ll,dl,ib,ab,cb,ub,pl,fl,hl,ml,gl,yl,bl,_l,Ui,wl,vl,xl,$l,kl,Sl,qi,Fi,Tl,El,Rl,Pl,Al,Il,Ol,Cl,zl,Nl,jl,Ml,Ll,Dl,Zl,db=E(()=>{Li();Wn();Xu();Ku();Mi();rr();Qu();rr();ve=k("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Jy;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=yn(s),u;for(let d of i){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;let l=s.issues.length,f=d._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new gr;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==l&&(c||(c=yn(s,l)))});else{if(s.issues.length===l)continue;c||(c=yn(s,l))}}return u?u.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 gr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=bn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return _n(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ss=k("$ZodString",(t,e)=>{ve.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Py(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}}),Te=k("$ZodStringFormat",(t,e)=>{os.init(t,e),ss.init(t,e)}),tl=k("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=hy),Te.init(t,e)}),rl=k("$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=Wu(n))}else e.pattern??(e.pattern=Wu());Te.init(t,e)}),nl=k("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=my),Te.init(t,e)}),ol=k("$ZodURL",(t,e)=>{Te.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:xy.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})}}}),sl=k("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=gy()),Te.init(t,e)}),il=k("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=py),Te.init(t,e)}),al=k("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ay),Te.init(t,e)}),cl=k("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=cy),Te.init(t,e)}),ul=k("$ZodULID",(t,e)=>{e.pattern??(e.pattern=uy),Te.init(t,e)}),ll=k("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ly),Te.init(t,e)}),dl=k("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=dy),Te.init(t,e)}),ib=k("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ry(e)),Te.init(t,e)}),ab=k("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Sy),Te.init(t,e)}),cb=k("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ey(e)),Te.init(t,e)}),ub=k("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=fy),Te.init(t,e)}),pl=k("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=yy),Te.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),fl=k("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=by),Te.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})}}}),hl=k("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=_y),Te.init(t,e)}),ml=k("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=wy),Te.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})}}});gl=k("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=vy),Te.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{lb(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});yl=k("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Gu),Te.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{lE(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),bl=k("$ZodE164",(t,e)=>{e.pattern??(e.pattern=$y),Te.init(t,e)});_l=k("$ZodJWT",(t,e)=>{Te.init(t,e),t._zod.check=r=>{dE(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ui=k("$ZodNumber",(t,e)=>{ve.init(t,e),t._zod.pattern=t._zod.bag.pattern??Iy,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}}),wl=k("$ZodNumber",(t,e)=>{Ly.init(t,e),Ui.init(t,e)}),vl=k("$ZodBoolean",(t,e)=>{ve.init(t,e),t._zod.pattern=Oy,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}}),xl=k("$ZodNull",(t,e)=>{ve.init(t,e),t._zod.pattern=Cy,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}}),$l=k("$ZodUnknown",(t,e)=>{ve.init(t,e),t._zod.parse=r=>r}),kl=k("$ZodNever",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Sl=k("$ZodArray",(t,e)=>{ve.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(u=>Yy(u,r,i))):Yy(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});qi=k("$ZodObject",(t,e)=>{ve.init(t,e);let r=Qo(()=>{let l=Object.keys(e.shape);for(let h of l)if(!(e.shape[h]instanceof ve))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let f=Nu(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(f)}});Se(t._zod,"propValues",()=>{let l=e.shape,f={};for(let h in l){let p=l[h]._zod;if(p.values){f[h]??(f[h]=new Set);for(let m of p.values)f[h].add(m)}}return f});let n=l=>{let f=new Di(["shape","payload","ctx"]),h=r.value,p=R=>{let C=gn(R);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`};f.write("const input = payload.value;");let m=Object.create(null),b=0;for(let R of h.keys)m[R]=`key_${b++}`;f.write("const newResult = {}");for(let R of h.keys)if(h.optionalKeys.has(R)){let C=m[R];f.write(`const ${C} = ${p(R)};`);let B=gn(R);f.write(`
|
|
901
|
+
if (${C}.issues.length) {
|
|
902
|
+
if (input[${B}] === undefined) {
|
|
903
|
+
if (${B} in input) {
|
|
904
|
+
newResult[${B}] = undefined;
|
|
905
|
+
}
|
|
906
|
+
} else {
|
|
907
|
+
payload.issues = payload.issues.concat(
|
|
908
|
+
${C}.issues.map((iss) => ({
|
|
909
|
+
...iss,
|
|
910
|
+
path: iss.path ? [${B}, ...iss.path] : [${B}],
|
|
911
|
+
}))
|
|
912
|
+
);
|
|
913
|
+
}
|
|
914
|
+
} else if (${C}.value === undefined) {
|
|
915
|
+
if (${B} in input) newResult[${B}] = undefined;
|
|
916
|
+
} else {
|
|
917
|
+
newResult[${B}] = ${C}.value;
|
|
918
|
+
}
|
|
919
|
+
`)}else{let C=m[R];f.write(`const ${C} = ${p(R)};`),f.write(`
|
|
920
|
+
if (${C}.issues.length) payload.issues = payload.issues.concat(${C}.issues.map(iss => ({
|
|
921
|
+
...iss,
|
|
922
|
+
path: iss.path ? [${gn(R)}, ...iss.path] : [${gn(R)}]
|
|
923
|
+
})));`),f.write(`newResult[${gn(R)}] = ${C}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let S=f.compile();return(R,C)=>S(l,R,C)},o,s=Gn,i=!Ii.jitless,c=i&&Cu.value,u=e.catchall,d;t._zod.parse=(l,f)=>{d??(d=r.value);let h=l.value;if(!s(h))return l.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),l;let p=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(e.shape)),l=o(l,f);else{l.value={};let C=d.shape;for(let B of d.keys){let G=C[B],Ve=G._zod.run({value:h[B],issues:[]},f),He=G._zod.optin==="optional"&&G._zod.optout==="optional";Ve instanceof Promise?p.push(Ve.then(ur=>He?Xy(ur,l,B,h):Zi(ur,l,B))):He?Xy(Ve,l,B,h):Zi(Ve,l,B)}}if(!u)return p.length?Promise.all(p).then(()=>l):l;let m=[],b=d.keySet,S=u._zod,R=S.def.type;for(let C of Object.keys(h)){if(b.has(C))continue;if(R==="never"){m.push(C);continue}let B=S.run({value:h[C],issues:[]},f);B instanceof Promise?p.push(B.then(G=>Zi(G,l,C))):Zi(B,l,C)}return m.length&&l.issues.push({code:"unrecognized_keys",keys:m,input:h,inst:t}),p.length?Promise.all(p).then(()=>l):l}});Fi=k("$ZodUnion",(t,e)=>{ve.init(t,e),Se(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Se(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Se(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Se(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=>ts(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=>Qy(i,r,t,n)):Qy(s,r,t,n)}}),Tl=k("$ZodDiscriminatedUnion",(t,e)=>{Fi.init(t,e);let r=t._zod.parse;Se(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 u of c)o[a].add(u)}}return o});let n=Qo(()=>{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(!Gn(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)}}),El=k("$ZodIntersection",(t,e)=>{ve.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,u])=>eb(r,c,u)):eb(r,s,i)}});Rl=k("$ZodRecord",(t,e)=>{ve.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Jn(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 u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(d=>{d.issues.length&&r.issues.push(...tr(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...tr(c,u.issues)),r.value[c]=u.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(u=>Ft(u,n,kt())),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(u=>{u.issues.length&&r.issues.push(...tr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...tr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Pl=k("$ZodEnum",(t,e)=>{ve.init(t,e);let r=Xo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>zu.has(typeof n)).map(n=>typeof n=="string"?Or(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}}),Al=k("$ZodLiteral",(t,e)=>{ve.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Or(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}}),Il=k("$ZodTransform",(t,e)=>{ve.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 gr;return r.value=o,r}}),Ol=k("$ZodOptional",(t,e)=>{ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Se(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Se(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ts(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)}),Cl=k("$ZodNullable",(t,e)=>{ve.init(t,e),Se(t._zod,"optin",()=>e.innerType._zod.optin),Se(t._zod,"optout",()=>e.innerType._zod.optout),Se(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ts(r.source)}|null)$`):void 0}),Se(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)}),zl=k("$ZodDefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Se(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=>tb(s,e)):tb(o,e)}});Nl=k("$ZodPrefault",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Se(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))}),jl=k("$ZodNonOptional",(t,e)=>{ve.init(t,e),Se(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=>rb(s,t)):rb(o,t)}});Ml=k("$ZodCatch",(t,e)=>{ve.init(t,e),t._zod.optin="optional",Se(t._zod,"optout",()=>e.innerType._zod.optout),Se(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=>Ft(i,n,kt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Ft(s,n,kt()))},input:r.value}),r.issues=[]),r)}}),Ll=k("$ZodPipe",(t,e)=>{ve.init(t,e),Se(t._zod,"values",()=>e.in._zod.values),Se(t._zod,"optin",()=>e.in._zod.optin),Se(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=>nb(s,e,n)):nb(o,e,n)}});Dl=k("$ZodReadonly",(t,e)=>{ve.init(t,e),Se(t._zod,"propValues",()=>e.innerType._zod.propValues),Se(t._zod,"values",()=>e.innerType._zod.values),Se(t._zod,"optin",()=>e.innerType._zod.optin),Se(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(ob):ob(o)}});Zl=k("$ZodCustom",(t,e)=>{Xe.init(t,e),ve.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=>sb(s,r,n,t));sb(o,r,n,t)}})});function pb(){return{localeError:fE()}}var pE,fE,fb=E(()=>{rr();pE=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},fE=()=>{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 ${pE(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${zi(n.values[0])}`:`Invalid option: expected one of ${Oi(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":""}: ${Oi(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 Bi=E(()=>{});function hb(){return new is}var is,Cr,ql=E(()=>{is=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)}};Cr=hb()});function Fl(t,e){return new t({type:"string",...X(e)})}function Bl(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...X(e)})}function Vi(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...X(e)})}function Vl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...X(e)})}function Hl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(e)})}function Kl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(e)})}function Wl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(e)})}function Gl(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...X(e)})}function Jl(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...X(e)})}function Yl(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(e)})}function Xl(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...X(e)})}function Ql(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(e)})}function ed(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...X(e)})}function td(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...X(e)})}function rd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(e)})}function nd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(e)})}function od(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(e)})}function sd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(e)})}function id(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(e)})}function ad(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...X(e)})}function cd(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...X(e)})}function ud(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...X(e)})}function ld(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...X(e)})}function mb(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(e)})}function gb(t,e){return new t({type:"string",format:"date",check:"string_format",...X(e)})}function yb(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...X(e)})}function bb(t,e){return new t({type:"string",format:"duration",check:"string_format",...X(e)})}function dd(t,e){return new t({type:"number",checks:[],...X(e)})}function pd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...X(e)})}function fd(t,e){return new t({type:"boolean",...X(e)})}function hd(t,e){return new t({type:"null",...X(e)})}function md(t){return new t({type:"unknown"})}function gd(t,e){return new t({type:"never",...X(e)})}function Hi(t,e){return new Ju({check:"less_than",...X(e),value:t,inclusive:!1})}function as(t,e){return new Ju({check:"less_than",...X(e),value:t,inclusive:!0})}function Ki(t,e){return new Yu({check:"greater_than",...X(e),value:t,inclusive:!1})}function cs(t,e){return new Yu({check:"greater_than",...X(e),value:t,inclusive:!0})}function Wi(t,e){return new My({check:"multiple_of",...X(e),value:t})}function Gi(t,e){return new Dy({check:"max_length",...X(e),maximum:t})}function Yn(t,e){return new Zy({check:"min_length",...X(e),minimum:t})}function Ji(t,e){return new Uy({check:"length_equals",...X(e),length:t})}function yd(t,e){return new qy({check:"string_format",format:"regex",...X(e),pattern:t})}function bd(t){return new Fy({check:"string_format",format:"lowercase",...X(t)})}function _d(t){return new By({check:"string_format",format:"uppercase",...X(t)})}function wd(t,e){return new Vy({check:"string_format",format:"includes",...X(e),includes:t})}function vd(t,e){return new Hy({check:"string_format",format:"starts_with",...X(e),prefix:t})}function xd(t,e){return new Ky({check:"string_format",format:"ends_with",...X(e),suffix:t})}function wn(t){return new Wy({check:"overwrite",tx:t})}function $d(t){return wn(e=>e.normalize(t))}function kd(){return wn(t=>t.trim())}function Sd(){return wn(t=>t.toLowerCase())}function Td(){return wn(t=>t.toUpperCase())}function _b(t,e,r){return new t({type:"array",element:e,...X(r)})}function Ed(t,e,r){let n=X(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Rd(t,e,r){return new t({type:"custom",check:"custom",fn:e,...X(r)})}var wb=E(()=>{Li();rr()});var vb=E(()=>{});function Pd(t,e){if(t instanceof is){let n=new Yi(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...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 Yi(e);return r.process(t),r.emit(t,e)}function Ke(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 Ke(o.element,r);case"object":{for(let s in o.shape)if(Ke(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Ke(s,r))return!0;return!1}case"intersection":return Ke(o.left,r)||Ke(o.right,r);case"tuple":{for(let s of o.items)if(Ke(s,r))return!0;return!!(o.rest&&Ke(o.rest,r))}case"record":return Ke(o.keyType,r)||Ke(o.valueType,r);case"map":return Ke(o.keyType,r)||Ke(o.valueType,r);case"set":return Ke(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ke(o.innerType,r);case"lazy":return Ke(o.getter(),r);case"default":return Ke(o.innerType,r);case"prefault":return Ke(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ke(o.in,r)||Ke(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Yi,xb=E(()=>{ql();rr();Yi=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Cr,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 l={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,l),this.seen.get(f).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let p=h;p.type="string";let{minimum:m,maximum:b,format:S,patterns:R,contentEncoding:C}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof b=="number"&&(p.maxLength=b),S&&(p.format=s[S]??S,p.format===""&&delete p.format),C&&(p.contentEncoding=C),R&&R.size>0){let B=[...R];B.length===1?p.pattern=B[0].source:B.length>1&&(a.schema.allOf=[...B.map(G=>({...this.target==="draft-7"?{type:"string"}:{},pattern:G.source}))])}break}case"number":{let p=h,{minimum:m,maximum:b,format:S,multipleOf:R,exclusiveMaximum:C,exclusiveMinimum:B}=e._zod.bag;typeof S=="string"&&S.includes("int")?p.type="integer":p.type="number",typeof B=="number"&&(p.exclusiveMinimum=B),typeof m=="number"&&(p.minimum=m,typeof B=="number"&&(B>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof C=="number"&&(p.exclusiveMaximum=C),typeof b=="number"&&(p.maximum=b,typeof C=="number"&&(C<=b?delete p.maximum:delete p.exclusiveMaximum)),typeof R=="number"&&(p.multipleOf=R);break}case"boolean":{let p=h;p.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":{h.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":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=h,{minimum:m,maximum:b}=e._zod.bag;typeof m=="number"&&(p.minItems=m),typeof b=="number"&&(p.maxItems=b),p.type="array",p.items=this.process(o.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=h;p.type="object",p.properties={};let m=o.shape;for(let R in m)p.properties[R]=this.process(m[R],{...l,path:[...l.path,"properties",R]});let b=new Set(Object.keys(m)),S=new Set([...b].filter(R=>{let C=o.shape[R]._zod;return this.io==="input"?C.optin===void 0:C.optout===void 0}));S.size>0&&(p.required=Array.from(S)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=h;p.anyOf=o.options.map((m,b)=>this.process(m,{...l,path:[...l.path,"anyOf",b]}));break}case"intersection":{let p=h,m=this.process(o.left,{...l,path:[...l.path,"allOf",0]}),b=this.process(o.right,{...l,path:[...l.path,"allOf",1]}),S=C=>"allOf"in C&&Object.keys(C).length===1,R=[...S(m)?m.allOf:[m],...S(b)?b.allOf:[b]];p.allOf=R;break}case"tuple":{let p=h;p.type="array";let m=o.items.map((R,C)=>this.process(R,{...l,path:[...l.path,"prefixItems",C]}));if(this.target==="draft-2020-12"?p.prefixItems=m:p.items=m,o.rest){let R=this.process(o.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=R:p.additionalItems=R}o.rest&&(p.items=this.process(o.rest,{...l,path:[...l.path,"items"]}));let{minimum:b,maximum:S}=e._zod.bag;typeof b=="number"&&(p.minItems=b),typeof S=="number"&&(p.maxItems=S);break}case"record":{let p=h;p.type="object",p.propertyNames=this.process(o.keyType,{...l,path:[...l.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...l,path:[...l.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 p=h,m=Xo(o.entries);m.every(b=>typeof b=="number")&&(p.type="number"),m.every(b=>typeof b=="string")&&(p.type="string"),p.enum=m;break}case"literal":{let p=h,m=[];for(let b of o.values)if(b===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof b=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");m.push(Number(b))}else m.push(b);if(m.length!==0)if(m.length===1){let b=m[0];p.type=b===null?"null":typeof b,p.const=b}else m.every(b=>typeof b=="number")&&(p.type="number"),m.every(b=>typeof b=="string")&&(p.type="string"),m.every(b=>typeof b=="boolean")&&(p.type="string"),m.every(b=>b===null)&&(p.type="null"),p.enum=m;break}case"file":{let p=h,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:b,maximum:S,mime:R}=e._zod.bag;b!==void 0&&(m.minLength=b),S!==void 0&&(m.maxLength=S),R?R.length===1?(m.contentMediaType=R[0],Object.assign(p,m)):p.anyOf=R.map(C=>({...m,contentMediaType:C})):Object.assign(p,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,l);h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"success":{let p=h;p.type="boolean";break}case"default":{this.process(o.innerType,l),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,l),a.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,l),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=h,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=m.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,l),a.ref=p;break}case"readonly":{this.process(o.innerType,l),a.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,l),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,l),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,l),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Ke(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=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let m=n.external.registry.get(d[0])?.id,b=n.external.uri??(R=>R);if(m)return{ref:b(m)};let S=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=S,{defId:S,ref:`${b("__shared")}#/${l}/${S}`}}if(d[1]===o)return{ref:"#"};let h=`#/${l}/`,p=d[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:h+p}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:f,defId:h}=s(d);l.def={...l.schema},h&&(l.defId=h);let p=l.schema;for(let m in p)delete p[m];p.$ref=f};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
924
|
+
|
|
925
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let h=n.external.registry.get(d[0])?.id;if(e!==d[0]&&h){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let f=this.seen.get(d),h=f.def??f.schema,p={...h};if(f.ref===null)return;let m=f.ref;if(f.ref=null,m){a(m,l);let b=this.seen.get(m).schema;b.$ref&&l.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(b)):(Object.assign(h,b),Object.assign(h,p))}f.isParent||this.override({zodSchema:d,jsonSchema:h,path:f.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[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 d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let d of this.seen.entries()){let l=d[1];l.def&&l.defId&&(u[l.defId]=l.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var $b=E(()=>{});var at=E(()=>{Wn();Ku();Zu();db();Li();Qu();rr();Mi();Bi();ql();Xu();vb();wb();xb();$b()});var Ad=E(()=>{at()});function Id(t,e){let r={type:"object",get shape(){return de.assignProp(this,"shape",{...t}),this.shape},...de.normalizeParams(e)};return new GE(r)}var WE,GE,kb=E(()=>{at();at();Ad();WE=k("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ve.init(t,e),t.def=e,t.parse=(r,n)=>qu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>bn(t,r,n),t.parseAsync=async(r,n)=>Bu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>_n(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)=>St(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),GE=k("ZodMiniObject",(t,e)=>{qi.init(t,e),WE.init(t,e),de.defineLazy(t,"shape",()=>e.shape)})});var Sb=E(()=>{});var Tb=E(()=>{});var Eb=E(()=>{});var Rb=E(()=>{at();Ad();kb();Sb();at();Bi();Tb();Eb()});var Pb=E(()=>{Rb()});var Od=E(()=>{Pb()});function nr(t){return!!t._zod}function xn(t){let e=Object.values(t);if(e.length===0)return Id({});let r=e.every(nr),n=e.every(o=>!nr(o));if(r)return Id(t);if(n)return Uc(t);throw new Error("Mixed Zod versions detected in object shape.")}function zr(t,e){return nr(t)?bn(t,e):t.safeParse(e)}async function Xi(t,e){return nr(t)?await _n(t,e):await t.safeParseAsync(e)}function Nr(t){if(!t)return;let e;if(nr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Xn(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 xn(t)}}if(nr(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 XE(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Qi(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 ${XE(e.path)}`:e.message).join(`
|
|
926
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Ib(t){return t.description}function Ob(t){if(nr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Qn(t){if(nr(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 us=E(()=>{Jo();Od()});var Cd=E(()=>{at()});var ls={};Po(ls,{ZodISODate:()=>zb,ZodISODateTime:()=>Cb,ZodISODuration:()=>jb,ZodISOTime:()=>Nb,date:()=>Nd,datetime:()=>zd,duration:()=>Md,time:()=>jd});function zd(t){return mb(Cb,t)}function Nd(t){return gb(zb,t)}function jd(t){return yb(Nb,t)}function Md(t){return bb(jb,t)}var Cb,zb,Nb,jb,Ld=E(()=>{at();Dd();Cb=k("ZodISODateTime",(t,e)=>{ib.init(t,e),Ne.init(t,e)});zb=k("ZodISODate",(t,e)=>{ab.init(t,e),Ne.init(t,e)});Nb=k("ZodISOTime",(t,e)=>{cb.init(t,e),Ne.init(t,e)});jb=k("ZodISODuration",(t,e)=>{ub.init(t,e),Ne.init(t,e)})});var Mb,EZ,ds,Zd=E(()=>{at();at();Mb=(t,e)=>{Ni.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Du(t,r)},flatten:{value:r=>Lu(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},EZ=k("ZodError",Mb),ds=k("ZodError",Mb,{Parent:Error})});var Lb,Db,Zb,Ub,Ud=E(()=>{at();Zd();Lb=Uu(ds),Db=Fu(ds),Zb=Vu(ds),Ub=Hu(ds)});function v(t){return Fl(iR,t)}function _e(t){return dd(Hb,t)}function Fb(t){return pd(kR,t)}function Ge(t){return fd(SR,t)}function Kb(t){return hd(TR,t)}function je(){return md(ER)}function PR(t){return gd(RR,t)}function fe(t,e){return _b(AR,t,e)}function F(t,e){let r={type:"object",get shape(){return de.assignProp(this,"shape",{...t}),this.shape},...de.normalizeParams(e)};return new Wb(r)}function ct(t,e){return new Wb({type:"object",get shape(){return de.assignProp(this,"shape",{...t}),this.shape},catchall:je(),...de.normalizeParams(e)})}function Pe(t,e){return new Gb({type:"union",options:t,...de.normalizeParams(e)})}function Bd(t,e,r){return new IR({type:"union",options:e,discriminator:t,...de.normalizeParams(r)})}function ta(t,e){return new OR({type:"intersection",left:t,right:e})}function Ee(t,e,r){return new CR({type:"record",keyType:t,valueType:e,...de.normalizeParams(r)})}function gt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new qd({type:"enum",entries:r,...de.normalizeParams(e)})}function K(t,e){return new zR({type:"literal",values:Array.isArray(t)?t:[t],...de.normalizeParams(e)})}function Jb(t){return new NR({type:"transform",transform:t})}function Me(t){return new Yb({type:"optional",innerType:t})}function Bb(t){return new jR({type:"nullable",innerType:t})}function LR(t,e){return new MR({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function ZR(t,e){return new DR({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function UR(t,e){return new Xb({type:"nonoptional",innerType:t,...de.normalizeParams(e)})}function FR(t,e){return new qR({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Fd(t,e){return new BR({type:"pipe",in:t,out:e})}function HR(t){return new VR({type:"readonly",innerType:t})}function KR(t){let e=new Xe({check:"custom"});return e._zod.check=t,e}function e_(t,e){return Ed(Qb,t??(()=>!0),e)}function WR(t,e={}){return Rd(Qb,t,e)}function GR(t){let e=KR(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(de.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(de.issue(o))}},t(r.value,r)));return e}function Vd(t,e){return Fd(Jb(t),e)}var Ze,Vb,iR,Ne,aR,qb,ea,cR,uR,lR,dR,pR,fR,hR,mR,gR,yR,bR,_R,wR,vR,xR,$R,Hb,kR,SR,TR,ER,RR,AR,Wb,Gb,IR,OR,CR,qd,zR,NR,Yb,jR,MR,DR,Xb,qR,BR,VR,Qb,Dd=E(()=>{at();at();Cd();Ld();Ud();Ze=k("ZodType",(t,e)=>(ve.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)=>St(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Lb(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Zb(t,r,n),t.parseAsync=async(r,n)=>Db(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ub(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(WR(r,n)),t.superRefine=r=>t.check(GR(r)),t.overwrite=r=>t.check(wn(r)),t.optional=()=>Me(t),t.nullable=()=>Bb(t),t.nullish=()=>Me(Bb(t)),t.nonoptional=r=>UR(t,r),t.array=()=>fe(t),t.or=r=>Pe([t,r]),t.and=r=>ta(t,r),t.transform=r=>Fd(t,Jb(r)),t.default=r=>LR(t,r),t.prefault=r=>ZR(t,r),t.catch=r=>FR(t,r),t.pipe=r=>Fd(t,r),t.readonly=()=>HR(t),t.describe=r=>{let n=t.clone();return Cr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Cr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Cr.get(t);let n=t.clone();return Cr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Vb=k("_ZodString",(t,e)=>{ss.init(t,e),Ze.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(yd(...n)),t.includes=(...n)=>t.check(wd(...n)),t.startsWith=(...n)=>t.check(vd(...n)),t.endsWith=(...n)=>t.check(xd(...n)),t.min=(...n)=>t.check(Yn(...n)),t.max=(...n)=>t.check(Gi(...n)),t.length=(...n)=>t.check(Ji(...n)),t.nonempty=(...n)=>t.check(Yn(1,...n)),t.lowercase=n=>t.check(bd(n)),t.uppercase=n=>t.check(_d(n)),t.trim=()=>t.check(kd()),t.normalize=(...n)=>t.check($d(...n)),t.toLowerCase=()=>t.check(Sd()),t.toUpperCase=()=>t.check(Td())}),iR=k("ZodString",(t,e)=>{ss.init(t,e),Vb.init(t,e),t.email=r=>t.check(Bl(aR,r)),t.url=r=>t.check(Gl(cR,r)),t.jwt=r=>t.check(ld($R,r)),t.emoji=r=>t.check(Jl(uR,r)),t.guid=r=>t.check(Vi(qb,r)),t.uuid=r=>t.check(Vl(ea,r)),t.uuidv4=r=>t.check(Hl(ea,r)),t.uuidv6=r=>t.check(Kl(ea,r)),t.uuidv7=r=>t.check(Wl(ea,r)),t.nanoid=r=>t.check(Yl(lR,r)),t.guid=r=>t.check(Vi(qb,r)),t.cuid=r=>t.check(Xl(dR,r)),t.cuid2=r=>t.check(Ql(pR,r)),t.ulid=r=>t.check(ed(fR,r)),t.base64=r=>t.check(ad(wR,r)),t.base64url=r=>t.check(cd(vR,r)),t.xid=r=>t.check(td(hR,r)),t.ksuid=r=>t.check(rd(mR,r)),t.ipv4=r=>t.check(nd(gR,r)),t.ipv6=r=>t.check(od(yR,r)),t.cidrv4=r=>t.check(sd(bR,r)),t.cidrv6=r=>t.check(id(_R,r)),t.e164=r=>t.check(ud(xR,r)),t.datetime=r=>t.check(zd(r)),t.date=r=>t.check(Nd(r)),t.time=r=>t.check(jd(r)),t.duration=r=>t.check(Md(r))});Ne=k("ZodStringFormat",(t,e)=>{Te.init(t,e),Vb.init(t,e)}),aR=k("ZodEmail",(t,e)=>{nl.init(t,e),Ne.init(t,e)}),qb=k("ZodGUID",(t,e)=>{tl.init(t,e),Ne.init(t,e)}),ea=k("ZodUUID",(t,e)=>{rl.init(t,e),Ne.init(t,e)}),cR=k("ZodURL",(t,e)=>{ol.init(t,e),Ne.init(t,e)}),uR=k("ZodEmoji",(t,e)=>{sl.init(t,e),Ne.init(t,e)}),lR=k("ZodNanoID",(t,e)=>{il.init(t,e),Ne.init(t,e)}),dR=k("ZodCUID",(t,e)=>{al.init(t,e),Ne.init(t,e)}),pR=k("ZodCUID2",(t,e)=>{cl.init(t,e),Ne.init(t,e)}),fR=k("ZodULID",(t,e)=>{ul.init(t,e),Ne.init(t,e)}),hR=k("ZodXID",(t,e)=>{ll.init(t,e),Ne.init(t,e)}),mR=k("ZodKSUID",(t,e)=>{dl.init(t,e),Ne.init(t,e)}),gR=k("ZodIPv4",(t,e)=>{pl.init(t,e),Ne.init(t,e)}),yR=k("ZodIPv6",(t,e)=>{fl.init(t,e),Ne.init(t,e)}),bR=k("ZodCIDRv4",(t,e)=>{hl.init(t,e),Ne.init(t,e)}),_R=k("ZodCIDRv6",(t,e)=>{ml.init(t,e),Ne.init(t,e)}),wR=k("ZodBase64",(t,e)=>{gl.init(t,e),Ne.init(t,e)}),vR=k("ZodBase64URL",(t,e)=>{yl.init(t,e),Ne.init(t,e)}),xR=k("ZodE164",(t,e)=>{bl.init(t,e),Ne.init(t,e)}),$R=k("ZodJWT",(t,e)=>{_l.init(t,e),Ne.init(t,e)}),Hb=k("ZodNumber",(t,e)=>{Ui.init(t,e),Ze.init(t,e),t.gt=(n,o)=>t.check(Ki(n,o)),t.gte=(n,o)=>t.check(cs(n,o)),t.min=(n,o)=>t.check(cs(n,o)),t.lt=(n,o)=>t.check(Hi(n,o)),t.lte=(n,o)=>t.check(as(n,o)),t.max=(n,o)=>t.check(as(n,o)),t.int=n=>t.check(Fb(n)),t.safe=n=>t.check(Fb(n)),t.positive=n=>t.check(Ki(0,n)),t.nonnegative=n=>t.check(cs(0,n)),t.negative=n=>t.check(Hi(0,n)),t.nonpositive=n=>t.check(as(0,n)),t.multipleOf=(n,o)=>t.check(Wi(n,o)),t.step=(n,o)=>t.check(Wi(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});kR=k("ZodNumberFormat",(t,e)=>{wl.init(t,e),Hb.init(t,e)});SR=k("ZodBoolean",(t,e)=>{vl.init(t,e),Ze.init(t,e)});TR=k("ZodNull",(t,e)=>{xl.init(t,e),Ze.init(t,e)});ER=k("ZodUnknown",(t,e)=>{$l.init(t,e),Ze.init(t,e)});RR=k("ZodNever",(t,e)=>{kl.init(t,e),Ze.init(t,e)});AR=k("ZodArray",(t,e)=>{Sl.init(t,e),Ze.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Yn(r,n)),t.nonempty=r=>t.check(Yn(1,r)),t.max=(r,n)=>t.check(Gi(r,n)),t.length=(r,n)=>t.check(Ji(r,n)),t.unwrap=()=>t.element});Wb=k("ZodObject",(t,e)=>{qi.init(t,e),Ze.init(t,e),de.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>gt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:je()}),t.loose=()=>t.clone({...t._zod.def,catchall:je()}),t.strict=()=>t.clone({...t._zod.def,catchall:PR()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>de.extend(t,r),t.merge=r=>de.merge(t,r),t.pick=r=>de.pick(t,r),t.omit=r=>de.omit(t,r),t.partial=(...r)=>de.partial(Yb,t,r[0]),t.required=(...r)=>de.required(Xb,t,r[0])});Gb=k("ZodUnion",(t,e)=>{Fi.init(t,e),Ze.init(t,e),t.options=e.options});IR=k("ZodDiscriminatedUnion",(t,e)=>{Gb.init(t,e),Tl.init(t,e)});OR=k("ZodIntersection",(t,e)=>{El.init(t,e),Ze.init(t,e)});CR=k("ZodRecord",(t,e)=>{Rl.init(t,e),Ze.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});qd=k("ZodEnum",(t,e)=>{Pl.init(t,e),Ze.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 qd({...e,checks:[],...de.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 qd({...e,checks:[],...de.normalizeParams(o),entries:s})}});zR=k("ZodLiteral",(t,e)=>{Al.init(t,e),Ze.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]}})});NR=k("ZodTransform",(t,e)=>{Il.init(t,e),Ze.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(de.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(de.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Yb=k("ZodOptional",(t,e)=>{Ol.init(t,e),Ze.init(t,e),t.unwrap=()=>t._zod.def.innerType});jR=k("ZodNullable",(t,e)=>{Cl.init(t,e),Ze.init(t,e),t.unwrap=()=>t._zod.def.innerType});MR=k("ZodDefault",(t,e)=>{zl.init(t,e),Ze.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});DR=k("ZodPrefault",(t,e)=>{Nl.init(t,e),Ze.init(t,e),t.unwrap=()=>t._zod.def.innerType});Xb=k("ZodNonOptional",(t,e)=>{jl.init(t,e),Ze.init(t,e),t.unwrap=()=>t._zod.def.innerType});qR=k("ZodCatch",(t,e)=>{Ml.init(t,e),Ze.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});BR=k("ZodPipe",(t,e)=>{Ll.init(t,e),Ze.init(t,e),t.in=e.in,t.out=e.out});VR=k("ZodReadonly",(t,e)=>{Dl.init(t,e),Ze.init(t,e)});Qb=k("ZodCustom",(t,e)=>{Zl.init(t,e),Ze.init(t,e)})});var t_=E(()=>{});var r_=E(()=>{});var n_=E(()=>{at();Dd();Cd();Zd();Ud();t_();at();fb();Bi();Ld();r_();kt(pb())});var o_=E(()=>{n_()});var s_=E(()=>{o_()});function x_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function $_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Kd,i_,jr,na,We,a_,c_,FZ,XR,QR,Wd,Tt,ps,u_,Qe,zt,Nt,et,oa,l_,Gd,d_,p_,Jd,fs,J,Yd,f_,h_,BZ,sa,eP,ia,tP,hs,eo,m_,rP,nP,oP,sP,iP,aP,Xd,cP,uP,Qd,aa,lP,dP,ca,pP,ms,gs,fP,ys,to,hP,bs,ua,la,da,VZ,pa,fa,ha,g_,y_,b_,ep,__,_s,ro,w_,mP,ma,gP,ga,yP,tp,bP,ya,_P,wP,vP,xP,$P,kP,SP,TP,EP,RP,ba,PP,AP,_a,rp,np,op,IP,OP,CP,sp,zP,NP,jP,MP,LP,v_,wa,DP,va,HZ,ZP,no,UP,KZ,ws,qP,ip,FP,BP,VP,HP,KP,WP,GP,ra,JP,YP,XP,vs,ap,QP,eA,tA,rA,nA,oA,sA,iA,aA,cA,uA,lA,dA,pA,fA,hA,mA,gA,oo,yA,bA,_A,xa,wA,vA,xA,cp,$A,WZ,GZ,JZ,YZ,XZ,QZ,H,Hd,so=E(()=>{s_();Kd="2025-11-25",i_=[Kd,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],jr="io.modelcontextprotocol/related-task",na="2.0",We=e_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),a_=Pe([v(),_e().int()]),c_=v(),FZ=ct({ttl:_e().optional(),pollInterval:_e().optional()}),XR=F({ttl:_e().optional()}),QR=F({taskId:v()}),Wd=ct({progressToken:a_.optional(),[jr]:QR.optional()}),Tt=F({_meta:Wd.optional()}),ps=Tt.extend({task:XR.optional()}),u_=t=>ps.safeParse(t).success,Qe=F({method:v(),params:Tt.loose().optional()}),zt=F({_meta:Wd.optional()}),Nt=F({method:v(),params:zt.loose().optional()}),et=ct({_meta:Wd.optional()}),oa=Pe([v(),_e().int()]),l_=F({jsonrpc:K(na),id:oa,...Qe.shape}).strict(),Gd=t=>l_.safeParse(t).success,d_=F({jsonrpc:K(na),...Nt.shape}).strict(),p_=t=>d_.safeParse(t).success,Jd=F({jsonrpc:K(na),id:oa,result:et}).strict(),fs=t=>Jd.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"})(J||(J={}));Yd=F({jsonrpc:K(na),id:oa.optional(),error:F({code:_e().int(),message:v(),data:je().optional()})}).strict(),f_=t=>Yd.safeParse(t).success,h_=Pe([l_,d_,Jd,Yd]),BZ=Pe([Jd,Yd]),sa=et.strict(),eP=zt.extend({requestId:oa.optional(),reason:v().optional()}),ia=Nt.extend({method:K("notifications/cancelled"),params:eP}),tP=F({src:v(),mimeType:v().optional(),sizes:fe(v()).optional(),theme:gt(["light","dark"]).optional()}),hs=F({icons:fe(tP).optional()}),eo=F({name:v(),title:v().optional()}),m_=eo.extend({...eo.shape,...hs.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),rP=ta(F({applyDefaults:Ge().optional()}),Ee(v(),je())),nP=Vd(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ta(F({form:rP.optional(),url:We.optional()}),Ee(v(),je()).optional())),oP=ct({list:We.optional(),cancel:We.optional(),requests:ct({sampling:ct({createMessage:We.optional()}).optional(),elicitation:ct({create:We.optional()}).optional()}).optional()}),sP=ct({list:We.optional(),cancel:We.optional(),requests:ct({tools:ct({call:We.optional()}).optional()}).optional()}),iP=F({experimental:Ee(v(),We).optional(),sampling:F({context:We.optional(),tools:We.optional()}).optional(),elicitation:nP.optional(),roots:F({listChanged:Ge().optional()}).optional(),tasks:oP.optional(),extensions:Ee(v(),We).optional()}),aP=Tt.extend({protocolVersion:v(),capabilities:iP,clientInfo:m_}),Xd=Qe.extend({method:K("initialize"),params:aP}),cP=F({experimental:Ee(v(),We).optional(),logging:We.optional(),completions:We.optional(),prompts:F({listChanged:Ge().optional()}).optional(),resources:F({subscribe:Ge().optional(),listChanged:Ge().optional()}).optional(),tools:F({listChanged:Ge().optional()}).optional(),tasks:sP.optional(),extensions:Ee(v(),We).optional()}),uP=et.extend({protocolVersion:v(),capabilities:cP,serverInfo:m_,instructions:v().optional()}),Qd=Nt.extend({method:K("notifications/initialized"),params:zt.optional()}),aa=Qe.extend({method:K("ping"),params:Tt.optional()}),lP=F({progress:_e(),total:Me(_e()),message:Me(v())}),dP=F({...zt.shape,...lP.shape,progressToken:a_}),ca=Nt.extend({method:K("notifications/progress"),params:dP}),pP=Tt.extend({cursor:c_.optional()}),ms=Qe.extend({params:pP.optional()}),gs=et.extend({nextCursor:c_.optional()}),fP=gt(["working","input_required","completed","failed","cancelled"]),ys=F({taskId:v(),status:fP,ttl:Pe([_e(),Kb()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:Me(_e()),statusMessage:Me(v())}),to=et.extend({task:ys}),hP=zt.merge(ys),bs=Nt.extend({method:K("notifications/tasks/status"),params:hP}),ua=Qe.extend({method:K("tasks/get"),params:Tt.extend({taskId:v()})}),la=et.merge(ys),da=Qe.extend({method:K("tasks/result"),params:Tt.extend({taskId:v()})}),VZ=et.loose(),pa=ms.extend({method:K("tasks/list")}),fa=gs.extend({tasks:fe(ys)}),ha=Qe.extend({method:K("tasks/cancel"),params:Tt.extend({taskId:v()})}),g_=et.merge(ys),y_=F({uri:v(),mimeType:Me(v()),_meta:Ee(v(),je()).optional()}),b_=y_.extend({text:v()}),ep=v().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),__=y_.extend({blob:ep}),_s=gt(["user","assistant"]),ro=F({audience:fe(_s).optional(),priority:_e().min(0).max(1).optional(),lastModified:ls.datetime({offset:!0}).optional()}),w_=F({...eo.shape,...hs.shape,uri:v(),description:Me(v()),mimeType:Me(v()),size:Me(_e()),annotations:ro.optional(),_meta:Me(ct({}))}),mP=F({...eo.shape,...hs.shape,uriTemplate:v(),description:Me(v()),mimeType:Me(v()),annotations:ro.optional(),_meta:Me(ct({}))}),ma=ms.extend({method:K("resources/list")}),gP=gs.extend({resources:fe(w_)}),ga=ms.extend({method:K("resources/templates/list")}),yP=gs.extend({resourceTemplates:fe(mP)}),tp=Tt.extend({uri:v()}),bP=tp,ya=Qe.extend({method:K("resources/read"),params:bP}),_P=et.extend({contents:fe(Pe([b_,__]))}),wP=Nt.extend({method:K("notifications/resources/list_changed"),params:zt.optional()}),vP=tp,xP=Qe.extend({method:K("resources/subscribe"),params:vP}),$P=tp,kP=Qe.extend({method:K("resources/unsubscribe"),params:$P}),SP=zt.extend({uri:v()}),TP=Nt.extend({method:K("notifications/resources/updated"),params:SP}),EP=F({name:v(),description:Me(v()),required:Me(Ge())}),RP=F({...eo.shape,...hs.shape,description:Me(v()),arguments:Me(fe(EP)),_meta:Me(ct({}))}),ba=ms.extend({method:K("prompts/list")}),PP=gs.extend({prompts:fe(RP)}),AP=Tt.extend({name:v(),arguments:Ee(v(),v()).optional()}),_a=Qe.extend({method:K("prompts/get"),params:AP}),rp=F({type:K("text"),text:v(),annotations:ro.optional(),_meta:Ee(v(),je()).optional()}),np=F({type:K("image"),data:ep,mimeType:v(),annotations:ro.optional(),_meta:Ee(v(),je()).optional()}),op=F({type:K("audio"),data:ep,mimeType:v(),annotations:ro.optional(),_meta:Ee(v(),je()).optional()}),IP=F({type:K("tool_use"),name:v(),id:v(),input:Ee(v(),je()),_meta:Ee(v(),je()).optional()}),OP=F({type:K("resource"),resource:Pe([b_,__]),annotations:ro.optional(),_meta:Ee(v(),je()).optional()}),CP=w_.extend({type:K("resource_link")}),sp=Pe([rp,np,op,CP,OP]),zP=F({role:_s,content:sp}),NP=et.extend({description:v().optional(),messages:fe(zP)}),jP=Nt.extend({method:K("notifications/prompts/list_changed"),params:zt.optional()}),MP=F({title:v().optional(),readOnlyHint:Ge().optional(),destructiveHint:Ge().optional(),idempotentHint:Ge().optional(),openWorldHint:Ge().optional()}),LP=F({taskSupport:gt(["required","optional","forbidden"]).optional()}),v_=F({...eo.shape,...hs.shape,description:v().optional(),inputSchema:F({type:K("object"),properties:Ee(v(),We).optional(),required:fe(v()).optional()}).catchall(je()),outputSchema:F({type:K("object"),properties:Ee(v(),We).optional(),required:fe(v()).optional()}).catchall(je()).optional(),annotations:MP.optional(),execution:LP.optional(),_meta:Ee(v(),je()).optional()}),wa=ms.extend({method:K("tools/list")}),DP=gs.extend({tools:fe(v_)}),va=et.extend({content:fe(sp).default([]),structuredContent:Ee(v(),je()).optional(),isError:Ge().optional()}),HZ=va.or(et.extend({toolResult:je()})),ZP=ps.extend({name:v(),arguments:Ee(v(),je()).optional()}),no=Qe.extend({method:K("tools/call"),params:ZP}),UP=Nt.extend({method:K("notifications/tools/list_changed"),params:zt.optional()}),KZ=F({autoRefresh:Ge().default(!0),debounceMs:_e().int().nonnegative().default(300)}),ws=gt(["debug","info","notice","warning","error","critical","alert","emergency"]),qP=Tt.extend({level:ws}),ip=Qe.extend({method:K("logging/setLevel"),params:qP}),FP=zt.extend({level:ws,logger:v().optional(),data:je()}),BP=Nt.extend({method:K("notifications/message"),params:FP}),VP=F({name:v().optional()}),HP=F({hints:fe(VP).optional(),costPriority:_e().min(0).max(1).optional(),speedPriority:_e().min(0).max(1).optional(),intelligencePriority:_e().min(0).max(1).optional()}),KP=F({mode:gt(["auto","required","none"]).optional()}),WP=F({type:K("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:fe(sp).default([]),structuredContent:F({}).loose().optional(),isError:Ge().optional(),_meta:Ee(v(),je()).optional()}),GP=Bd("type",[rp,np,op]),ra=Bd("type",[rp,np,op,IP,WP]),JP=F({role:_s,content:Pe([ra,fe(ra)]),_meta:Ee(v(),je()).optional()}),YP=ps.extend({messages:fe(JP),modelPreferences:HP.optional(),systemPrompt:v().optional(),includeContext:gt(["none","thisServer","allServers"]).optional(),temperature:_e().optional(),maxTokens:_e().int(),stopSequences:fe(v()).optional(),metadata:We.optional(),tools:fe(v_).optional(),toolChoice:KP.optional()}),XP=Qe.extend({method:K("sampling/createMessage"),params:YP}),vs=et.extend({model:v(),stopReason:Me(gt(["endTurn","stopSequence","maxTokens"]).or(v())),role:_s,content:GP}),ap=et.extend({model:v(),stopReason:Me(gt(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:_s,content:Pe([ra,fe(ra)])}),QP=F({type:K("boolean"),title:v().optional(),description:v().optional(),default:Ge().optional()}),eA=F({type:K("string"),title:v().optional(),description:v().optional(),minLength:_e().optional(),maxLength:_e().optional(),format:gt(["email","uri","date","date-time"]).optional(),default:v().optional()}),tA=F({type:gt(["number","integer"]),title:v().optional(),description:v().optional(),minimum:_e().optional(),maximum:_e().optional(),default:_e().optional()}),rA=F({type:K("string"),title:v().optional(),description:v().optional(),enum:fe(v()),default:v().optional()}),nA=F({type:K("string"),title:v().optional(),description:v().optional(),oneOf:fe(F({const:v(),title:v()})),default:v().optional()}),oA=F({type:K("string"),title:v().optional(),description:v().optional(),enum:fe(v()),enumNames:fe(v()).optional(),default:v().optional()}),sA=Pe([rA,nA]),iA=F({type:K("array"),title:v().optional(),description:v().optional(),minItems:_e().optional(),maxItems:_e().optional(),items:F({type:K("string"),enum:fe(v())}),default:fe(v()).optional()}),aA=F({type:K("array"),title:v().optional(),description:v().optional(),minItems:_e().optional(),maxItems:_e().optional(),items:F({anyOf:fe(F({const:v(),title:v()}))}),default:fe(v()).optional()}),cA=Pe([iA,aA]),uA=Pe([oA,sA,cA]),lA=Pe([uA,QP,eA,tA]),dA=ps.extend({mode:K("form").optional(),message:v(),requestedSchema:F({type:K("object"),properties:Ee(v(),lA),required:fe(v()).optional()})}),pA=ps.extend({mode:K("url"),message:v(),elicitationId:v(),url:v().url()}),fA=Pe([dA,pA]),hA=Qe.extend({method:K("elicitation/create"),params:fA}),mA=zt.extend({elicitationId:v()}),gA=Nt.extend({method:K("notifications/elicitation/complete"),params:mA}),oo=et.extend({action:gt(["accept","decline","cancel"]),content:Vd(t=>t===null?void 0:t,Ee(v(),Pe([v(),_e(),Ge(),fe(v())])).optional())}),yA=F({type:K("ref/resource"),uri:v()}),bA=F({type:K("ref/prompt"),name:v()}),_A=Tt.extend({ref:Pe([bA,yA]),argument:F({name:v(),value:v()}),context:F({arguments:Ee(v(),v()).optional()}).optional()}),xa=Qe.extend({method:K("completion/complete"),params:_A});wA=et.extend({completion:ct({values:fe(v()).max(100),total:Me(_e().int()),hasMore:Me(Ge())})}),vA=F({uri:v().startsWith("file://"),name:v().optional(),_meta:Ee(v(),je()).optional()}),xA=Qe.extend({method:K("roots/list"),params:Tt.optional()}),cp=et.extend({roots:fe(vA)}),$A=Nt.extend({method:K("notifications/roots/list_changed"),params:zt.optional()}),WZ=Pe([aa,Xd,xa,ip,_a,ba,ma,ga,ya,xP,kP,no,wa,ua,da,pa,ha]),GZ=Pe([ia,ca,Qd,$A,bs]),JZ=Pe([sa,vs,ap,oo,cp,la,fa,to]),YZ=Pe([aa,XP,hA,xA,ua,da,pa,ha]),XZ=Pe([ia,ca,BP,TP,wP,UP,jP,bs,gA]),QZ=Pe([sa,uP,wA,NP,PP,gP,yP,_P,va,DP,la,fa,to]),H=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===J.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Hd(o.elicitations,r)}return new t(e,r,n)}},Hd=class extends H{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(J.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Mr(t){return t==="completed"||t==="failed"||t==="cancelled"}var k_=E(()=>{});var T_,S_,E_,$a=E(()=>{T_=Symbol("Let zodToJsonSchema decide on which parser to use"),S_={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"},E_=t=>typeof t=="string"?{...S_,name:t}:{...S_,...t}});var R_,up=E(()=>{$a();R_=t=>{let e=E_(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 lp(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function he(t,e,r,n,o){t[e]=r,lp(t,e,n,o)}var Lr=E(()=>{});var ka,Sa=E(()=>{ka=(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 Le(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ka(e,t.currentPath):e.join("/")}}var jt=E(()=>{Sa()});function P_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==N.ZodAny&&(r.items=Q(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&he(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&he(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(he(r,"minItems",t.exactLength.value,t.exactLength.message,e),he(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var dp=E(()=>{Jo();Lr();Be()});function A_(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?he(r,"minimum",n.value,n.message,e):he(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),he(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?he(r,"maximum",n.value,n.message,e):he(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),he(r,"maximum",n.value,n.message,e));break;case"multipleOf":he(r,"multipleOf",n.value,n.message,e);break}return r}var pp=E(()=>{Lr()});function I_(){return{type:"boolean"}}var fp=E(()=>{});function Ta(t,e){return Q(t.type._def,e)}var Ea=E(()=>{Be()});var O_,hp=E(()=>{Be();O_=(t,e)=>Q(t.innerType._def,e)});function mp(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>mp(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 kA(t,e)}}var kA,gp=E(()=>{Lr();kA=(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":he(r,"minimum",n.value,n.message,e);break;case"max":he(r,"maximum",n.value,n.message,e);break}return r}});function C_(t,e){return{...Q(t.innerType._def,e),default:t.defaultValue()}}var yp=E(()=>{Be()});function z_(t,e){return e.effectStrategy==="input"?Q(t.schema._def,e):Le(e)}var bp=E(()=>{Be();jt()});function N_(t){return{type:"string",enum:Array.from(t.values)}}var _p=E(()=>{});function j_(t,e){let r=[Q(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Q(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(SA(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 SA,wp=E(()=>{Be();SA=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function M_(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 vp=E(()=>{});function Ra(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":he(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":he(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":Vt(r,"email",n.message,e);break;case"format:idn-email":Vt(r,"idn-email",n.message,e);break;case"pattern:zod":ut(r,Bt.email,n.message,e);break}break;case"url":Vt(r,"uri",n.message,e);break;case"uuid":Vt(r,"uuid",n.message,e);break;case"regex":ut(r,n.regex,n.message,e);break;case"cuid":ut(r,Bt.cuid,n.message,e);break;case"cuid2":ut(r,Bt.cuid2,n.message,e);break;case"startsWith":ut(r,RegExp(`^${$p(n.value,e)}`),n.message,e);break;case"endsWith":ut(r,RegExp(`${$p(n.value,e)}$`),n.message,e);break;case"datetime":Vt(r,"date-time",n.message,e);break;case"date":Vt(r,"date",n.message,e);break;case"time":Vt(r,"time",n.message,e);break;case"duration":Vt(r,"duration",n.message,e);break;case"length":he(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),he(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ut(r,RegExp($p(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Vt(r,"ipv4",n.message,e),n.version!=="v4"&&Vt(r,"ipv6",n.message,e);break}case"base64url":ut(r,Bt.base64url,n.message,e);break;case"jwt":ut(r,Bt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ut(r,Bt.ipv4Cidr,n.message,e),n.version!=="v4"&&ut(r,Bt.ipv6Cidr,n.message,e);break}case"emoji":ut(r,Bt.emoji(),n.message,e);break;case"ulid":{ut(r,Bt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Vt(r,"binary",n.message,e);break}case"contentEncoding:base64":{he(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ut(r,Bt.base64,n.message,e);break}}break}case"nanoid":ut(r,Bt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function $p(t,e){return e.patternStrategy==="escape"?EA(t):t}function EA(t){let e="";for(let r=0;r<t.length;r++)TA.has(t[r])||(e+="\\"),e+=t[r];return e}function Vt(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}}})):he(t,"format",e,r,n)}function ut(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:L_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):he(t,"pattern",L_(e,n),r,n)}function L_(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
|
|
927
|
+
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
928
|
+
]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
|
|
929
|
+
`:`[${n[c]}\r
|
|
930
|
+
]`;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 xp,Bt,TA,Pa=E(()=>{Lr();Bt={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:()=>(xp===void 0&&(xp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),xp),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-_]*$/};TA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Aa(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===N.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Le(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===N.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ra(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===N.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===N.ZodBranded&&t.keyType._def.type._def.typeName===N.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ta(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Ia=E(()=>{Jo();Be();Pa();Ea();jt()});function D_(t,e){if(e.mapStrategy==="record")return Aa(t,e);let r=Q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Le(e),n=Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Le(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var kp=E(()=>{Be();Ia();jt()});function Z_(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 Sp=E(()=>{});function U_(t){return t.target==="openAi"?void 0:{not:Le({...t,currentPath:[...t.currentPath,"not"]})}}var Tp=E(()=>{jt()});function q_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ep=E(()=>{});function B_(t,e){if(e.target==="openApi3")return F_(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 F_(t,e)}var xs,F_,Oa=E(()=>{Be();xs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};F_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Q(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 V_(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=Q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Rp=E(()=>{Be();Oa()});function H_(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",lp(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?he(r,"minimum",n.value,n.message,e):he(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),he(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?he(r,"maximum",n.value,n.message,e):he(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),he(r,"maximum",n.value,n.message,e));break;case"multipleOf":he(r,"multipleOf",n.value,n.message,e);break}return r}var Pp=E(()=>{Lr()});function K_(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 u=PA(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=Q(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||o.push(a))}o.length&&(n.required=o);let i=RA(t,e);return i!==void 0&&(n.additionalProperties=i),n}function RA(t,e){if(t.catchall._def.typeName!=="ZodNever")return Q(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 PA(t){try{return t.isOptional()}catch{return!0}}var Ap=E(()=>{Be()});var W_,Ip=E(()=>{Be();jt();W_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Q(t.innerType._def,e);let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Le(e)},r]}:Le(e)}});var G_,Op=E(()=>{Be();G_=(t,e)=>{if(e.pipeStrategy==="input")return Q(t.in._def,e);if(e.pipeStrategy==="output")return Q(t.out._def,e);let r=Q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function J_(t,e){return Q(t.type._def,e)}var Cp=E(()=>{Be()});function Y_(t,e){let n={type:"array",uniqueItems:!0,items:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&he(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&he(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var zp=E(()=>{Lr();Be()});function X_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Np=E(()=>{Be()});function Q_(t){return{not:Le(t)}}var jp=E(()=>{jt()});function ew(t){return Le(t)}var Mp=E(()=>{jt()});var tw,Lp=E(()=>{Be();tw=(t,e)=>Q(t.innerType._def,e)});var rw,Dp=E(()=>{Jo();jt();dp();pp();fp();Ea();hp();gp();yp();bp();_p();wp();vp();kp();Sp();Tp();Ep();Rp();Pp();Ap();Ip();Op();Cp();Ia();zp();Pa();Np();jp();Oa();Mp();Lp();rw=(t,e,r)=>{switch(e){case N.ZodString:return Ra(t,r);case N.ZodNumber:return H_(t,r);case N.ZodObject:return K_(t,r);case N.ZodBigInt:return A_(t,r);case N.ZodBoolean:return I_();case N.ZodDate:return mp(t,r);case N.ZodUndefined:return Q_(r);case N.ZodNull:return q_(r);case N.ZodArray:return P_(t,r);case N.ZodUnion:case N.ZodDiscriminatedUnion:return B_(t,r);case N.ZodIntersection:return j_(t,r);case N.ZodTuple:return X_(t,r);case N.ZodRecord:return Aa(t,r);case N.ZodLiteral:return M_(t,r);case N.ZodEnum:return N_(t);case N.ZodNativeEnum:return Z_(t);case N.ZodNullable:return V_(t,r);case N.ZodOptional:return W_(t,r);case N.ZodMap:return D_(t,r);case N.ZodSet:return Y_(t,r);case N.ZodLazy:return()=>t.getter()._def;case N.ZodPromise:return J_(t,r);case N.ZodNaN:case N.ZodNever:return U_(r);case N.ZodEffects:return z_(t,r);case N.ZodAny:return Le(r);case N.ZodUnknown:return ew(r);case N.ZodDefault:return C_(t,r);case N.ZodBranded:return Ta(t,r);case N.ZodReadonly:return tw(t,r);case N.ZodCatch:return O_(t,r);case N.ZodPipeline:return G_(t,r);case N.ZodFunction:case N.ZodVoid:case N.ZodSymbol:return;default:return(n=>{})(e)}}});function Q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==T_)return a}if(n&&!r){let a=AA(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=rw(t,t.typeName,e),i=typeof s=="function"?Q(s(),e):s;if(i&&IA(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var AA,IA,Be=E(()=>{$a();Dp();Sa();jt();AA=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ka(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`),Le(e)):e.$refStrategy==="seen"?Le(e):void 0}},IA=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var nw=E(()=>{});var Zp,Up=E(()=>{Be();up();jt();Zp=(t,e)=>{let r=R_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:Q(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Le(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Q(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Le(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 ow=E(()=>{$a();up();Lr();Sa();Be();nw();jt();dp();pp();fp();Ea();hp();gp();yp();bp();_p();wp();vp();kp();Sp();Tp();Ep();Rp();Pp();Ap();Ip();Op();Cp();Lp();Ia();zp();Pa();Np();jp();Oa();Mp();Dp();Up();Up()});function OA(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function qp(t,e){return nr(t)?Pd(t,{target:OA(e?.target),io:e?.pipeStrategy??"input"}):Zp(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Fp(t){let r=Nr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Qn(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Bp(t,e){let r=zr(t,e);if(!r.success)throw r.error;return r.data}var Vp=E(()=>{Od();us();ow()});function sw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function iw(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];sw(i)&&sw(s)?r[o]={...i,...s}:r[o]=s}return r}var CA,Ca,aw=E(()=>{us();so();k_();Vp();CA=6e4,Ca=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(ia,r=>{this._oncancel(r)}),this.setNotificationHandler(ca,r=>{this._onprogress(r)}),this.setRequestHandler(aa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ua,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(J.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(da,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,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,f=new H(l.error.code,l.error.message,l.error.data);d(f)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new H(J.InvalidParams,`Task not found: ${s}`);if(!Mr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Mr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[jr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(pa,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 H(J.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ha,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(J.InvalidParams,`Task not found: ${r.params.taskId}`);if(Mr(o.status))throw new H(J.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 H(J.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof H?o:new H(J.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),H.fromError(J.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),fs(s)||f_(s)?this._onresponse(s):Gd(s)?this._onrequest(s,i):p_(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=H.fromError(J.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?.[jr]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:J.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):o?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=u_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,f)=>{if(i.signal.aborted)throw new H(J.ConnectionClosed,"Request was cancelled");let h={...f,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let p=h.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,h)},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,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:J.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).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),fs(e))n(e);else{let i=new H(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(fs(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),fs(e))o(e);else{let i=H.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 H?i:new H(J.InternalError,String(i))}}return}let s;try{let i=await this.request(e,to,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new H(J.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Mr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new H(J.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new H(J.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(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof H?i:new H(J.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=R=>{d(R)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(R){l(R);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[jr]:c}});let p=R=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(R)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(B=>this._onerror(new Error(`Failed to send cancellation: ${B}`)));let C=R instanceof H?R:new H(J.RequestTimeout,String(R));d(C)};this._responseHandlers.set(f,R=>{if(!n?.signal?.aborted){if(R instanceof Error)return d(R);try{let C=zr(r,R.result);C.success?u(C.data):d(C.error)}catch(C){d(C)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let m=n?.timeout??CA,b=()=>p(H.fromError(J.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,b,n?.resetTimeoutOnProgress??!1);let S=c?.taskId;if(S){let R=C=>{let B=this._responseHandlers.get(f);B?B(C):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,R),this._enqueueTaskMessage(S,{type:"request",message:h,timestamp:Date.now()}).catch(C=>{this._cleanupTimeout(f),d(C)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(R=>{this._cleanupTimeout(f),d(R)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},la,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},fa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},g_,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||{},[jr]: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||{},[jr]: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||{},[jr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Fp(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Bp(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=Fp(e);this._notificationHandlers.set(n,o=>{let s=Bp(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"&&Gd(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new H(J.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 H(J.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new H(J.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 H(J.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=bs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Mr(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 H(J.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Mr(a.status))throw new H(J.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 u=bs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Mr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Ss=Z(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.regexpCode=be.getEsmExportName=be.getProperty=be.safeStringify=be.stringify=be.strConcat=be.addCodeArg=be.str=be._=be.nil=be._Code=be.Name=be.IDENTIFIER=be._CodeOrName=void 0;var $s=class{};be._CodeOrName=$s;be.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var $n=class extends $s{constructor(e){if(super(),!be.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}}};be.Name=$n;var Mt=class extends $s{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 $n&&(r[n.str]=(r[n.str]||0)+1),r),{})}};be._Code=Mt;be.nil=new Mt("");function cw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Kp(r,e[n]),r.push(t[++n]);return new Mt(r)}be._=cw;var Hp=new Mt("+");function uw(t,...e){let r=[ks(t[0])],n=0;for(;n<e.length;)r.push(Hp),Kp(r,e[n]),r.push(Hp,ks(t[++n]));return zA(r),new Mt(r)}be.str=uw;function Kp(t,e){e instanceof Mt?t.push(...e._items):e instanceof $n?t.push(e):t.push(MA(e))}be.addCodeArg=Kp;function zA(t){let e=1;for(;e<t.length-1;){if(t[e]===Hp){let r=NA(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function NA(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof $n||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 $n))return`"${t}${e.slice(1)}`}function jA(t,e){return e.emptyStr()?t:t.emptyStr()?e:uw`${t}${e}`}be.strConcat=jA;function MA(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ks(Array.isArray(t)?t.join(","):t)}function LA(t){return new Mt(ks(t))}be.stringify=LA;function ks(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}be.safeStringify=ks;function DA(t){return typeof t=="string"&&be.IDENTIFIER.test(t)?new Mt(`.${t}`):cw`[${t}]`}be.getProperty=DA;function ZA(t){if(typeof t=="string"&&be.IDENTIFIER.test(t))return new Mt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}be.getEsmExportName=ZA;function UA(t){return new Mt(t.toString())}be.regexpCode=UA});var Jp=Z(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.ValueScope=bt.ValueScopeName=bt.Scope=bt.varKinds=bt.UsedValueState=void 0;var yt=Ss(),Wp=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},za;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(za||(bt.UsedValueState=za={}));bt.varKinds={const:new yt.Name("const"),let:new yt.Name("let"),var:new yt.Name("var")};var Na=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof yt.Name?e:this.name(e)}name(e){return new yt.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}}};bt.Scope=Na;var ja=class extends yt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,yt._)`.${new yt.Name(r)}[${n}]`}};bt.ValueScopeName=ja;var qA=(0,yt._)`\n`,Gp=class extends Na{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?qA:yt.nil}}get(){return this._scope}name(e){return new ja(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 d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),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,yt._)`${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=yt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,za.Started);let d=r(u);if(d){let l=this.opts.es5?bt.varKinds.var:bt.varKinds.const;s=(0,yt._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,yt._)`${s}${d}${this.opts._n}`;else throw new Wp(u);c.set(u,za.Completed)})}return s}};bt.ValueScope=Gp});var se=Z(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.or=ie.and=ie.not=ie.CodeGen=ie.operators=ie.varKinds=ie.ValueScopeName=ie.ValueScope=ie.Scope=ie.Name=ie.regexpCode=ie.stringify=ie.getProperty=ie.nil=ie.strConcat=ie.str=ie._=void 0;var me=Ss(),Ht=Jp(),Dr=Ss();Object.defineProperty(ie,"_",{enumerable:!0,get:function(){return Dr._}});Object.defineProperty(ie,"str",{enumerable:!0,get:function(){return Dr.str}});Object.defineProperty(ie,"strConcat",{enumerable:!0,get:function(){return Dr.strConcat}});Object.defineProperty(ie,"nil",{enumerable:!0,get:function(){return Dr.nil}});Object.defineProperty(ie,"getProperty",{enumerable:!0,get:function(){return Dr.getProperty}});Object.defineProperty(ie,"stringify",{enumerable:!0,get:function(){return Dr.stringify}});Object.defineProperty(ie,"regexpCode",{enumerable:!0,get:function(){return Dr.regexpCode}});Object.defineProperty(ie,"Name",{enumerable:!0,get:function(){return Dr.Name}});var Za=Jp();Object.defineProperty(ie,"Scope",{enumerable:!0,get:function(){return Za.Scope}});Object.defineProperty(ie,"ValueScope",{enumerable:!0,get:function(){return Za.ValueScope}});Object.defineProperty(ie,"ValueScopeName",{enumerable:!0,get:function(){return Za.ValueScopeName}});Object.defineProperty(ie,"varKinds",{enumerable:!0,get:function(){return Za.varKinds}});ie.operators={GT:new me._Code(">"),GTE:new me._Code(">="),LT:new me._Code("<"),LTE:new me._Code("<="),EQ:new me._Code("==="),NEQ:new me._Code("!=="),NOT:new me._Code("!"),OR:new me._Code("||"),AND:new me._Code("&&"),ADD:new me._Code("+")};var yr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Yp=class extends yr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Ht.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=ao(this.rhs,e,r)),this}get names(){return this.rhs instanceof me._CodeOrName?this.rhs.names:{}}},Ma=class extends yr{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 me.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ao(this.rhs,e,r),this}get names(){let e=this.lhs instanceof me.Name?{}:{...this.lhs.names};return Da(e,this.rhs)}},Xp=class extends Ma{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Qp=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ef=class extends yr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},tf=class extends yr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},rf=class extends yr{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=ao(this.code,e,r),this}get names(){return this.code instanceof me._CodeOrName?this.code.names:{}}},Ts=class extends yr{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)||(FA(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Tn(e,r.names),{})}},br=class extends Ts{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},nf=class extends Ts{},io=class extends br{};io.kind="else";var kn=class t extends br{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 io(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(lw(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=ao(this.condition,e,r),this}get names(){let e=super.names;return Da(e,this.condition),this.else&&Tn(e,this.else.names),e}};kn.kind="if";var Sn=class extends br{};Sn.kind="for";var of=class extends Sn{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=ao(this.iteration,e,r),this}get names(){return Tn(super.names,this.iteration.names)}},sf=class extends Sn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Ht.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=Da(super.names,this.from);return Da(e,this.to)}},La=class extends Sn{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=ao(this.iterable,e,r),this}get names(){return Tn(super.names,this.iterable.names)}},Es=class extends br{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)}};Es.kind="func";var Rs=class extends Ts{render(e){return"return "+super.render(e)}};Rs.kind="return";var af=class extends br{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&&Tn(e,this.catch.names),this.finally&&Tn(e,this.finally.names),e}},Ps=class extends br{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ps.kind="catch";var As=class extends br{render(e){return"finally"+super.render(e)}};As.kind="finally";var cf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
931
|
+
`:""},this._extScope=e,this._scope=new Ht.Scope({parent:e}),this._nodes=[new nf]}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 Yp(e,s,n)),s}const(e,r,n){return this._def(Ht.varKinds.const,e,r,n)}let(e,r,n){return this._def(Ht.varKinds.let,e,r,n)}var(e,r,n){return this._def(Ht.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ma(e,r,n))}add(e,r){return this._leafNode(new Xp(e,ie.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==me.nil&&this._leafNode(new rf(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,me.addCodeArg)(r,o));return r.push("}"),new me._Code(r)}if(e,r,n){if(this._blockNode(new kn(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 kn(e))}else(){return this._elseNode(new io)}endIf(){return this._endBlockNode(kn,io)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new of(e),r)}forRange(e,r,n,o,s=this.opts.es5?Ht.varKinds.var:Ht.varKinds.let){let i=this._scope.toName(e);return this._for(new sf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Ht.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof me.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,me._)`${i}.length`,a=>{this.var(s,(0,me._)`${i}[${a}]`),n(s)})}return this._for(new La("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Ht.varKinds.var:Ht.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,me._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new La("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Sn)}label(e){return this._leafNode(new Qp(e))}break(e){return this._leafNode(new ef(e))}return(e){let r=new Rs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Rs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new af;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Ps(s),r(s)}return n&&(this._currNode=o.finally=new As,this.code(n)),this._endBlockNode(Ps,As)}throw(e){return this._leafNode(new tf(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=me.nil,n,o){return this._blockNode(new Es(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Es)}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 kn))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}};ie.CodeGen=cf;function Tn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Da(t,e){return e instanceof me._CodeOrName?Tn(t,e.names):t}function ao(t,e,r){if(t instanceof me.Name)return n(t);if(!o(t))return t;return new me._Code(t._items.reduce((s,i)=>(i instanceof me.Name&&(i=n(i)),i instanceof me._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 me._Code&&s._items.some(i=>i instanceof me.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function FA(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function lw(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,me._)`!${uf(t)}`}ie.not=lw;var BA=dw(ie.operators.AND);function VA(...t){return t.reduce(BA)}ie.and=VA;var HA=dw(ie.operators.OR);function KA(...t){return t.reduce(HA)}ie.or=KA;function dw(t){return(e,r)=>e===me.nil?r:r===me.nil?e:(0,me._)`${uf(e)} ${t} ${uf(r)}`}function uf(t){return t instanceof me.Name?t:(0,me._)`(${t})`}});var ge=Z(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.checkStrictMode=ce.getErrorPath=ce.Type=ce.useFunc=ce.setEvaluated=ce.evaluatedPropsToName=ce.mergeEvaluated=ce.eachItem=ce.unescapeJsonPointer=ce.escapeJsonPointer=ce.escapeFragment=ce.unescapeFragment=ce.schemaRefOrVal=ce.schemaHasRulesButRef=ce.schemaHasRules=ce.checkUnknownRules=ce.alwaysValidSchema=ce.toHash=void 0;var ke=se(),WA=Ss();function GA(t){let e={};for(let r of t)e[r]=!0;return e}ce.toHash=GA;function JA(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(hw(t,e),!mw(e,t.self.RULES.all))}ce.alwaysValidSchema=JA;function hw(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]||bw(t,`unknown keyword: "${s}"`)}ce.checkUnknownRules=hw;function mw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ce.schemaHasRules=mw;function YA(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ce.schemaHasRulesButRef=YA;function XA({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ke._)`${r}`}return(0,ke._)`${t}${e}${(0,ke.getProperty)(n)}`}ce.schemaRefOrVal=XA;function QA(t){return gw(decodeURIComponent(t))}ce.unescapeFragment=QA;function eI(t){return encodeURIComponent(df(t))}ce.escapeFragment=eI;function df(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ce.escapeJsonPointer=df;function gw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ce.unescapeJsonPointer=gw;function tI(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ce.eachItem=tI;function pw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof ke.Name?(s instanceof ke.Name?t(o,s,i):e(o,s,i),i):s instanceof ke.Name?(e(o,i,s),s):r(s,i);return a===ke.Name&&!(c instanceof ke.Name)?n(o,c):c}}ce.mergeEvaluated={props:pw({mergeNames:(t,e,r)=>t.if((0,ke._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ke._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ke._)`${r} || {}`).code((0,ke._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ke._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ke._)`${r} || {}`),pf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:yw}),items:pw({mergeNames:(t,e,r)=>t.if((0,ke._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ke._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ke._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ke._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function yw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ke._)`{}`);return e!==void 0&&pf(t,r,e),r}ce.evaluatedPropsToName=yw;function pf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ke._)`${e}${(0,ke.getProperty)(n)}`,!0))}ce.setEvaluated=pf;var fw={};function rI(t,e){return t.scopeValue("func",{ref:e,code:fw[e.code]||(fw[e.code]=new WA._Code(e.code))})}ce.useFunc=rI;var lf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(lf||(ce.Type=lf={}));function nI(t,e,r){if(t instanceof ke.Name){let n=e===lf.Num;return r?n?(0,ke._)`"[" + ${t} + "]"`:(0,ke._)`"['" + ${t} + "']"`:n?(0,ke._)`"/" + ${t}`:(0,ke._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ke.getProperty)(t).toString():"/"+df(t)}ce.getErrorPath=nI;function bw(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ce.checkStrictMode=bw});var _r=Z(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var ot=se(),oI={data:new ot.Name("data"),valCxt:new ot.Name("valCxt"),instancePath:new ot.Name("instancePath"),parentData:new ot.Name("parentData"),parentDataProperty:new ot.Name("parentDataProperty"),rootData:new ot.Name("rootData"),dynamicAnchors:new ot.Name("dynamicAnchors"),vErrors:new ot.Name("vErrors"),errors:new ot.Name("errors"),this:new ot.Name("this"),self:new ot.Name("self"),scope:new ot.Name("scope"),json:new ot.Name("json"),jsonPos:new ot.Name("jsonPos"),jsonLen:new ot.Name("jsonLen"),jsonPart:new ot.Name("jsonPart")};ff.default=oI});var Is=Z(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.extendErrors=st.resetErrorsCount=st.reportExtraError=st.reportError=st.keyword$DataError=st.keywordError=void 0;var ye=se(),Ua=ge(),lt=_r();st.keywordError={message:({keyword:t})=>(0,ye.str)`must pass "${t}" keyword validation`};st.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ye.str)`"${t}" keyword must be ${e} ($data)`:(0,ye.str)`"${t}" keyword is invalid ($data)`};function sI(t,e=st.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=vw(t,e,r);n??(i||a)?_w(s,c):ww(o,(0,ye._)`[${c}]`)}st.reportError=sI;function iI(t,e=st.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=vw(t,e,r);_w(o,a),s||i||ww(n,lt.default.vErrors)}st.reportExtraError=iI;function aI(t,e){t.assign(lt.default.errors,e),t.if((0,ye._)`${lt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ye._)`${lt.default.vErrors}.length`,e),()=>t.assign(lt.default.vErrors,null)))}st.resetErrorsCount=aI;function cI({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,lt.default.errors,a=>{t.const(i,(0,ye._)`${lt.default.vErrors}[${a}]`),t.if((0,ye._)`${i}.instancePath === undefined`,()=>t.assign((0,ye._)`${i}.instancePath`,(0,ye.strConcat)(lt.default.instancePath,s.errorPath))),t.assign((0,ye._)`${i}.schemaPath`,(0,ye.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ye._)`${i}.schema`,r),t.assign((0,ye._)`${i}.data`,n))})}st.extendErrors=cI;function _w(t,e){let r=t.const("err",e);t.if((0,ye._)`${lt.default.vErrors} === null`,()=>t.assign(lt.default.vErrors,(0,ye._)`[${r}]`),(0,ye._)`${lt.default.vErrors}.push(${r})`),t.code((0,ye._)`${lt.default.errors}++`)}function ww(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ye._)`new ${t.ValidationError}(${e})`):(r.assign((0,ye._)`${n}.errors`,e),r.return(!1))}var En={keyword:new ye.Name("keyword"),schemaPath:new ye.Name("schemaPath"),params:new ye.Name("params"),propertyName:new ye.Name("propertyName"),message:new ye.Name("message"),schema:new ye.Name("schema"),parentSchema:new ye.Name("parentSchema")};function vw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ye._)`{}`:uI(t,e,r)}function uI(t,e,r={}){let{gen:n,it:o}=t,s=[lI(o,r),dI(t,r)];return pI(t,e,s),n.object(...s)}function lI({errorPath:t},{instancePath:e}){let r=e?(0,ye.str)`${t}${(0,Ua.getErrorPath)(e,Ua.Type.Str)}`:t;return[lt.default.instancePath,(0,ye.strConcat)(lt.default.instancePath,r)]}function dI({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ye.str)`${e}/${t}`;return r&&(o=(0,ye.str)`${o}${(0,Ua.getErrorPath)(r,Ua.Type.Str)}`),[En.schemaPath,o]}function pI(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([En.keyword,o],[En.params,typeof e=="function"?e(t):e||(0,ye._)`{}`]),c.messages&&n.push([En.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([En.schema,i],[En.parentSchema,(0,ye._)`${d}${l}`],[lt.default.data,s]),u&&n.push([En.propertyName,u])}});var $w=Z(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.boolOrEmptySchema=co.topBoolOrEmptySchema=void 0;var fI=Is(),hI=se(),mI=_r(),gI={message:"boolean schema is false"};function yI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?xw(t,!1):typeof r=="object"&&r.$async===!0?e.return(mI.default.data):(e.assign((0,hI._)`${n}.errors`,null),e.return(!0))}co.topBoolOrEmptySchema=yI;function bI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),xw(t)):r.var(e,!0)}co.boolOrEmptySchema=bI;function xw(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,fI.reportError)(o,gI,void 0,e)}});var hf=Z(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.getRules=uo.isJSONType=void 0;var _I=["string","number","integer","boolean","null","object","array"],wI=new Set(_I);function vI(t){return typeof t=="string"&&wI.has(t)}uo.isJSONType=vI;function xI(){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=xI});var mf=Z(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.shouldUseRule=Zr.shouldUseGroup=Zr.schemaHasRulesForType=void 0;function $I({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&kw(t,n)}Zr.schemaHasRulesForType=$I;function kw(t,e){return e.rules.some(r=>Sw(t,r))}Zr.shouldUseGroup=kw;function Sw(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))}Zr.shouldUseRule=Sw});var Os=Z(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.reportTypeError=it.checkDataTypes=it.checkDataType=it.coerceAndCheckDataType=it.getJSONTypes=it.getSchemaTypes=it.DataType=void 0;var kI=hf(),SI=mf(),TI=Is(),ne=se(),Tw=ge(),lo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(lo||(it.DataType=lo={}));function EI(t){let e=Ew(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}it.getSchemaTypes=EI;function Ew(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(kI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}it.getJSONTypes=Ew;function RI(t,e){let{gen:r,data:n,opts:o}=t,s=PI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,SI.schemaHasRulesForType)(t,e[0]));if(i){let a=yf(e,n,o.strictNumbers,lo.Wrong);r.if(a,()=>{s.length?AI(t,e,s):bf(t)})}return i}it.coerceAndCheckDataType=RI;var Rw=new Set(["string","number","integer","boolean","null"]);function PI(t,e){return e?t.filter(r=>Rw.has(r)||e==="array"&&r==="array"):[]}function AI(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ne._)`typeof ${o}`),a=n.let("coerced",(0,ne._)`undefined`);s.coerceTypes==="array"&&n.if((0,ne._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ne._)`${o}[0]`).assign(i,(0,ne._)`typeof ${o}`).if(yf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ne._)`${a} !== undefined`);for(let u of r)(Rw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),bf(t),n.endIf(),n.if((0,ne._)`${a} !== undefined`,()=>{n.assign(o,a),II(t,a)});function c(u){switch(u){case"string":n.elseIf((0,ne._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ne._)`"" + ${o}`).elseIf((0,ne._)`${o} === null`).assign(a,(0,ne._)`""`);return;case"number":n.elseIf((0,ne._)`${i} == "boolean" || ${o} === null
|
|
932
|
+
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ne._)`+${o}`);return;case"integer":n.elseIf((0,ne._)`${i} === "boolean" || ${o} === null
|
|
933
|
+
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ne._)`+${o}`);return;case"boolean":n.elseIf((0,ne._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ne._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ne._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ne._)`${i} === "string" || ${i} === "number"
|
|
934
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,ne._)`[${o}]`)}}}function II({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ne._)`${e} !== undefined`,()=>t.assign((0,ne._)`${e}[${r}]`,n))}function gf(t,e,r,n=lo.Correct){let o=n===lo.Correct?ne.operators.EQ:ne.operators.NEQ,s;switch(t){case"null":return(0,ne._)`${e} ${o} null`;case"array":s=(0,ne._)`Array.isArray(${e})`;break;case"object":s=(0,ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ne._)`typeof ${e} ${o} ${t}`}return n===lo.Correct?s:(0,ne.not)(s);function i(a=ne.nil){return(0,ne.and)((0,ne._)`typeof ${e} == "number"`,a,r?(0,ne._)`isFinite(${e})`:ne.nil)}}it.checkDataType=gf;function yf(t,e,r,n){if(t.length===1)return gf(t[0],e,r,n);let o,s=(0,Tw.toHash)(t);if(s.array&&s.object){let i=(0,ne._)`typeof ${e} != "object"`;o=s.null?i:(0,ne._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ne.nil;s.number&&delete s.integer;for(let i in s)o=(0,ne.and)(o,gf(i,e,r,n));return o}it.checkDataTypes=yf;var OI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ne._)`{type: ${t}}`:(0,ne._)`{type: ${e}}`};function bf(t){let e=CI(t);(0,TI.reportError)(e,OI)}it.reportTypeError=bf;function CI(t){let{gen:e,data:r,schema:n}=t,o=(0,Tw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Aw=Z(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.assignDefaults=void 0;var po=se(),zI=ge();function NI(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Pw(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Pw(t,s,o.default))}qa.assignDefaults=NI;function Pw(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,po._)`${s}${(0,po.getProperty)(e)}`;if(o){(0,zI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,po._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,po._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,po._)`${a} = ${(0,po.stringify)(r)}`)}});var Lt=Z(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.validateUnion=xe.validateArray=xe.usePattern=xe.callValidateCode=xe.schemaProperties=xe.allSchemaProperties=xe.noPropertyInData=xe.propertyInData=xe.isOwnProperty=xe.hasPropFunc=xe.reportMissingProp=xe.checkMissingProp=xe.checkReportMissingProp=void 0;var Ae=se(),_f=ge(),Ur=_r(),jI=ge();function MI(t,e){let{gen:r,data:n,it:o}=t;r.if(vf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ae._)`${e}`},!0),t.error()})}xe.checkReportMissingProp=MI;function LI({gen:t,data:e,it:{opts:r}},n,o){return(0,Ae.or)(...n.map(s=>(0,Ae.and)(vf(t,e,s,r.ownProperties),(0,Ae._)`${o} = ${s}`)))}xe.checkMissingProp=LI;function DI(t,e){t.setParams({missingProperty:e},!0),t.error()}xe.reportMissingProp=DI;function Iw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ae._)`Object.prototype.hasOwnProperty`})}xe.hasPropFunc=Iw;function wf(t,e,r){return(0,Ae._)`${Iw(t)}.call(${e}, ${r})`}xe.isOwnProperty=wf;function ZI(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} !== undefined`;return n?(0,Ae._)`${o} && ${wf(t,e,r)}`:o}xe.propertyInData=ZI;function vf(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} === undefined`;return n?(0,Ae.or)(o,(0,Ae.not)(wf(t,e,r))):o}xe.noPropertyInData=vf;function Ow(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}xe.allSchemaProperties=Ow;function UI(t,e){return Ow(e).filter(r=>!(0,_f.alwaysValidSchema)(t,e[r]))}xe.schemaProperties=UI;function qI({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,Ae._)`${t}, ${e}, ${n}${o}`:e,l=[[Ur.default.instancePath,(0,Ae.strConcat)(Ur.default.instancePath,s)],[Ur.default.parentData,i.parentData],[Ur.default.parentDataProperty,i.parentDataProperty],[Ur.default.rootData,Ur.default.rootData]];i.opts.dynamicRef&&l.push([Ur.default.dynamicAnchors,Ur.default.dynamicAnchors]);let f=(0,Ae._)`${d}, ${r.object(...l)}`;return c!==Ae.nil?(0,Ae._)`${a}.call(${c}, ${f})`:(0,Ae._)`${a}(${f})`}xe.callValidateCode=qI;var FI=(0,Ae._)`new RegExp`;function BI({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,Ae._)`${o.code==="new RegExp"?FI:(0,jI.useFunc)(t,o)}(${r}, ${n})`})}xe.usePattern=BI;function VI(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,Ae._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:_f.Type.Num},s),e.if((0,Ae.not)(s),a)})}}xe.validateArray=VI;function HI(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,_f.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ae._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Ae.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}xe.validateUnion=HI});var Nw=Z(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.validateKeywordUsage=or.validSchemaType=or.funcKeywordCode=or.macroKeywordCode=void 0;var dt=se(),Rn=_r(),KI=Lt(),WI=Is();function GI(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=zw(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:dt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}or.macroKeywordCode=GI;function JI(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;XI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=zw(n,o,u),l=n.let("valid");t.block$data(l,f),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function f(){if(e.errors===!1)m(),e.modifying&&Cw(t),b(()=>t.error());else{let S=e.async?h():p();e.modifying&&Cw(t),b(()=>YI(t,S))}}function h(){let S=n.let("ruleErrs",null);return n.try(()=>m((0,dt._)`await `),R=>n.assign(l,!1).if((0,dt._)`${R} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,dt._)`${R}.errors`),()=>n.throw(R))),S}function p(){let S=(0,dt._)`${d}.errors`;return n.assign(S,null),m(dt.nil),S}function m(S=e.async?(0,dt._)`await `:dt.nil){let R=c.opts.passContext?Rn.default.this:Rn.default.self,C=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,dt._)`${S}${(0,KI.callValidateCode)(t,d,R,C)}`,e.modifying)}function b(S){var R;n.if((0,dt.not)((R=e.valid)!==null&&R!==void 0?R:l),S)}}or.funcKeywordCode=JI;function Cw(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,dt._)`${n.parentData}[${n.parentDataProperty}]`))}function YI(t,e){let{gen:r}=t;r.if((0,dt._)`Array.isArray(${e})`,()=>{r.assign(Rn.default.vErrors,(0,dt._)`${Rn.default.vErrors} === null ? ${e} : ${Rn.default.vErrors}.concat(${e})`).assign(Rn.default.errors,(0,dt._)`${Rn.default.vErrors}.length`),(0,WI.extendErrors)(t)},()=>t.error())}function XI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function zw(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,dt.stringify)(r)})}function QI(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")}or.validSchemaType=QI;function eO({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)}}or.validateKeywordUsage=eO});var Mw=Z(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.extendSubschemaMode=qr.extendSubschemaData=qr.getSubschema=void 0;var sr=se(),jw=ge();function tO(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,sr._)`${t.schemaPath}${(0,sr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,sr._)`${t.schemaPath}${(0,sr.getProperty)(e)}${(0,sr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,jw.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')}qr.getSubschema=tO;function rO(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:u,dataPathArr:d,opts:l}=e,f=a.let("data",(0,sr._)`${e.data}${(0,sr.getProperty)(r)}`,!0);c(f),t.errorPath=(0,sr.str)`${u}${(0,jw.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,sr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof sr.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}qr.extendSubschemaData=rO;function nO(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}qr.extendSubschemaMode=nO});var xf=Z((mF,Lw)=>{"use strict";Lw.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 Zw=Z((gF,Dw)=>{"use strict";var Fr=Dw.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(){};Fa(e,n,o,t,"",t)};Fr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Fr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Fr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Fr.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 Fa(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in Fr.arrayKeywords)for(var f=0;f<l.length;f++)Fa(t,e,r,l[f],o+"/"+d+"/"+f,s,o,d,n,f)}else if(d in Fr.propsKeywords){if(l&&typeof l=="object")for(var h in l)Fa(t,e,r,l[h],o+"/"+d+"/"+oO(h),s,o,d,n,h)}else(d in Fr.keywords||t.allKeys&&!(d in Fr.skipKeywords))&&Fa(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function oO(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Cs=Z(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.getSchemaRefs=_t.resolveUrl=_t.normalizeId=_t._getFullPath=_t.getFullPath=_t.inlineRef=void 0;var sO=ge(),iO=xf(),aO=Zw(),cO=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function uO(t,e=!0){return typeof t=="boolean"?!0:e===!0?!$f(t):e?Uw(t)<=e:!1}_t.inlineRef=uO;var lO=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function $f(t){for(let e in t){if(lO.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some($f)||typeof r=="object"&&$f(r))return!0}return!1}function Uw(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!cO.has(r)&&(typeof t[r]=="object"&&(0,sO.eachItem)(t[r],n=>e+=Uw(n)),e===1/0))return 1/0}return e}function qw(t,e="",r){r!==!1&&(e=fo(e));let n=t.parse(e);return Fw(t,n)}_t.getFullPath=qw;function Fw(t,e){return t.serialize(e).split("#")[0]+"#"}_t._getFullPath=Fw;var dO=/#\/?$/;function fo(t){return t?t.replace(dO,""):""}_t.normalizeId=fo;function pO(t,e,r){return r=fo(r),t.resolve(e,r)}_t.resolveUrl=pO;var fO=/^[a-z_][-a-z0-9._]*$/i;function hO(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=fo(t[r]||e),s={"":o},i=qw(n,o,!1),a={},c=new Set;return aO(t,{allKeys:!0},(l,f,h,p)=>{if(p===void 0)return;let m=i+f,b=s[p];typeof l[r]=="string"&&(b=S.call(this,l[r])),R.call(this,l.$anchor),R.call(this,l.$dynamicAnchor),s[f]=b;function S(C){let B=this.opts.uriResolver.resolve;if(C=fo(b?B(b,C):C),c.has(C))throw d(C);c.add(C);let G=this.refs[C];return typeof G=="string"&&(G=this.refs[G]),typeof G=="object"?u(l,G.schema,C):C!==fo(m)&&(C[0]==="#"?(u(l,a[C],C),a[C]=l):this.refs[C]=m),C}function R(C){if(typeof C=="string"){if(!fO.test(C))throw new Error(`invalid anchor "${C}"`);S.call(this,`#${C}`)}}}),a;function u(l,f,h){if(f!==void 0&&!iO(l,f))throw d(h)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}_t.getSchemaRefs=hO});var js=Z(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.getData=Br.KeywordCxt=Br.validateFunctionCode=void 0;var Ww=$w(),Bw=Os(),Sf=mf(),Ba=Os(),mO=Aw(),Ns=Nw(),kf=Mw(),W=se(),ee=_r(),gO=Cs(),wr=ge(),zs=Is();function yO(t){if(Yw(t)&&(Xw(t),Jw(t))){wO(t);return}Gw(t,()=>(0,Ww.topBoolOrEmptySchema)(t))}Br.validateFunctionCode=yO;function Gw({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,W._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,W._)`"use strict"; ${Vw(r,o)}`),_O(t,o),t.code(s)}):t.func(e,(0,W._)`${ee.default.data}, ${bO(o)}`,n.$async,()=>t.code(Vw(r,o)).code(s))}function bO(t){return(0,W._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,W._)`, ${ee.default.dynamicAnchors}={}`:W.nil}}={}`}function _O(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,W._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,W._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,W._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,W._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,W._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,W._)`""`),t.var(ee.default.parentData,(0,W._)`undefined`),t.var(ee.default.parentDataProperty,(0,W._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,W._)`{}`)})}function wO(t){let{schema:e,opts:r,gen:n}=t;Gw(t,()=>{r.$comment&&e.$comment&&ev(t),SO(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&vO(t),Qw(t),RO(t)})}function vO(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,W._)`${r}.evaluated`),e.if((0,W._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,W._)`${t.evaluated}.props`,(0,W._)`undefined`)),e.if((0,W._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,W._)`${t.evaluated}.items`,(0,W._)`undefined`))}function Vw(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,W._)`/*# sourceURL=${r} */`:W.nil}function xO(t,e){if(Yw(t)&&(Xw(t),Jw(t))){$O(t,e);return}(0,Ww.boolOrEmptySchema)(t,e)}function Jw({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 Yw(t){return typeof t.schema!="boolean"}function $O(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&ev(t),TO(t),EO(t);let s=n.const("_errs",ee.default.errors);Qw(t,s),n.var(e,(0,W._)`${s} === ${ee.default.errors}`)}function Xw(t){(0,wr.checkUnknownRules)(t),kO(t)}function Qw(t,e){if(t.opts.jtd)return Hw(t,[],!1,e);let r=(0,Bw.getSchemaTypes)(t.schema),n=(0,Bw.coerceAndCheckDataType)(t,r);Hw(t,r,!n,e)}function kO(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,wr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function SO(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,wr.checkStrictMode)(t,"default is ignored in the schema root")}function TO(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,gO.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function EO(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function ev({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,W._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,W.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,W._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function RO(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,W._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,W._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,W._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&PO(t),e.return((0,W._)`${ee.default.errors} === 0`))}function PO({gen:t,evaluated:e,props:r,items:n}){r instanceof W.Name&&t.assign((0,W._)`${e}.props`,r),n instanceof W.Name&&t.assign((0,W._)`${e}.items`,n)}function Hw(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,wr.schemaHasRulesButRef)(s,d))){o.block(()=>rv(t,"$ref",d.all.$ref.definition));return}c.jtd||AO(t,e),o.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,Sf.shouldUseGroup)(s,f)&&(f.type?(o.if((0,Ba.checkDataType)(f.type,i,c.strictNumbers)),Kw(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,Ba.reportTypeError)(t)),o.endIf()):Kw(t,f),a||o.if((0,W._)`${ee.default.errors} === ${n||0}`))}}function Kw(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,mO.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Sf.shouldUseRule)(n,s)&&rv(t,s.keyword,s.definition,e.type)})}function AO(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(IO(t,e),t.opts.allowUnionTypes||OO(t,e),CO(t,t.dataTypes))}function IO(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{tv(t.dataTypes,r)||Tf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),NO(t,e)}}function OO(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Tf(t,"use allowUnionTypes to allow union type keyword")}function CO(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Sf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>zO(e,i))&&Tf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function zO(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function tv(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function NO(t,e){let r=[];for(let n of t.dataTypes)tv(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Tf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,wr.checkStrictMode)(t,e,t.opts.strictTypes)}var Va=class{constructor(e,r,n){if((0,Ns.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,wr.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",nv(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ns.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",ee.default.errors))}result(e,r,n){this.failResult((0,W.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,W.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,W._)`${r} !== undefined && (${(0,W.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?zs.reportExtraError:zs.reportError)(this,this.def.error,r)}$dataError(){(0,zs.reportError)(this,this.def.$dataError||zs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,zs.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=W.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=W.nil,r=W.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,W.or)((0,W._)`${o} === undefined`,r)),e!==W.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==W.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,W.or)(i(),a());function i(){if(n.length){if(!(r instanceof W.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,W._)`${(0,Ba.checkDataTypes)(c,r,s.opts.strictNumbers,Ba.DataType.Wrong)}`}return W.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,W._)`!${c}(${r})`}return W.nil}}subschema(e,r){let n=(0,kf.getSubschema)(this.it,e);(0,kf.extendSubschemaData)(n,this.it,e),(0,kf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return xO(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=wr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=wr.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,W.Name)),!0}};Br.KeywordCxt=Va;function rv(t,e,r,n){let o=new Va(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ns.funcKeywordCode)(o,r):"macro"in r?(0,Ns.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ns.funcKeywordCode)(o,r)}var jO=/^\/(?:[^~]|~0|~1)*$/,MO=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function nv(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!jO.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=MO.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(o=u[2],o==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(s=r[e-d],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,W._)`${s}${(0,W.getProperty)((0,wr.unescapeJsonPointer)(u))}`,i=(0,W._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}Br.getData=nv});var Ha=Z(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var Ef=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Rf.default=Ef});var Ms=Z(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var Pf=Cs(),Af=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Pf.resolveUrl)(e,r,n),this.missingSchema=(0,Pf.normalizeId)((0,Pf.getFullPath)(e,this.missingRef))}};If.default=Af});var Wa=Z(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.resolveSchema=Dt.getCompilingSchema=Dt.resolveRef=Dt.compileSchema=Dt.SchemaEnv=void 0;var Kt=se(),LO=Ha(),Pn=_r(),Wt=Cs(),ov=ge(),DO=js(),ho=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,Wt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Dt.SchemaEnv=ho;function Cf(t){let e=sv.call(this,t);if(e)return e;let r=(0,Wt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Kt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:LO.default,code:(0,Kt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Pn.default.data,parentData:Pn.default.parentData,parentDataProperty:Pn.default.parentDataProperty,dataNames:[Pn.default.data],dataPathArr:[Kt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Kt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Kt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Kt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,DO.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(Pn.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let h=new Function(`${Pn.default.self}`,`${Pn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:m}=u;h.evaluated={props:p instanceof Kt.Name?void 0:p,items:m instanceof Kt.Name?void 0:m,dynamicProps:p instanceof Kt.Name,dynamicItems:m instanceof Kt.Name},h.source&&(h.source.evaluated=(0,Kt.stringify)(h.evaluated))}return t.validate=h,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Dt.compileSchema=Cf;function ZO(t,e,r){var n;r=(0,Wt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=FO.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 ho({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=UO.call(this,s)}Dt.resolveRef=ZO;function UO(t){return(0,Wt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Cf.call(this,t)}function sv(t){for(let e of this._compilations)if(qO(e,t))return e}Dt.getCompilingSchema=sv;function qO(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function FO(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ka.call(this,t,e)}function Ka(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Wt._getFullPath)(this.opts.uriResolver,r),o=(0,Wt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Of.call(this,r,t);let s=(0,Wt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ka.call(this,t,i);return typeof a?.schema!="object"?void 0:Of.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Cf.call(this,i),s===(0,Wt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Wt.resolveUrl)(this.opts.uriResolver,o,u)),new ho({schema:a,schemaId:c,root:t,baseId:o})}return Of.call(this,r,i)}}Dt.resolveSchema=Ka;var BO=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Of(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,ov.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!BO.has(a)&&u&&(e=(0,Wt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,ov.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Wt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ka.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new ho({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var iv=Z((xF,VO)=>{VO.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 jf=Z(($F,pv)=>{"use strict";var HO=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),cv=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),zf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),uv=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),KO=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 WO=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function av(t){return t.length=0,!0}function GO(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 JO(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=GO;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){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(u==="%"){if(!a(o,n,r))break;a=av}else{o.push(u);continue}}return o.length&&(a===av?r.zone=o.join(""):i?n.push(o.join("")):n.push(Nf(o))),r.address=n.join(""),r}function lv(t){if(YO(t,":")<2)return{host:t,isIPV6:!1};let e=JO(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 YO(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function XO(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 QO={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},eC=/[@/?#:]/g,tC=/[@/?#]/g;function dv(t,e){let r=e?tC:eC;return r.lastIndex=0,t.replace(r,n=>QO[n])}function rC(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(zf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&uv(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function nC(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(zf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&uv(s)?e+=s:e+="%"+o,r+=2;continue}}KO(t[r])?e+=t[r]:e+=escape(t[r])}return e}function oC(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(zf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function sC(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!cv(r)){let n=lv(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=dv(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}pv.exports={nonSimpleDomain:WO,recomposeAuthority:sC,reescapeHostDelimiters:dv,normalizePercentEncoding:rC,normalizePathEncoding:nC,escapePreservingEscapes:oC,removeDotSegments:XO,isIPv4:cv,isUUID:HO,normalizeIPv6:lv,stringArrayToHexStripped:Nf}});var yv=Z((kF,gv)=>{"use strict";var{isUUID:iC}=jf(),aC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,cC=["http","https","ws","wss","urn","urn:uuid"];function uC(t){return cC.indexOf(t)!==-1}function Mf(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 fv(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function hv(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 lC(t){return t.secure=Mf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function dC(t){if((t.port===(Mf(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 pC(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(aC);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=Lf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function fC(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=Lf(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 hC(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!iC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function mC(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var mv={scheme:"http",domainHost:!0,parse:fv,serialize:hv},gC={scheme:"https",domainHost:mv.domainHost,parse:fv,serialize:hv},Ga={scheme:"ws",domainHost:!0,parse:lC,serialize:dC},yC={scheme:"wss",domainHost:Ga.domainHost,parse:Ga.parse,serialize:Ga.serialize},bC={scheme:"urn",parse:pC,serialize:fC,skipNormalize:!0},_C={scheme:"urn:uuid",parse:hC,serialize:mC,skipNormalize:!0},Ja={http:mv,https:gC,ws:Ga,wss:yC,urn:bC,"urn:uuid":_C};Object.setPrototypeOf(Ja,null);function Lf(t){return t&&(Ja[t]||Ja[t.toLowerCase()])||void 0}gv.exports={wsIsSecure:Mf,SCHEMES:Ja,isValidSchemeName:uC,getSchemeHandler:Lf}});var $v=Z((SF,Ya)=>{"use strict";var{normalizeIPv6:wC,removeDotSegments:Ls,recomposeAuthority:vC,normalizePercentEncoding:xC,normalizePathEncoding:$C,escapePreservingEscapes:kC,reescapeHostDelimiters:SC,isIPv4:TC,nonSimpleDomain:EC}=jf(),{SCHEMES:RC,getSchemeHandler:_v}=yv();function PC(t,e){return typeof t=="string"?t=NC(t,e):typeof t=="object"&&(t=mo(An(t,e),e)),t}function AC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=wv(mo(t,n),mo(e,n),n,!0);return n.skipEscape=!0,An(o,n)}function wv(t,e,r,n){let o={};return n||(t=mo(An(t,r),r),e=mo(An(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=Ls(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=Ls(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ls(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=Ls(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 IC(t,e,r){let n=bv(t,r),o=bv(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function An(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=_v(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=xC(r.path):(r.path=kC(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=vC(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=Ls(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 OC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,CC=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function zC(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 vv(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(CC);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(OC);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=zC(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(TC(n.host)===!1){let l=wC(n.host);n.host=l.host.toLowerCase(),s=l.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=_v(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&EC(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(d){n.error=n.error||"Host's domain name can not be converted to ASCII: "+d}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=SC(unescape(n.host),s))),n.path&&(n.path=$C(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 mo(t,e){return vv(t,e).parsed}function NC(t,e){return xv(t,e).normalized}function xv(t,e){let{parsed:r,malformedAuthorityOrPort:n}=vv(t,e);return{normalized:n?t:An(r,e),malformedAuthorityOrPort:n}}function bv(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=xv(t,e);return n?void 0:r}if(typeof t=="object")return An(t,e)}var Df={SCHEMES:RC,normalize:PC,resolve:AC,resolveComponent:wv,equal:IC,serialize:An,parse:mo};Ya.exports=Df;Ya.exports.default=Df;Ya.exports.fastUri=Df});var Sv=Z(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var kv=$v();kv.code='require("ajv/dist/runtime/uri").default';Zf.default=kv});var Cv=Z(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.CodeGen=tt.Name=tt.nil=tt.stringify=tt.str=tt._=tt.KeywordCxt=void 0;var jC=js();Object.defineProperty(tt,"KeywordCxt",{enumerable:!0,get:function(){return jC.KeywordCxt}});var go=se();Object.defineProperty(tt,"_",{enumerable:!0,get:function(){return go._}});Object.defineProperty(tt,"str",{enumerable:!0,get:function(){return go.str}});Object.defineProperty(tt,"stringify",{enumerable:!0,get:function(){return go.stringify}});Object.defineProperty(tt,"nil",{enumerable:!0,get:function(){return go.nil}});Object.defineProperty(tt,"Name",{enumerable:!0,get:function(){return go.Name}});Object.defineProperty(tt,"CodeGen",{enumerable:!0,get:function(){return go.CodeGen}});var MC=Ha(),Av=Ms(),LC=hf(),Ds=Wa(),DC=se(),Zs=Cs(),Xa=Os(),qf=ge(),Tv=iv(),ZC=Sv(),Iv=(t,e)=>new RegExp(t,e);Iv.code="new RegExp";var UC=["removeAdditional","useDefaults","coerceTypes"],qC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),FC={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."},BC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ev=200;function VC(t){var e,r,n,o,s,i,a,c,u,d,l,f,h,p,m,b,S,R,C,B,G,Ve,He,ur,To;let vr=t.strict,Eo=(e=t.code)===null||e===void 0?void 0:e.optimize,Wr=Eo===!0||Eo===void 0?1:Eo||0,g=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Iv,y=(o=t.uriResolver)!==null&&o!==void 0?o:ZC.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:vr)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:vr)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:vr)!==null&&d!==void 0?d:"log",strictTuples:(f=(l=t.strictTuples)!==null&&l!==void 0?l:vr)!==null&&f!==void 0?f:"log",strictRequired:(p=(h=t.strictRequired)!==null&&h!==void 0?h:vr)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:Wr,regExp:g}:{optimize:Wr,regExp:g},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:Ev,loopEnum:(b=t.loopEnum)!==null&&b!==void 0?b:Ev,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(R=t.messages)!==null&&R!==void 0?R:!0,inlineRefs:(C=t.inlineRefs)!==null&&C!==void 0?C:!0,schemaId:(B=t.schemaId)!==null&&B!==void 0?B:"$id",addUsedSchema:(G=t.addUsedSchema)!==null&&G!==void 0?G:!0,validateSchema:(Ve=t.validateSchema)!==null&&Ve!==void 0?Ve:!0,validateFormats:(He=t.validateFormats)!==null&&He!==void 0?He:!0,unicodeRegExp:(ur=t.unicodeRegExp)!==null&&ur!==void 0?ur:!0,int32range:(To=t.int32range)!==null&&To!==void 0?To:!0,uriResolver:y}}var Us=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,...VC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new DC.ValueScope({scope:{},prefixes:qC,es5:r,lines:n}),this.logger=YC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,LC.getRules)(),Rv.call(this,FC,e,"NOT SUPPORTED"),Rv.call(this,BC,e,"DEPRECATED","warn"),this._metaOpts=GC.call(this),e.formats&&KC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&WC.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),HC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Tv;n==="id"&&(o={...Tv},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(d,l){await s.call(this,d.$schema);let f=this._addSchema(d,l);return f.validate||i.call(this,f)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof Av.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await s.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}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,Zs.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=Pv.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Ds.SchemaEnv({schema:{},schemaId:n});if(r=Ds.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=Pv.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,Zs.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(QC.call(this,n,r),!r)return(0,qf.eachItem)(n,s=>Uf.call(this,s)),this;tz.call(this,r);let o={...r,type:(0,Xa.getJSONTypes)(r.type),schemaType:(0,Xa.getJSONTypes)(r.schemaType)};return(0,qf.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:u}=c.definition,d=i[a];u&&d&&(i[a]=Ov(d))}}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,Zs.normalizeId)(i||n);let u=Zs.getSchemaRefs.call(this,e,n);return c=new Ds.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),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):Ds.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{Ds.compileSchema.call(this,e)}finally{this.opts=r}}};Us.ValidationError=MC.default;Us.MissingRefError=Av.default;tt.default=Us;function Rv(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 Pv(t){return t=(0,Zs.normalizeId)(t),this.schemas[t]||this.refs[t]}function HC(){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 KC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function WC(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 GC(){let t={...this.opts};for(let e of UC)delete t[e];return t}var JC={log(){},warn(){},error(){}};function YC(t){if(t===!1)return JC;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 XC=/^[a-z_$][a-z0-9_$:-]*$/i;function QC(t,e){let{RULES:r}=this;if((0,qf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!XC.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,Xa.getJSONTypes)(e.type),schemaType:(0,Xa.getJSONTypes)(e.schemaType)}};e.before?ez.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 ez(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 tz(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Ov(e)),t.validateSchema=this.compile(e,!0))}var rz={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ov(t){return{anyOf:[t,rz]}}});var zv=Z(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var nz={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ff.default=nz});var Lv=Z(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.callRef=In.getValidate=void 0;var oz=Ms(),Nv=Lt(),wt=se(),yo=_r(),jv=Wa(),Qa=ge(),sz={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:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return l();let d=jv.resolveRef.call(c,u,o,r);if(d===void 0)throw new oz.default(n.opts.uriResolver,o,r);if(d instanceof jv.SchemaEnv)return f(d);return h(d);function l(){if(s===u)return ec(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return ec(t,(0,wt._)`${p}.validate`,u,u.$async)}function f(p){let m=Mv(t,p);ec(t,m,p,p.$async)}function h(p){let m=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,wt.stringify)(p)}:{ref:p}),b=e.name("valid"),S=t.subschema({schema:p,dataTypes:[],schemaPath:wt.nil,topSchemaRef:m,errSchemaPath:r},b);t.mergeEvaluated(S),t.ok(b)}}};function Mv(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,wt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}In.getValidate=Mv;function ec(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?yo.default.this:wt.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,wt._)`await ${(0,Nv.callValidateCode)(t,e,u)}`),h(e),i||o.assign(p,!0)},m=>{o.if((0,wt._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),f(m),i||o.assign(p,!1)}),t.ok(p)}function l(){t.result((0,Nv.callValidateCode)(t,e,u),()=>h(e),()=>f(e))}function f(p){let m=(0,wt._)`${p}.errors`;o.assign(yo.default.vErrors,(0,wt._)`${yo.default.vErrors} === null ? ${m} : ${yo.default.vErrors}.concat(${m})`),o.assign(yo.default.errors,(0,wt._)`${yo.default.vErrors}.length`)}function h(p){var m;if(!s.opts.unevaluated)return;let b=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(b&&!b.dynamicProps)b.props!==void 0&&(s.props=Qa.mergeEvaluated.props(o,b.props,s.props));else{let S=o.var("props",(0,wt._)`${p}.evaluated.props`);s.props=Qa.mergeEvaluated.props(o,S,s.props,wt.Name)}if(s.items!==!0)if(b&&!b.dynamicItems)b.items!==void 0&&(s.items=Qa.mergeEvaluated.items(o,b.items,s.items));else{let S=o.var("items",(0,wt._)`${p}.evaluated.items`);s.items=Qa.mergeEvaluated.items(o,S,s.items,wt.Name)}}}In.callRef=ec;In.default=sz});var Dv=Z(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var iz=zv(),az=Lv(),cz=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",iz.default,az.default];Bf.default=cz});var Zv=Z(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var tc=se(),Vr=tc.operators,rc={maximum:{okStr:"<=",ok:Vr.LTE,fail:Vr.GT},minimum:{okStr:">=",ok:Vr.GTE,fail:Vr.LT},exclusiveMaximum:{okStr:"<",ok:Vr.LT,fail:Vr.GTE},exclusiveMinimum:{okStr:">",ok:Vr.GT,fail:Vr.LTE}},uz={message:({keyword:t,schemaCode:e})=>(0,tc.str)`must be ${rc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,tc._)`{comparison: ${rc[t].okStr}, limit: ${e}}`},lz={keyword:Object.keys(rc),type:"number",schemaType:"number",$data:!0,error:uz,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,tc._)`${r} ${rc[e].fail} ${n} || isNaN(${r})`)}};Vf.default=lz});var Uv=Z(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var qs=se(),dz={message:({schemaCode:t})=>(0,qs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,qs._)`{multipleOf: ${t}}`},pz={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:dz,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,qs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,qs._)`${i} !== parseInt(${i})`;t.fail$data((0,qs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Hf.default=pz});var Fv=Z(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});function qv(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}Kf.default=qv;qv.code='require("ajv/dist/runtime/ucs2length").default'});var Bv=Z(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var On=se(),fz=ge(),hz=Fv(),mz={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,On.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,On._)`{limit: ${t}}`},gz={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:mz,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?On.operators.GT:On.operators.LT,i=o.opts.unicode===!1?(0,On._)`${r}.length`:(0,On._)`${(0,fz.useFunc)(t.gen,hz.default)}(${r})`;t.fail$data((0,On._)`${i} ${s} ${n}`)}};Wf.default=gz});var Vv=Z(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var yz=Lt(),bz=ge(),bo=se(),_z={message:({schemaCode:t})=>(0,bo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,bo._)`{pattern: ${t}}`},wz={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_z,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,u=c.code==="new RegExp"?(0,bo._)`new RegExp`:(0,bz.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,bo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,bo._)`!${d}`)}else{let c=(0,yz.usePattern)(t,o);t.fail$data((0,bo._)`!${c}.test(${r})`)}}};Gf.default=wz});var Hv=Z(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var Fs=se(),vz={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Fs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Fs._)`{limit: ${t}}`},xz={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:vz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Fs.operators.GT:Fs.operators.LT;t.fail$data((0,Fs._)`Object.keys(${r}).length ${o} ${n}`)}};Jf.default=xz});var Kv=Z(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var Bs=Lt(),Vs=se(),$z=ge(),kz={message:({params:{missingProperty:t}})=>(0,Vs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Vs._)`{missingProperty: ${t}}`},Sz={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kz,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?u():d(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:p}=t.it;for(let m of r)if(h?.[m]===void 0&&!p.has(m)){let b=i.schemaEnv.baseId+i.errSchemaPath,S=`required property "${m}" is not defined at "${b}" (strictRequired)`;(0,$z.checkStrictMode)(i,S,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Vs.nil,l);else for(let h of r)(0,Bs.checkReportMissingProp)(t,h)}function d(){let h=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>f(h,p)),t.ok(p)}else e.if((0,Bs.checkMissingProp)(t,r,h)),(0,Bs.reportMissingProp)(t,h),e.else()}function l(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,Bs.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function f(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,Bs.propertyInData)(e,o,h,a.ownProperties)),e.if((0,Vs.not)(p),()=>{t.error(),e.break()})},Vs.nil)}}};Yf.default=Sz});var Wv=Z(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var Hs=se(),Tz={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Hs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Hs._)`{limit: ${t}}`},Ez={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Tz,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Hs.operators.GT:Hs.operators.LT;t.fail$data((0,Hs._)`${r}.length ${o} ${n}`)}};Xf.default=Ez});var nc=Z(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var Gv=xf();Gv.code='require("ajv/dist/runtime/equal").default';Qf.default=Gv});var Jv=Z(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var eh=Os(),rt=se(),Rz=ge(),Pz=nc(),Az={message:({params:{i:t,j:e}})=>(0,rt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,rt._)`{i: ${t}, j: ${e}}`},Iz={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Az,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"),u=s.items?(0,eh.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,rt._)`${i} === false`),t.ok(c);function d(){let p=e.let("i",(0,rt._)`${r}.length`),m=e.let("j");t.setParams({i:p,j:m}),e.assign(c,!0),e.if((0,rt._)`${p} > 1`,()=>(l()?f:h)(p,m))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,m){let b=e.name("item"),S=(0,eh.checkDataTypes)(u,b,a.opts.strictNumbers,eh.DataType.Wrong),R=e.const("indices",(0,rt._)`{}`);e.for((0,rt._)`;${p}--;`,()=>{e.let(b,(0,rt._)`${r}[${p}]`),e.if(S,(0,rt._)`continue`),u.length>1&&e.if((0,rt._)`typeof ${b} == "string"`,(0,rt._)`${b} += "_"`),e.if((0,rt._)`typeof ${R}[${b}] == "number"`,()=>{e.assign(m,(0,rt._)`${R}[${b}]`),t.error(),e.assign(c,!1).break()}).code((0,rt._)`${R}[${b}] = ${p}`)})}function h(p,m){let b=(0,Rz.useFunc)(e,Pz.default),S=e.name("outer");e.label(S).for((0,rt._)`;${p}--;`,()=>e.for((0,rt._)`${m} = ${p}; ${m}--;`,()=>e.if((0,rt._)`${b}(${r}[${p}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(S)})))}}};th.default=Iz});var Yv=Z(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var rh=se(),Oz=ge(),Cz=nc(),zz={message:"must be equal to constant",params:({schemaCode:t})=>(0,rh._)`{allowedValue: ${t}}`},Nz={keyword:"const",$data:!0,error:zz,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,rh._)`!${(0,Oz.useFunc)(e,Cz.default)}(${r}, ${o})`):t.fail((0,rh._)`${s} !== ${r}`)}};nh.default=Nz});var Xv=Z(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var Ks=se(),jz=ge(),Mz=nc(),Lz={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ks._)`{allowedValues: ${t}}`},Dz={keyword:"enum",schemaType:"array",$data:!0,error:Lz,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,u=()=>c??(c=(0,jz.useFunc)(e,Mz.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let h=e.const("vSchema",s);d=(0,Ks.or)(...o.map((p,m)=>f(h,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,h=>e.if((0,Ks._)`${u()}(${r}, ${h})`,()=>e.assign(d,!0).break()))}function f(h,p){let m=o[p];return typeof m=="object"&&m!==null?(0,Ks._)`${u()}(${r}, ${h}[${p}])`:(0,Ks._)`${r} === ${m}`}}};oh.default=Dz});var Qv=Z(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var Zz=Zv(),Uz=Uv(),qz=Bv(),Fz=Vv(),Bz=Hv(),Vz=Kv(),Hz=Wv(),Kz=Jv(),Wz=Yv(),Gz=Xv(),Jz=[Zz.default,Uz.default,qz.default,Fz.default,Bz.default,Vz.default,Hz.default,Kz.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Wz.default,Gz.default];sh.default=Jz});var ah=Z(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.validateAdditionalItems=void 0;var Cn=se(),ih=ge(),Yz={message:({params:{len:t}})=>(0,Cn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Cn._)`{limit: ${t}}`},Xz={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Yz,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,ih.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ex(t,n)}};function ex(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Cn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Cn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ih.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Cn._)`${a} <= ${e.length}`);r.if((0,Cn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:ih.Type.Num},u),i.allErrors||r.if((0,Cn.not)(u),()=>r.break())})}}Ws.validateAdditionalItems=ex;Ws.default=Xz});var ch=Z(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.validateTuple=void 0;var tx=se(),oc=ge(),Qz=Lt(),eN={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return rx(t,"additionalItems",e);r.items=!0,!(0,oc.alwaysValidSchema)(r,e)&&t.ok((0,Qz.validateArray)(t))}};function rx(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=oc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,tx._)`${s}.length`);r.forEach((l,f)=>{(0,oc.alwaysValidSchema)(a,l)||(n.if((0,tx._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(l){let{opts:f,errSchemaPath:h}=a,p=r.length,m=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(f.strictTuples&&!m){let b=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,oc.checkStrictMode)(a,b,f.strictTuples)}}}Gs.validateTuple=rx;Gs.default=eN});var nx=Z(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var tN=ch(),rN={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,tN.validateTuple)(t,"items")};uh.default=rN});var sx=Z(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var ox=se(),nN=ge(),oN=Lt(),sN=ah(),iN={message:({params:{len:t}})=>(0,ox.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ox._)`{limit: ${t}}`},aN={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:iN,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,nN.alwaysValidSchema)(n,e)&&(o?(0,sN.validateAdditionalItems)(t,o):t.ok((0,oN.validateArray)(t)))}};lh.default=aN});var ix=Z(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var Zt=se(),sc=ge(),cN={message:({params:{min:t,max:e}})=>e===void 0?(0,Zt.str)`must contain at least ${t} valid item(s)`:(0,Zt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Zt._)`{minContains: ${t}}`:(0,Zt._)`{minContains: ${t}, maxContains: ${e}}`},uN={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:cN,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,Zt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,sc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,sc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,sc.alwaysValidSchema)(s,r)){let m=(0,Zt._)`${d} >= ${i}`;a!==void 0&&(m=(0,Zt._)`${m} && ${d} <= ${a}`),t.pass(m);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?h(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,Zt._)`${o}.length > 0`,f)):(e.let(l,!1),f()),t.result(l,()=>t.reset());function f(){let m=e.name("_valid"),b=e.let("count",0);h(m,()=>e.if(m,()=>p(b)))}function h(m,b){e.forRange("i",0,d,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:sc.Type.Num,compositeRule:!0},m),b()})}function p(m){e.code((0,Zt._)`${m}++`),a===void 0?e.if((0,Zt._)`${m} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,Zt._)`${m} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,Zt._)`${m} >= ${i}`,()=>e.assign(l,!0)))}}};dh.default=uN});var ux=Z(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.validateSchemaDeps=ir.validatePropertyDeps=ir.error=void 0;var ph=se(),lN=ge(),Js=Lt();ir.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,ph.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,ph._)`{property: ${t},
|
|
935
|
+
missingProperty: ${n},
|
|
936
|
+
depsCount: ${e},
|
|
937
|
+
deps: ${r}}`};var dN={keyword:"dependencies",type:"object",schemaType:"object",error:ir.error,code(t){let[e,r]=pN(t);ax(t,e),cx(t,r)}};function pN({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 ax(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,Js.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Js.checkReportMissingProp)(t,u)}):(r.if((0,ph._)`${c} && (${(0,Js.checkMissingProp)(t,a,s)})`),(0,Js.reportMissingProp)(t,s),r.else())}}ir.validatePropertyDeps=ax;function cx(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,lN.alwaysValidSchema)(s,e[a])||(r.if((0,Js.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))}ir.validateSchemaDeps=cx;ir.default=dN});var dx=Z(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var lx=se(),fN=ge(),hN={message:"property name must be valid",params:({params:t})=>(0,lx._)`{propertyName: ${t.propertyName}}`},mN={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:hN,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,fN.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,lx.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};fh.default=mN});var mh=Z(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var ic=Lt(),Gt=se(),gN=_r(),ac=ge(),yN={message:"must NOT have additional properties",params:({params:t})=>(0,Gt._)`{additionalProperty: ${t.additionalProperty}}`},bN={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:yN,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,ac.alwaysValidSchema)(i,r))return;let u=(0,ic.allSchemaProperties)(n.properties),d=(0,ic.allSchemaProperties)(n.patternProperties);l(),t.ok((0,Gt._)`${s} === ${gN.default.errors}`);function l(){e.forIn("key",o,b=>{!u.length&&!d.length?p(b):e.if(f(b),()=>p(b))})}function f(b){let S;if(u.length>8){let R=(0,ac.schemaRefOrVal)(i,n.properties,"properties");S=(0,ic.isOwnProperty)(e,R,b)}else u.length?S=(0,Gt.or)(...u.map(R=>(0,Gt._)`${b} === ${R}`)):S=Gt.nil;return d.length&&(S=(0,Gt.or)(S,...d.map(R=>(0,Gt._)`${(0,ic.usePattern)(t,R)}.test(${b})`))),(0,Gt.not)(S)}function h(b){e.code((0,Gt._)`delete ${o}[${b}]`)}function p(b){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(b);return}if(r===!1){t.setParams({additionalProperty:b}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ac.alwaysValidSchema)(i,r)){let S=e.name("valid");c.removeAdditional==="failing"?(m(b,S,!1),e.if((0,Gt.not)(S),()=>{t.reset(),h(b)})):(m(b,S),a||e.if((0,Gt.not)(S),()=>e.break()))}}function m(b,S,R){let C={keyword:"additionalProperties",dataProp:b,dataPropType:ac.Type.Str};R===!1&&Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(C,S)}}};hh.default=bN});var hx=Z(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});var _N=js(),px=Lt(),gh=ge(),fx=mh(),wN={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&&fx.default.code(new _N.KeywordCxt(s,fx.default,"additionalProperties"));let i=(0,px.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=gh.mergeEvaluated.props(e,(0,gh.toHash)(i),s.props));let a=i.filter(l=>!(0,gh.alwaysValidSchema)(s,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,px.propertyInData)(e,o,l,s.opts.ownProperties)),d(l),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return s.opts.useDefaults&&!s.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};yh.default=wN});var bx=Z(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var mx=Lt(),cc=se(),gx=ge(),yx=ge(),vN={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,mx.allSchemaProperties)(r),c=a.filter(m=>(0,gx.alwaysValidSchema)(s,r[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof cc.Name)&&(s.props=(0,yx.evaluatedPropsToName)(e,s.props));let{props:l}=s;f();function f(){for(let m of a)u&&h(m),s.allErrors?p(m):(e.var(d,!0),p(m),e.if(d))}function h(m){for(let b in u)new RegExp(m).test(b)&&(0,gx.checkStrictMode)(s,`property ${b} matches pattern ${m} (use allowMatchingProperties)`)}function p(m){e.forIn("key",n,b=>{e.if((0,cc._)`${(0,mx.usePattern)(t,m)}.test(${b})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:b,dataPropType:yx.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,cc._)`${l}[${b}]`,!0):!S&&!s.allErrors&&e.if((0,cc.not)(d),()=>e.break())})})}}};bh.default=vN});var _x=Z(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});var xN=ge(),$N={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,xN.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"}};_h.default=$N});var wx=Z(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});var kN=Lt(),SN={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kN.validateUnion,error:{message:"must match a schema in anyOf"}};wh.default=SN});var vx=Z(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var uc=se(),TN=ge(),EN={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,uc._)`{passingSchemas: ${t.passing}}`},RN={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:EN,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(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let f;(0,TN.alwaysValidSchema)(o,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,uc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,uc._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),f&&t.mergeEvaluated(f,uc.Name)})})}}};vh.default=RN});var xx=Z(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});var PN=ge(),AN={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,PN.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};xh.default=AN});var Sx=Z($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});var lc=se(),kx=ge(),IN={message:({params:t})=>(0,lc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,lc._)`{failingKeyword: ${t.ifClause}}`},ON={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:IN,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,kx.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=$x(n,"then"),s=$x(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else o?e.if(a,u("then")):e.if((0,lc.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let f=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(f,i),l?e.assign(l,(0,lc._)`${d}`):t.setParams({ifClause:d})}}}};function $x(t,e){let r=t.schema[e];return r!==void 0&&!(0,kx.alwaysValidSchema)(t,r)}$h.default=ON});var Tx=Z(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var CN=ge(),zN={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,CN.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};kh.default=zN});var Ex=Z(Sh=>{"use strict";Object.defineProperty(Sh,"__esModule",{value:!0});var NN=ah(),jN=nx(),MN=ch(),LN=sx(),DN=ix(),ZN=ux(),UN=dx(),qN=mh(),FN=hx(),BN=bx(),VN=_x(),HN=wx(),KN=vx(),WN=xx(),GN=Sx(),JN=Tx();function YN(t=!1){let e=[VN.default,HN.default,KN.default,WN.default,GN.default,JN.default,UN.default,qN.default,ZN.default,FN.default,BN.default];return t?e.push(jN.default,LN.default):e.push(NN.default,MN.default),e.push(DN.default),e}Sh.default=YN});var Rx=Z(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});var Fe=se(),XN={message:({schemaCode:t})=>(0,Fe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Fe._)`{format: ${t}}`},QN={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:XN,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?f():h();function f(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,Fe._)`${p}[${i}]`),b=r.let("fType"),S=r.let("format");r.if((0,Fe._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(b,(0,Fe._)`${m}.type || "string"`).assign(S,(0,Fe._)`${m}.validate`),()=>r.assign(b,(0,Fe._)`"string"`).assign(S,m)),t.fail$data((0,Fe.or)(R(),C()));function R(){return c.strictSchema===!1?Fe.nil:(0,Fe._)`${i} && !${S}`}function C(){let B=d.$async?(0,Fe._)`(${m}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,Fe._)`${S}(${n})`,G=(0,Fe._)`(typeof ${S} == "function" ? ${B} : ${S}.test(${n}))`;return(0,Fe._)`${S} && ${S} !== true && ${b} === ${e} && !${G}`}}function h(){let p=l.formats[s];if(!p){R();return}if(p===!0)return;let[m,b,S]=C(p);m===e&&t.pass(B());function R(){if(c.strictSchema===!1){l.logger.warn(G());return}throw new Error(G());function G(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function C(G){let Ve=G instanceof RegExp?(0,Fe.regexpCode)(G):c.code.formats?(0,Fe._)`${c.code.formats}${(0,Fe.getProperty)(s)}`:void 0,He=r.scopeValue("formats",{key:s,ref:G,code:Ve});return typeof G=="object"&&!(G instanceof RegExp)?[G.type||"string",G.validate,(0,Fe._)`${He}.validate`]:["string",G,He]}function B(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Fe._)`await ${S}(${n})`}return typeof b=="function"?(0,Fe._)`${S}(${n})`:(0,Fe._)`${S}.test(${n})`}}}};Th.default=QN});var Px=Z(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var e1=Rx(),t1=[e1.default];Eh.default=t1});var Ax=Z(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.contentVocabulary=_o.metadataVocabulary=void 0;_o.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];_o.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Ox=Z(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});var r1=Dv(),n1=Qv(),o1=Ex(),s1=Px(),Ix=Ax(),i1=[r1.default,n1.default,(0,o1.default)(),s1.default,Ix.metadataVocabulary,Ix.contentVocabulary];Rh.default=i1});var zx=Z(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});dc.DiscrError=void 0;var Cx;(function(t){t.Tag="tag",t.Mapping="mapping"})(Cx||(dc.DiscrError=Cx={}))});var jx=Z(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});var wo=se(),Ph=zx(),Nx=Wa(),a1=Ms(),c1=ge(),u1={message:({params:{discrError:t,tagName:e}})=>t===Ph.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,wo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},l1={keyword:"discriminator",type:"object",schemaType:"object",error:u1,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),u=e.const("tag",(0,wo._)`${r}${(0,wo.getProperty)(a)}`);e.if((0,wo._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:Ph.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let h=f();e.if(!1);for(let p in h)e.elseIf((0,wo._)`${u} === ${p}`),e.assign(c,l(h[p]));e.else(),t.error(!1,{discrError:Ph.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(h){let p=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(m,wo.Name),p}function f(){var h;let p={},m=S(o),b=!0;for(let B=0;B<i.length;B++){let G=i[B];if(G?.$ref&&!(0,c1.schemaHasRulesButRef)(G,s.self.RULES)){let He=G.$ref;if(G=Nx.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,He),G instanceof Nx.SchemaEnv&&(G=G.schema),G===void 0)throw new a1.default(s.opts.uriResolver,s.baseId,He)}let Ve=(h=G?.properties)===null||h===void 0?void 0:h[a];if(typeof Ve!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);b=b&&(m||S(G)),R(Ve,B)}if(!b)throw new Error(`discriminator: "${a}" must be required`);return p;function S({required:B}){return Array.isArray(B)&&B.includes(a)}function R(B,G){if(B.const)C(B.const,G);else if(B.enum)for(let Ve of B.enum)C(Ve,G);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function C(B,G){if(typeof B!="string"||B in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[B]=G}}}};Ah.default=l1});var Mx=Z((fB,d1)=>{d1.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 Oh=Z((Ie,Ih)=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.MissingRefError=Ie.ValidationError=Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=Ie.Ajv=void 0;var p1=Cv(),f1=Ox(),h1=jx(),Lx=Mx(),m1=["/properties"],pc="http://json-schema.org/draft-07/schema",vo=class extends p1.default{_addVocabularies(){super._addVocabularies(),f1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(h1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Lx,m1):Lx;this.addMetaSchema(e,pc,!1),this.refs["http://json-schema.org/schema"]=pc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(pc)?pc:void 0)}};Ie.Ajv=vo;Ih.exports=Ie=vo;Ih.exports.Ajv=vo;Object.defineProperty(Ie,"__esModule",{value:!0});Ie.default=vo;var g1=js();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return g1.KeywordCxt}});var xo=se();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return xo._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return xo.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return xo.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return xo.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return xo.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return xo.CodeGen}});var y1=Ha();Object.defineProperty(Ie,"ValidationError",{enumerable:!0,get:function(){return y1.default}});var b1=Ms();Object.defineProperty(Ie,"MissingRefError",{enumerable:!0,get:function(){return b1.default}})});var Hx=Z(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.formatNames=cr.fastFormats=cr.fullFormats=void 0;function ar(t,e){return{validate:t,compare:e}}cr.fullFormats={date:ar(qx,jh),time:ar(zh(!0),Mh),"date-time":ar(Dx(!0),Bx),"iso-time":ar(zh(),Fx),"iso-date-time":ar(Dx(),Vx),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:k1,"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:I1,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:S1,int32:{type:"number",validate:R1},int64:{type:"number",validate:P1},float:{type:"number",validate:Ux},double:{type:"number",validate:Ux},password:!0,binary:!0};cr.fastFormats={...cr.fullFormats,date:ar(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,jh),time:ar(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Mh),"date-time":ar(/^\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,Bx),"iso-time":ar(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Fx),"iso-date-time":ar(/^\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,Vx),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};cr.formatNames=Object.keys(cr.fullFormats);function _1(t){return t%4===0&&(t%100!==0||t%400===0)}var w1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,v1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function qx(t){let e=w1.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&&_1(r)?29:v1[n])}function jh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Ch=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function zh(t){return function(r){let n=Ch.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let l=s-d*c,f=o-u*c-(l<0?1:0);return(f===23||f===-1)&&(l===59||l===-1)&&i<61}}function Mh(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 Fx(t,e){if(!(t&&e))return;let r=Ch.exec(t),n=Ch.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 Nh=/t|\s/i;function Dx(t){let e=zh(t);return function(n){let o=n.split(Nh);return o.length===2&&qx(o[0])&&e(o[1])}}function Bx(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Vx(t,e){if(!(t&&e))return;let[r,n]=t.split(Nh),[o,s]=e.split(Nh),i=jh(r,o);if(i!==void 0)return i||Mh(n,s)}var x1=/\/|:/,$1=/^(?:[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 k1(t){return x1.test(t)&&$1.test(t)}var Zx=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function S1(t){return Zx.lastIndex=0,Zx.test(t)}var T1=-(2**31),E1=2**31-1;function R1(t){return Number.isInteger(t)&&t<=E1&&t>=T1}function P1(t){return Number.isInteger(t)}function Ux(){return!0}var A1=/[^\\]\\Z/;function I1(t){if(A1.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Kx=Z($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.formatLimitDefinition=void 0;var O1=Oh(),Jt=se(),Hr=Jt.operators,fc={formatMaximum:{okStr:"<=",ok:Hr.LTE,fail:Hr.GT},formatMinimum:{okStr:">=",ok:Hr.GTE,fail:Hr.LT},formatExclusiveMaximum:{okStr:"<",ok:Hr.LT,fail:Hr.GTE},formatExclusiveMinimum:{okStr:">",ok:Hr.GT,fail:Hr.LTE}},C1={message:({keyword:t,schemaCode:e})=>(0,Jt.str)`should be ${fc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Jt._)`{comparison: ${fc[t].okStr}, limit: ${e}}`};$o.formatLimitDefinition={keyword:Object.keys(fc),type:"string",schemaType:"string",$data:!0,error:C1,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 O1.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,Jt._)`${f}[${c.schemaCode}]`);t.fail$data((0,Jt.or)((0,Jt._)`typeof ${h} != "object"`,(0,Jt._)`${h} instanceof RegExp`,(0,Jt._)`typeof ${h}.compare != "function"`,l(h)))}function d(){let f=c.schema,h=a.formats[f];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let p=e.scopeValue("formats",{key:f,ref:h,code:i.code.formats?(0,Jt._)`${i.code.formats}${(0,Jt.getProperty)(f)}`:void 0});t.fail$data(l(p))}function l(f){return(0,Jt._)`${f}.compare(${r}, ${n}) ${fc[o].fail} 0`}},dependencies:["format"]};var z1=t=>(t.addKeyword($o.formatLimitDefinition),t);$o.default=z1});var Yx=Z((Ys,Jx)=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var ko=Hx(),N1=Kx(),Lh=se(),Wx=new Lh.Name("fullFormats"),j1=new Lh.Name("fastFormats"),Dh=(t,e={keywords:!0})=>{if(Array.isArray(e))return Gx(t,e,ko.fullFormats,Wx),t;let[r,n]=e.mode==="fast"?[ko.fastFormats,j1]:[ko.fullFormats,Wx],o=e.formats||ko.formatNames;return Gx(t,o,r,n),e.keywords&&(0,N1.default)(t),t};Dh.get=(t,e="full")=>{let n=(e==="fast"?ko.fastFormats:ko.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Gx(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Lh._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Jx.exports=Ys=Dh;Object.defineProperty(Ys,"__esModule",{value:!0});Ys.default=Dh});function M1(){let t=new Xx.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Qx.default)(t),t}var Xx,Qx,hc,e$=E(()=>{Xx=xc(Oh(),1),Qx=xc(Yx(),1);hc=class{constructor(e){this._ajv=e??M1()}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 mc,t$=E(()=>{so();mc=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(d=>d.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]:[],u=c.some(d=>d.type==="tool_use");if(i){if(s.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let d=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),l=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(d.size!==l.size||![...d].every(f=>l.has(f)))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},vs,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 r$(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 n$(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 o$=E(()=>{});var gc,s$=E(()=>{aw();so();e$();us();t$();o$();gc=class extends Ca{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 hc,this.setRequestHandler(Xd,n=>this._oninitialize(n)),this.setNotificationHandler(Qd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ip,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 mc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=iw(this._capabilities,e)}setRequestHandler(e,r){let o=Nr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Qn(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let d=zr(no,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new H(J.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,f=await Promise.resolve(r(c,u));if(l.task){let p=zr(to,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new H(J.InvalidParams,`Invalid task creation result: ${m}`)}return p.data}let h=zr(va,f);if(!h.success){let p=h.error instanceof Error?h.error.message:String(h.error);throw new H(J.InvalidParams,`Invalid tools/call result: ${p}`)}return h.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){n$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&r$(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:i_.includes(r)?r:Kd,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"},sa)}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(u=>u.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(u=>u.type==="tool_use");if(s){if(o.some(u=>u.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 u=new Set(a.filter(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(o.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))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},ap,r):this.request({method:"sampling/createMessage",params:e},vs,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 H(J.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof H?i:new H(J.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},cp,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 Zh(t){return!!t&&typeof t=="object"&&a$ in t}function c$(t){return t[a$]?.complete}var a$,i$,u$=E(()=>{a$=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(i$||(i$={}))});var l$=E(()=>{});function D1(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"),!L1.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 Z1(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 Uh(t){let e=D1(t);return Z1(t,e.warnings),e.isValid}var L1,d$=E(()=>{L1=/^[A-Za-z0-9._-]{1,128}$/});var yc,p$=E(()=>{yc=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 m$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function g$(t){return"_def"in t||"_zod"in t||m$(t)}function qh(t){return typeof t!="object"||t===null||g$(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(m$)}function f$(t){if(t){if(qh(t))return xn(t);if(!g$(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function q1(t){let e=Nr(t);return e?Object.entries(e).map(([r,n])=>{let o=Ib(n),s=Ob(n);return{name:r,description:o,required:!s}}):[]}function Kr(t){let r=Nr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Qn(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function h$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var bc,U1,Xs,y$=E(()=>{s$();us();Vp();so();u$();l$();d$();p$();Fn();bc=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 gc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new yc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Kr(wa)),this.server.assertCanSetRequestHandler(Kr(no)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(wa,()=>({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=Xn(r.inputSchema);return o?qp(o,{strictUnions:!0,pipeStrategy:"input"}):U1})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Xn(r.outputSchema);o&&(n.outputSchema=qp(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 H(J.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new H(J.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 H(J.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new H(J.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 H&&n.code===J.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=Xn(e.inputSchema)??e.inputSchema,i=await Xi(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Qi(a);throw new H(J.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 H(J.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Xn(e.outputSchema),s=await Xi(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Qi(i);throw new H(J.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,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,d));let l=await n.taskStore.getTask(c);if(!l)throw new H(J.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Kr(xa)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(xa,async e=>{switch(e.params.ref.type){case"ref/prompt":return x_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return $_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new H(J.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new H(J.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new H(J.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Xs;let s=Nr(n.argsSchema)?.[e.params.argument.name];if(!Zh(s))return Xs;let i=c$(s);if(!i)return Xs;let a=await i(e.params.argument.value,e.params.context);return h$(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 Xs;throw new H(J.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Xs;let s=await o(e.params.argument.value,e.params.context);return h$(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Kr(ma)),this.server.assertCanSetRequestHandler(Kr(ga)),this.server.assertCanSetRequestHandler(Kr(ya)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ma,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(ga,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ya,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new H(J.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 H(J.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Kr(ba)),this.server.assertCanSetRequestHandler(Kr(_a)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ba,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?q1(r.argsSchema):void 0}))})),this.server.setRequestHandler(_a,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new H(J.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new H(J.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Xn(n.argsSchema),s=await Xi(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Qi(c);throw new H(J.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}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:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:xn(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=xn(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 u=c instanceof ft?c._def?.innerType:c;return Zh(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Uh(e);let d={title:r,description:n,inputSchema:f$(o),outputSchema:f$(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&Uh(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=xn(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=xn(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}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(qh(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!qh(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==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:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,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()}},U1={type:"object",properties:{}};Xs={completion:{values:[],hasMore:!1}}});function B1(t){return h_.parse(JSON.parse(t))}function b$(t){return JSON.stringify(t)+`
|
|
938
|
+
`}var F1,_c,_$=E(()=>{so();F1=10*1024*1024,_c=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??F1}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(`
|
|
939
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),B1(r)}clear(){this._buffer=void 0}}});import w$ from"node:process";var wc,v$=E(()=>{_$();wc=class{constructor(e=w$.stdin,r=w$.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 _c({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=b$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var x$,$$=E(()=>{x$=[]});var O$={};Po(O$,{AUTHORING_MCP_SERVER_NAME:()=>R$,AUTHORING_MCP_SERVER_VERSION:()=>P$,AUTHORING_RESOURCES:()=>W1,AUTHORING_TOOLS:()=>K1,AUTHORING_TOOLS_PUBLIC:()=>I$,buildAuthoringMcpServer:()=>A$,runAuthoringMcpServer:()=>G1});import{promises as V1}from"node:fs";import{resolve as k$}from"node:path";function E$(){return T$??=import("../mcp/grounding.js").then(e=>e,()=>null),T$}function Je(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function H1(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 A$(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let l=await er(t.baseUrl);if(!l)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:l.baseUrl,token:l.token}}let r=t.grounding??{},n=await E$(),o=null;if(n)try{let l=await e();o={surface:"mcp-authoring",baseUrl:l.baseUrl,token:l.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(l=>({id:l.id,record_type:l.record_type,intent:l.intent}))}catch{c=[]}}let u=o?await H1(o,r):null,d=new bc({name:R$,version:P$},n?{instructions:n.renderAuthoringInstructions({baseUrl:o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(l=>l.id),deployedExtensions:u,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let l=o;for(let f of a)d.registerPrompt(f.id,{title:f.name,description:f.description},async()=>{let h=await n.getMcpPromptSkill(l,f.id,r);if(!h)throw new Error(`unknown prompt: ${f.id}`);return{description:h.description,messages:[{role:"user",content:{type:"text",text:(h.prompts??[]).join(`
|
|
940
|
+
|
|
941
|
+
`)}}]}})}return d.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:l,token:f}=await e(),h=await fetch(`${l}/v1/catalog/records`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!h.ok)throw new Error(`catalog fetch failed: ${h.status}`);return Je(await h.json())}),d.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:j.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".')}},async({recordType:l})=>{let{baseUrl:f,token:h}=await e(),p=await fetch(`${f}/v1/catalog/records/${encodeURIComponent(l)}`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(p.status===404)throw new Error(`unknown record type "${l}" \u2014 list them with catalog_get.`);if(!p.ok)throw new Error(`record anatomy fetch failed: ${p.status}`);return Je(await p.json())}),d.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:j.array(j.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].')}},async({recordTypes:l})=>{let{baseUrl:f,token:h}=await e(),p=new URLSearchParams({types:l.join(",")}),m=await fetch(`${f}/v1/catalog/columns?${p}`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(m.status===404)throw new Error(`none of those record types resolved: ${l.join(", ")} \u2014 list them with catalog_get.`);if(!m.ok)throw new Error(`common columns fetch failed: ${m.status}`);return Je(await m.json())}),d.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:l,token:f}=await e(),h=await fetch(`${l}/v1/catalog/census`,{headers:{Authorization:`Bearer ${f}`,Accept:"application/json"}});if(!h.ok)throw new Error(`catalog census failed: ${h.status}`);return Je(await h.json())}),d.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:j.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:j.enum(S$).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:j.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:l,kind:f,limit:h})=>{let{baseUrl:p,token:m}=await e(),b=new URLSearchParams({q:l});f&&b.set("kind",f),h!==void 0&&b.set("limit",String(h));let S=await fetch(`${p}/v1/catalog/objects?${b}`,{headers:{Authorization:`Bearer ${m}`,Accept:"application/json"}});if(!S.ok)throw new Error(`catalog object search failed: ${S.status}`);return Je(await S.json())}),d.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:j.enum(S$),externalId:j.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:l,externalId:f})=>{let{baseUrl:h,token:p}=await e(),m=await fetch(`${h}/v1/catalog/objects/${encodeURIComponent(l)}/${encodeURIComponent(f)}`,{headers:{Authorization:`Bearer ${p}`,Accept:"application/json"}});if(m.status===404)throw new Error(`unknown object ${l}:${f} \u2014 find it with search_catalog.`);if(!m.ok)throw new Error(`catalog object fetch failed: ${m.status}`);return Je(await m.json())}),d.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:j.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:j.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:l,limit:f})=>{let{baseUrl:h,token:p}=await e(),m=new URLSearchParams({q:l});f!==void 0&&m.set("limit",String(f));let b=await fetch(`${h}/v1/kb/search?${m}`,{headers:{Authorization:`Bearer ${p}`,Accept:"application/json"}});if(!b.ok)throw new Error(`kb search failed: ${b.status}`);return Je(await b.json())}),d.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:j.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:l})=>{let{baseUrl:f,token:h}=await e(),p=await fetch(`${f}/v1/kb/document/${encodeURIComponent(l)}`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!p.ok&&p.status!==404)throw new Error(`kb document fetch failed: ${p.status}`);return Je(await p.json())}),d.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:j.boolean().optional()}},async({recordsOnly:l})=>{let{baseUrl:f,token:h}=await e();return{content:[{type:"text",text:await Er({baseUrl:f,token:h,recordsOnly:l})}]}}),d.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:j.string(),event:j.string().optional(),template:j.enum(["require-field","enforce-format","blank"]).optional(),field:j.string().optional(),regex:j.string().optional(),source:j.string().optional(),id:j.string().optional()}},async l=>{let f=Hn("hook",{recordType:l.recordType,event:l.event,template:l.template,field:l.field,regex:l.regex,source:l.source,id:l.id});return Je({path:f.relativePath,content:f.content})}),d.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:j.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:j.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:j.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:j.string().optional().describe("Target record type (defaults to the trigger record type)."),event:j.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:j.string().optional()}},async l=>{let f=Hn("conduit",{recordType:l.recordType,source:l.source,to:l.to,toRecordType:l.toRecordType,event:l.event,id:l.id});return Je({path:f.relativePath,content:f.content})}),d.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:j.string().describe("The extension TS source."),samplesDir:j.string().optional().describe('Samples directory (default "samples").')}},async({source:l,samplesDir:f})=>{let h=k$(process.cwd(),f??"samples"),p=await Zo(h),m=await xi(l,p.map(S=>S.fixture)),b=m.filter(S=>!S.pass).length;return Je({total:m.length,passed:m.length-b,results:m})}),d.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:j.string(),recordType:j.string(),event:j.string(),source:j.string().describe('Adapter id or "standalone".'),sourceCode:j.string().describe("The verbatim extension TS."),extensionKind:j.string().optional()}},async l=>{let{baseUrl:f,token:h}=await e(),m=await new Re({baseUrl:f,token:h}).deploy({id:l.id,recordType:l.recordType,event:l.event,source:l.source,sourceCode:l.sourceCode,extensionKind:l.extensionKind});return Je(m)}),d.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:j.string(),limit:j.number().int().positive().optional()}},async({id:l,limit:f})=>{let{baseUrl:h,token:p}=await e(),m=new Re({baseUrl:h,token:p});return Je({id:l,logs:await m.logs(l,f)})}),d.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:l,token:f}=await e(),h=new Re({baseUrl:l,token:f});return Je(await h.appsList())}),d.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:j.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:j.string().optional().describe("Display name (defaults to the slug)."),description:j.string().optional().describe("Short description.")}},async({slug:l,name:f,description:h})=>{let{baseUrl:p,token:m}=await e(),b=new Re({baseUrl:p,token:m});return Je(await b.appsCreate({slug:l,name:f,description:h}))}),d.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:j.string().describe("App slug or id.")}},async({app:l})=>{let{baseUrl:f,token:h}=await e(),p=new Re({baseUrl:f,token:h});return Je(await p.appsPull(l))}),d.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:j.string().describe("App slug or id."),files:j.record(j.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:j.string().optional().describe("Short note stored with the revision.")}},async({app:l,files:f,note:h})=>{let{baseUrl:p,token:m}=await e(),b=new Re({baseUrl:p,token:m});return Je(await b.appsPush(l,f,{note:h}))}),d.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async l=>{let{baseUrl:f,token:h}=await e(),m=await(await fetch(`${f}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}})).text();return{contents:[{uri:l.href,mimeType:"application/json",text:m}]}}),d.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async l=>{let{baseUrl:f,token:h}=await e(),p=await Er({baseUrl:f,token:h});return{contents:[{uri:l.href,mimeType:"text/plain",text:p}]}}),d.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async l=>{let f=k$(process.cwd(),"samples"),h=[];try{h=(await V1.readdir(f)).filter(m=>m.endsWith(".json"))}catch{h=[]}let p=await Zo(f);return{contents:[{uri:l.href,mimeType:"application/json",text:JSON.stringify({files:h,samples:p.map(m=>m.fixture)},null,2)}]}}),d.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 l=>{let f=await E$(),h=[];if(f){let{baseUrl:p,token:m}=await e();h=await f.listRecipesForSurface({surface:"mcp-authoring",baseUrl:p,token:m},r)}return{contents:[{uri:l.href,mimeType:"application/json",text:JSON.stringify({recipes:h})}]}}),d}async function G1(t={}){let e=await A$(t),r=new wc;await e.connect(r)}var S$,T$,R$,P$,I$,K1,W1,C$=E(()=>{y$();v$();Fn();Qc();_i();Lo();cu();mu();$$();S$=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];R$="turbobase-authoring",P$="0.1.0";I$=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push"],K1=[...I$,...x$],W1=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as j$}from"node:child_process";import{promises as we}from"node:fs";import{homedir as J1}from"node:os";import{basename as M$,dirname as Qs,join as zn,relative as Fh,resolve as $e,sep as z$}from"node:path";var cm=xc(am(),1),{program:yj,createCommand:bj,createArgument:_j,createOption:wj,CommanderError:vj,InvalidArgumentError:xj,InvalidOptionArgumentError:$j,Command:um,Argument:kj,Option:Sj,Help:Tj}=cm.default;Qc();_i();Lo();cu();iu();import{promises as Hm}from"node:fs";function Bm(t,e){return e===t?"same-type-merge":"different-type-mint"}var Km=4;function uu(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Vn(t,"id"),r=Vn(t,"on"),n=Vn(t,"source"),o=Vn(t,"recordType"),s=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=Vn(s,"source"),a=Vn(s,"recordType"),c=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!o||!i||!a)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,toRecordType:a,cycleBudget:c?Number(c[1]):Km}}function Vn(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function ZS(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??{}}}async function Wm(t,e,r="fixture"){let n=e.name??r,o=[],s;try{s=uu(t)}catch(c){return{fixtureName:n,conduit:qS(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}let i=ZS(e),a=Object.entries(e.atlasLinks??{}).map(([c,u])=>({key:c,resolved:u}));try{let c=await vi(t),d=!!(await Do(c,i,{member:"when",timeoutMs:200})).whenResult;o.push({name:"from.when",status:d?"passed":"failed",detail:d?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let l=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${l} vs cycleBudget=${s.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),o.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)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!d)return{fixtureName:n,conduit:s,guards:o,whenPassed:d,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let f=await Do(c,i,{member:"transform",timeoutMs:200}),h=f.effects.logs,p=f.effects.result;if(!p||typeof p!="object")throw new Error(`conduit ${s.id} transform returned no result (expected { patch, createdFrom? })`);let m=p,b=Bm(s.fromRecordType,s.toRecordType),{wouldWriteBindings:S,masterAction:R}=US(s,b,e);return{fixtureName:n,conduit:s,guards:o,whenPassed:d,atlasResolutions:a,transformResult:m,applyBranch:b,wouldWriteBindings:S,masterAction:R,logs:h}}catch(c){return{fixtureName:n,conduit:s,guards:o,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:c instanceof Error?c.message:String(c)}}}function US(t,e,r){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function qS(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Km}}async function Gm(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 Jm(t){let e=await Hm.readFile(t,"utf8");return JSON.parse(e)}function Ym(t){return Hm.readFile(t,"utf8")}function Xm(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;let n=[];n.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),n.push(`conduit: ${r.id}`),n.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${r.toSource}.${r.toRecordType}${r.on?` on=${r.on}`:""}`),n.push(""),n.push("guards (dispatch order):");for(let o of t.guards){let s=o.status==="passed"?"\u2713":o.status==="failed"?"\u2717":"\u2298";n.push(` ${s} ${o.name} [${o.status}] \u2014 ${o.detail}`)}if(n.push(""),n.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)n.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let o of t.atlasResolutions)n.push(` ${o.key} \u2192 ${o.resolved===null?"null (no Atlas link \u2014 noted)":o.resolved}`);if(!t.whenPassed)return n.push(""),n.push("transform: SKIPPED (from.when gate did not fire)."),n.join(`
|
|
942
|
+
`);if(n.push(""),n.push("transform \u2192 patch:"),n.push(FS(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&n.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){n.push(""),n.push("conduit logs:");for(let o of t.logs)n.push(` [${o.level}] ${o.message}${o.meta?` ${JSON.stringify(o.meta)}`:""}`)}n.push(""),n.push(`apply-branch: ${t.applyBranch}`),n.push(` ${t.masterAction}`),n.push(""),n.push("bindings that WOULD be written (txn_source_link):");for(let o of t.wouldWriteBindings)n.push(` ${o.source} role=${o.role} external_id=${o.externalId??"null"} \u2014 ${o.why}`);return n.join(`
|
|
943
|
+
`)}function FS(t,e){return t.split(`
|
|
944
|
+
`).map(r=>e+r).join(`
|
|
945
|
+
`)}var BS="2026-01-01",Qm="2026-01-01T00:00:00.000Z";function VS(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"?BS:r.startsWith("timestamp")?Qm: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:Qm}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function HS(t){let e={};for(let r of t.columns)e[r.name]=VS(r.pgType,r.name);return e}function KS(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:HS(t)},expect:e.expect??"pass"}}function eg(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:KS(r,e)}))}import{promises as tg}from"node:fs";import{join as rg,relative as WS,sep as GS}from"node:path";var JS=67324752,YS=33639248,XS=101010256,QS=(()=>{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 e0(t){let e=4294967295;for(let r=0;r<t.length;r++)e=QS[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function t0(t){let e=[];async function r(n){let o=await tg.readdir(n,{withFileTypes:!0});for(let s of o){let i=rg(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(WS(t,i).split(GS).join("/"))}}return await r(t),e.sort(),e}async function ng(t){let e=await t0(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),u=await tg.readFile(rg(t,a)),d=e0(u),l=Buffer.alloc(30+c.length);l.writeUInt32LE(JS,0),l.writeUInt16LE(20,4),l.writeUInt16LE(0,6),l.writeUInt16LE(0,8),l.writeUInt32LE(d,14),l.writeUInt32LE(u.length,18),l.writeUInt32LE(u.length,22),l.writeUInt16LE(c.length,26),c.copy(l,30),r.push(l,u);let f=Buffer.alloc(46+c.length);f.writeUInt32LE(YS,0),f.writeUInt16LE(20,4),f.writeUInt16LE(20,6),f.writeUInt16LE(0,10),f.writeUInt32LE(d,16),f.writeUInt32LE(u.length,20),f.writeUInt32LE(u.length,24),f.writeUInt16LE(c.length,28),f.writeUInt32LE(o,42),c.copy(f,46),n.push(f),o+=l.length+u.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(XS,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}}function r0(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function $i(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function n0(t){let e=og(t,"from"),r=og(t,"to");return{fromSource:e?$i(e,"source"):void 0,fromRecordType:e?$i(e,"recordType"):void 0,toSource:r?$i(r,"source"):void 0,toRecordType:r?$i(r,"recordType"):void 0}}function og(t,e){let r=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!r)return null;let n=0,o=r.index+r[0].length-1;for(let s=o;s<t.length;s+=1){let i=t[s];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return t.slice(o+1,s)}return null}function o0(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 s0(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function i0(t){return/\bcreatedFrom\b/.test(t)}function sg(t){let e=r0(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:o,fromRecordType:s,toRecordType:i}=n0(t);n&&o&&n===o&&r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \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.`});let a=o0(t);if(a!==null){let u=/\bexternalId\b/.test(a),d=/\bfromSource\b/.test(a);!u&&!d&&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}``."})}s&&i&&s!==i&&!i0(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} 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 c=s0(t,"cycleBudget");return c!==void 0&&(c<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${c} 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)."}):c>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${c} 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 ig(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(`
|
|
946
|
+
`);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(`
|
|
947
|
+
lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
|
|
948
|
+
`)}function ag(t){return t.cases.filter(e=>e.status==="failed").length}function qo(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function a0(t){let e=ag(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${qo(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${qo(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${qo(n.type)}"`:"";r.push(` <failure${i} message="${qo(s)}">${qo(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
|
|
949
|
+
`)}
|
|
950
|
+
`}function c0(t){let e={suite:t.name,tests:t.cases.length,failures:ag(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
|
|
951
|
+
`}function ki(t,e){return e==="junit"?a0(t):c0(t)}var mt={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"},vt={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Si=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],It={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},cg=/\x1b\[[0-9;]*m/g;function mr(t){return t.replace(cg,"").length}function lu(t,e){return e<=0?1:Math.max(1,Math.ceil(mr(t)/e))}function u0(){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 du=u0();function xt(){return du}function pu(t){du=t}function pn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Ot(t,e){return du?`${t}${e}${mt.reset}`:e}var O={bold:t=>Ot(mt.bold,t),dim:t=>Ot(mt.dim,t),red:t=>Ot(mt.red,t),green:t=>Ot(mt.green,t),yellow:t=>Ot(mt.yellow,t),blue:t=>Ot(mt.blue,t),magenta:t=>Ot(mt.magenta,t),cyan:t=>Ot(mt.cyan,t),grey:t=>Ot(mt.grey,t)};var $t={success:t=>`${O.green("\u2713")} ${t}`,error:t=>`${O.red("\u2716")} ${t}`,warn:t=>`${O.yellow("\u26A0")} ${t}`,info:t=>`${O.dim("\xB7")} ${t}`,step:t=>`${O.cyan("\u25B8")} ${t}`},Pr={add:t=>O.green(`+ ${t}`),change:t=>O.yellow(`~ ${t}`),destroy:t=>O.red(`- ${t}`)},l0=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),d0=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),p0=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Fo(t){let e=t.toLowerCase();return l0.has(e)?O.green(t):d0.has(e)?O.red(t):p0.has(e)?O.yellow(t):t}function Ar(t,e=[]){let r=Math.max(mr(t),...e.map(mr),0),n=r+2,o=O.cyan(It.v),s=a=>` ${a}${" ".repeat(r-mr(a))} `,i=[O.cyan(`${It.tl}${It.h.repeat(n)}${It.tr}`),`${o}${O.bold(s(t))}${o}`];if(e.length){i.push(`${O.cyan(It.ml)}${O.dim(It.h.repeat(n))}${O.cyan(It.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(O.cyan(`${It.bl}${It.h.repeat(n)}${It.br}`)),i.join(`
|
|
952
|
+
`)}function Ti(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(u=>u.length)),i=[];for(let u=0;u<s;u+=1)i[u]=Math.max(0,...o.map(d=>mr(d[u]??"")));let a=u=>{let d=u.map((l,f)=>{let h=l??"";return f===u.length-1?h:h+" ".repeat(Math.max(0,i[f]-mr(h)))});return r+d.join(n)},c=[];e.head&&(c.push(a(e.head.map(u=>O.bold(u)))),c.push(a(e.head.map((u,d)=>O.dim("\u2500".repeat(i[d]??mr(u)))))));for(let u of t)c.push(a(u));return c.join(`
|
|
953
|
+
`)}function fu(t="extension authoring CLI"){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`${xt()?e.map(n=>Ot(mt.cyan,n)).join(`
|
|
954
|
+
`):e.join(`
|
|
955
|
+
`)}
|
|
956
|
+
${O.dim(` ${t}`)}`}var Bo=t=>{process.stderr.write(t)};function hu(){return xt()&&process.stderr.isTTY===!0}async function Ce(t,e){let r=hu(),n=0,o;r&&(Bo(vt.hideCursor),o=setInterval(()=>{Bo(`${vt.col0}${vt.clearLine}${O.magenta(Si[n++%Si.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Bo(`${vt.col0}${vt.clearLine}${vt.showCursor}`)};try{let i=await e();return s(),r&&Bo(`${$t.success(t)}
|
|
957
|
+
`),i}catch(i){throw s(),r&&Bo(`${$t.error(t)}
|
|
958
|
+
`),i}}function fn(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(m=>!m.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=m=>{process.stderr.write(m)},c=process.stdin,u=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${O.bold(O.cyan("?"))} ${O.bold(t)}
|
|
959
|
+
`),a(`${O.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
960
|
+
`),a(vt.hideCursor);let d=0,l=()=>{let m=process.stderr.columns??process.stdout.columns??80;d>0&&(a(vt.cursorUp(d)),a(vt.clearToEnd));let b=0;for(let S=0;S<e.length;S+=1){let R=e[S],C=S===i,B=C?O.cyan("\u25B6"):" ",G=R.disabled?O.grey(R.label):C?O.bold(O.cyan(R.label)):R.label,Ve=R.description?` ${O.dim(R.description)}`:"",He=` ${B} ${G}${Ve}`;a(`\r${He}
|
|
961
|
+
`),b+=lu(He,m)}d=b},f=()=>{c.removeListener("data",p),c.setRawMode?.(u??!1),c.pause(),a(vt.showCursor)},h=m=>{let b=i;for(let S=0;S<e.length;S+=1)if(b=(b+m+e.length)%e.length,!e[b].disabled){i=b;return}},p=m=>{let b=m.toString("utf8");if(b===""||b==="q"){f(),a(`
|
|
962
|
+
`),o(new Error("aborted"));return}if(b==="\r"||b===`
|
|
963
|
+
`){let R=e[i];if(R.disabled)return;f(),n(R.value);return}if(b==="\x1B[A"||b==="k"){h(-1),l();return}if(b==="\x1B[B"||b==="j"){h(1),l();return}let S=Number(b);Number.isFinite(S)&&S>=1&&S<=e.length&&!e[S-1].disabled&&(i=S-1,l())};c.on("data",p),l()})}function lg(t,e){return`${Fo(t)}${" ".repeat(Math.max(0,e-t.length))}`}var h0=t=>new Promise(e=>setTimeout(e,t));function ug(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}] ${lg(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function dg(t,e,r={}){let n=r.sink??(d=>{process.stdout.write(`${d}
|
|
964
|
+
`)}),o=r.sleep??h0,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 d of[...i].reverse())n(ug(d)),a+=1,d.updatedAt>c&&(c=d.updatedAt);if(!r.follow)return a;let u=r.maxPolls??Number.POSITIVE_INFINITY;for(let d=0;d<u;d+=1){await o(s);let l=await t.conduitEvents(e,{since:c||void 0,limit:200});for(let f of[...l].reverse())n(ug(f)),a+=1,f.updatedAt>c&&(c=f.updatedAt)}return a}function m0(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${lg(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function pg(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
|
|
965
|
+
`)});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(m0(o));return r(`
|
|
966
|
+
binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}mu();function hg(t){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?{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var _0=[".mcp.json"];function gg(t,e=_0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
|
|
967
|
+
`).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(`
|
|
968
|
+
`)?t:`${t}
|
|
969
|
+
`}
|
|
970
|
+
# Added by the TurboBase scaffold.
|
|
971
|
+
${o.join(`
|
|
972
|
+
`)}
|
|
973
|
+
`}var w0=`# TurboBase Extensions \u2014 extension project
|
|
974
|
+
|
|
975
|
+
This directory authors **TurboBase extensions** (hooks today; conduits later)
|
|
976
|
+
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
977
|
+
through the local MCP server (\`.mcp.json\`) and the skills under \`.claude/skills/\`.
|
|
978
|
+
|
|
979
|
+
## Layout
|
|
980
|
+
|
|
981
|
+
- \`hooks/\` \u2014 your hook files (one self-contained \`defineHook({...})\` per file).
|
|
982
|
+
- \`samples/\` \u2014 JSON fixtures \`turbobase ext test\` runs each hook against.
|
|
983
|
+
- \`types.ts\` \u2014 generated record + PostgREST types (\`turbobase project types\`); refreshed
|
|
984
|
+
automatically on each Claude Code session start.
|
|
985
|
+
|
|
986
|
+
## Workflow
|
|
987
|
+
|
|
988
|
+
1. \`turbobase auth login\` \u2014 sign in as an instance admin; stores a personal access token (PAT).
|
|
989
|
+
2. \`turbobase project types\` \u2014 regenerate \`types.ts\` from the instance catalog.
|
|
990
|
+
3. \`turbobase ext new hook --record=<type> --event=before_save --field=<name>\` \u2014 scaffold.
|
|
991
|
+
4. Edit the hook; add fixtures under \`samples/\`.
|
|
992
|
+
5. \`turbobase ext test hooks/<...>.ts\` \u2014 dry-run against the fixtures (same isolate as prod).
|
|
993
|
+
6. \`turbobase ext deploy hooks/<...>.ts\` \u2014 deploy (lands active).
|
|
994
|
+
7. \`turbobase ext logs <id>\` \u2014 tail the deployed hook's logs.
|
|
995
|
+
|
|
996
|
+
## Rules
|
|
997
|
+
|
|
998
|
+
- A hook is **pure and credentials-free**: no secrets, no network, no Node
|
|
999
|
+
builtins. The sandbox fences every import except \`@turbobase/extensions\`.
|
|
1000
|
+
- One concern per file. Do not factor shared logic into a \`lib/\` \u2014 inline it.
|
|
1001
|
+
|
|
1002
|
+
## Record what you learn about THIS customer \u2014 continuously
|
|
1003
|
+
|
|
1004
|
+
**\`INSTANCE-LEARNINGS.md\`** is the standing write-up of how this instance's
|
|
1005
|
+
source system is actually set up \u2014 which is exactly the knowledge a hook has to
|
|
1006
|
+
be right about: which field a rule must really read, which records arrive with
|
|
1007
|
+
it empty, what a status code means in this account, whether a link lives on the
|
|
1008
|
+
header or only on the line. It feeds the knowledge base, so every claim in it
|
|
1009
|
+
carries the record ids it was verified against.
|
|
1010
|
+
|
|
1011
|
+
Add to it whenever you establish a fact about the CUSTOMER'S SETUP that was not
|
|
1012
|
+
already written down \u2014 especially when real rows contradicted an assumption
|
|
1013
|
+
(yours, the catalog's, the knowledge base's, or a field label's). A hook you had
|
|
1014
|
+
to write defensively is a fact about the data worth recording, not just a
|
|
1015
|
+
\`?? null\`.
|
|
1016
|
+
|
|
1017
|
+
**Both halves, in the same change.** The numbered sections hold the finding;
|
|
1018
|
+
\`## Suggested KB edits\` holds what to DO about it \u2014 the knowledge-base page to
|
|
1019
|
+
change, or "new page for \`<record>\`". When the data contradicts a PUBLISHED
|
|
1020
|
+
knowledge-base claim, the row goes in \`## Knowledge-base corrections\` instead
|
|
1021
|
+
(KB claim / Live value / Verdict); that is the only way a stale published fact
|
|
1022
|
+
gets caught. A finding added without its entry is half-done. Neither waits for
|
|
1023
|
+
the end of a task, and neither waits to be asked.
|
|
1024
|
+
|
|
1025
|
+
## Feed problems back to TurboBase \u2014 continuously
|
|
1026
|
+
|
|
1027
|
+
Keep **\`TURBOBASE-FEEDBACK.md\`** up to date AS YOU WORK. It is the channel to the
|
|
1028
|
+
TurboBase product team, and the entries worth most are the ones written the
|
|
1029
|
+
moment they cost you time \u2014 they evaporate from memory otherwise.
|
|
1030
|
+
|
|
1031
|
+
Append an entry whenever the PLATFORM itself (not your own code) causes trouble:
|
|
1032
|
+
a fixture shape that did not match the live event payload, an import the sandbox
|
|
1033
|
+
fenced with no hint of what to use instead, a hook that passed \`turbobase ext test\`
|
|
1034
|
+
and behaved differently deployed, a misleading CLI error, a type the generator
|
|
1035
|
+
did not emit, a confusing default. For each, note: what you expected, what
|
|
1036
|
+
happened, the concrete cost, and the fix or workaround. Skip anything that is
|
|
1037
|
+
just your own bug. Keep \`## What would have helped most, in order\` ranked \u2014 the
|
|
1038
|
+
order is the signal, and it is the part the product team reads first.
|
|
1039
|
+
|
|
1040
|
+
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
1041
|
+
updating a test. It is checked into the repo so the whole team sees it.
|
|
1042
|
+
`,v0=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)+`
|
|
1043
|
+
`;function x0(t){return`---
|
|
1044
|
+
name: generate-types
|
|
1045
|
+
description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
1046
|
+
---
|
|
1047
|
+
|
|
1048
|
+
Run \`turbobase project types -o ${t}\` to fetch the instance's record shapes
|
|
1049
|
+
(/v1/catalog/records) and PostgREST operations (/v1/catalog/openapi.json) and
|
|
1050
|
+
write \`${t}\`. Import the generated record interfaces for typed rows.
|
|
1051
|
+
|
|
1052
|
+
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
1053
|
+
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
1054
|
+
`}var $0=`---
|
|
1055
|
+
name: mock-test
|
|
1056
|
+
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
1057
|
+
---
|
|
1058
|
+
|
|
1059
|
+
Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
1060
|
+
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
1061
|
+
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
1062
|
+
fixture for each branch (a passing record and a rejecting record).
|
|
1063
|
+
`,k0=`---
|
|
1064
|
+
name: deploy
|
|
1065
|
+
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
1066
|
+
---
|
|
1067
|
+
|
|
1068
|
+
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
1069
|
+
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
1070
|
+
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
1071
|
+
`;function S0(t){return`# ${t} \u2014 TurboBase app
|
|
1072
|
+
|
|
1073
|
+
This directory is a **hosted TurboBase app**: a Vite + React + TS SPA served
|
|
1074
|
+
same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
|
|
1075
|
+
(Claude Code) reach the instance through the two MCP servers in \`.mcp.json\`.
|
|
1076
|
+
|
|
1077
|
+
## Know the instance before you write code
|
|
1078
|
+
|
|
1079
|
+
Ground first, code second \u2014 the instance already knows this business.
|
|
1080
|
+
|
|
1081
|
+
- **\`INSTANCE.md\`** \u2014 the grounding brief (source primer, record anatomy,
|
|
1082
|
+
knowledge-base retrieval), refreshed each session. READ IT FIRST. Once you
|
|
1083
|
+
know which records the app is about, widen it:
|
|
1084
|
+
\`turbobase project grounding --records purchaseOrder,itemReceipt -o INSTANCE.md\` \u2014
|
|
1085
|
+
the session hook keeps that focus on later refreshes.
|
|
1086
|
+
- \`record_anatomy\` (authoring MCP) \u2014 ONE record in depth: field meanings,
|
|
1087
|
+
sublists, gotchas, authored display contracts. Read it before building UI
|
|
1088
|
+
over a record.
|
|
1089
|
+
- \`search_documentation\` / \`read_document\` (authoring MCP) \u2014 the published
|
|
1090
|
+
knowledge base: how this business runs its processes. For a CUSTOM record
|
|
1091
|
+
the KB + \`search_catalog\`/\`explain_object\` are the only spec that exists.
|
|
1092
|
+
- \`list_records\` / \`get_record\` (data MCP) \u2014 real rows, through the signed-in
|
|
1093
|
+
user's row-level security. What you can't see here, the app can't see either.
|
|
1094
|
+
|
|
1095
|
+
Read the catalog BEFORE writing a query. A column that doesn't exist fails at
|
|
1096
|
+
runtime, not at build \u2014 \`npm run build\` will happily compile it. And RENDER
|
|
1097
|
+
display columns, not identifiers: \`src/types.ts\` marks each column's role and
|
|
1098
|
+
its id\u2194display twin ("identifier \u2014 render entity_name instead"). A table cell
|
|
1099
|
+
showing \`entity_id\` where \`entity_name\` exists is wrong.
|
|
1100
|
+
|
|
1101
|
+
## What the mirror does NOT look like
|
|
1102
|
+
|
|
1103
|
+
Five facts that produce a WORKING BUILD and a WRONG SCREEN. Each one fails
|
|
1104
|
+
silently \u2014 the query succeeds, the page renders, the data is absent or wrong.
|
|
1105
|
+
Check them before you trust a result.
|
|
1106
|
+
|
|
1107
|
+
1. **A \`jsonb\` custom field holds a BARE id, not \`{value, text}\`.**
|
|
1108
|
+
\`cf_ns_custrecord_vendor\` is \`1074\`, not \`{value: 1074, text: "FedEx"}\`.
|
|
1109
|
+
There is NO display twin for custom fields \u2014 resolve the id yourself. Build
|
|
1110
|
+
on the envelope assumption and every cell renders empty, which is
|
|
1111
|
+
indistinguishable from an empty table.
|
|
1112
|
+
2. **The obvious lookup table is often the wrong one.** A List/Record field
|
|
1113
|
+
named after a custom record may point somewhere else entirely (a carrier
|
|
1114
|
+
field pointing at \`entity\` \u2014 vendors \u2014 not \`customrecord_carrier\`). Confirm
|
|
1115
|
+
the target by checking that real ids resolve, not by the name.
|
|
1116
|
+
3. **Some tables mix kinds in one id space.** \`entity\` holds customers AND
|
|
1117
|
+
vendors; the same id is a valid row of each. \`order\` holds every connector's
|
|
1118
|
+
orders. The catalog marks these (\`sharedTable\`) \u2014 apply the discriminator
|
|
1119
|
+
(\`entity_type=eq.vendor\`, \`source_system=eq.netsuite\`) or you will label a
|
|
1120
|
+
vendor with a customer's name.
|
|
1121
|
+
4. **\`created_at\` / \`updated_at\` / \`synced_at\` / \`last_modified_pg\` are MIRROR
|
|
1122
|
+
timestamps** \u2014 when TurboBase wrote the row. After a bulk sync they are
|
|
1123
|
+
identical across the table, so ordering by one gives sync batch order, not
|
|
1124
|
+
business order. Use \`source_modified\`, or the source's own date in \`raw\`.
|
|
1125
|
+
5. **A column can exist and be empty on every row.** \`currency_name\` and
|
|
1126
|
+
\`subsidiary_name\` are often NULL while \`currency_id\` / \`subsidiary_id\` carry
|
|
1127
|
+
the data. Check one real row before rendering a column, not just the schema.
|
|
1128
|
+
|
|
1129
|
+
## Reading efficiently (and not tripping the edge)
|
|
1130
|
+
|
|
1131
|
+
- **Never select bare \`raw\`** on a wide table \u2014 it is the entire source
|
|
1132
|
+
document and the response can be big enough to fail at the edge (502).
|
|
1133
|
+
Project the ONE key you need: \`select=external_id,ship:raw->custbody_x\`.
|
|
1134
|
+
- **Cap your concurrency.** A page that fans out ~25 parallel reads on load will
|
|
1135
|
+
trip rate limiting (HTTP 429). Keep a handful in flight, space them slightly,
|
|
1136
|
+
and retry on 429 honouring \`retry_after\`. Load what the first screen needs;
|
|
1137
|
+
fetch the rest on demand.
|
|
1138
|
+
- **PostgREST fails the WHOLE request on one unknown column** (\`42703\`), so a
|
|
1139
|
+
single wrong name in a \`select\` loses the entire table. Transaction tables are
|
|
1140
|
+
NOT uniform \u2014 \`memo\`, \`total\`, \`created_from_id\`, even \`pg_row_id\` are missing
|
|
1141
|
+
from some. Verify each column against the catalog per table rather than
|
|
1142
|
+
assuming a shared shape.
|
|
1143
|
+
|
|
1144
|
+
## Layout
|
|
1145
|
+
|
|
1146
|
+
- \`src/App.tsx\` \u2014 the app. Start here.
|
|
1147
|
+
- \`src/lib/turbobase.ts\` \u2014 the auth-wired client. Don't rewrite it; import from it.
|
|
1148
|
+
- \`src/types.ts\` \u2014 generated record types (\`turbobase project types -o src/types.ts\`),
|
|
1149
|
+
refreshed at the start of every Claude Code session.
|
|
1150
|
+
- \`INSTANCE.md\` \u2014 the grounding brief (\`turbobase project grounding\`), refreshed
|
|
1151
|
+
each session; instance-specific, don't hand-edit.
|
|
1152
|
+
- \`vite.config.ts\` \u2014 \`base\` is pinned to \`/a/${t}/\` and MUST stay that way, or
|
|
1153
|
+
every asset 404s and the page renders blank with no console error. The
|
|
1154
|
+
\`server.proxy\` block is dev-only.
|
|
1155
|
+
|
|
1156
|
+
## Reads and writes are different surfaces
|
|
1157
|
+
|
|
1158
|
+
- **Read** with \`select('<table>?select=...')\` \u2192 PostgREST, row-level-security scoped.
|
|
1159
|
+
- **Write** with \`write('<recordType>', { parent, lines })\` \u2192 \`POST /v1/data/:recordType\`,
|
|
1160
|
+
the canonical write boundary. **Never** write a table directly through PostgREST.
|
|
1161
|
+
|
|
1162
|
+
Both are same-origin and carry the session cookie. There are no app-owned keys,
|
|
1163
|
+
no Bearer tokens to manage, and no sign-in page to build \u2014 the instance handles
|
|
1164
|
+
auth before your SPA loads.
|
|
1165
|
+
|
|
1166
|
+
**Reading data yourself, without a browser.** The PAT in \`.mcp.json\` authenticates
|
|
1167
|
+
the authoring MCP, but PostgREST rejects it outright (\`PGRST301 \u2026 Expected 3
|
|
1168
|
+
parts; got 1\`) \u2014 it is an opaque bearer, not a JWT. To read rows from a script or
|
|
1169
|
+
a terminal, trade it for a short-lived session first:
|
|
1170
|
+
|
|
1171
|
+
\`\`\`sh
|
|
1172
|
+
curl -sX POST "$INSTANCE/auth/pat-exchange" -H "Authorization: Bearer $PAT"
|
|
1173
|
+
# \u2192 { "token": "<15-min session JWT>", ... }
|
|
1174
|
+
curl -s "$INSTANCE/rest/v1/<table>?select=..." \\
|
|
1175
|
+
-H "Authorization: Bearer $SESSION" -H "apikey: $SESSION"
|
|
1176
|
+
\`\`\`
|
|
1177
|
+
|
|
1178
|
+
The PAT must carry the \`data:read\` scope (Settings \u203A Tokens) \u2014 it is opt-in, so
|
|
1179
|
+
a token minted without it gets \`403 insufficient_scope\`. PostgREST wants the JWT
|
|
1180
|
+
in BOTH the \`Authorization\` and \`apikey\` positions.
|
|
1181
|
+
|
|
1182
|
+
**\`permission denied for table <x>\` usually means NOT SIGNED IN.** With no
|
|
1183
|
+
session, PostgREST answers as the anonymous role and every table denies \u2014 it
|
|
1184
|
+
reads like an RLS problem and is not one. Check the session before the grants.
|
|
1185
|
+
|
|
1186
|
+
## Workflow
|
|
1187
|
+
|
|
1188
|
+
1. \`npm install && npm run dev\` \u2014 the app is at **http://localhost:3000/a/${t}/**,
|
|
1189
|
+
NOT \`/\` (Vite serves under \`base\`; \`/\` 302s there). The dev server proxies
|
|
1190
|
+
\`/rest\`, \`/realtime\`, \`/v1\`, \`/auth\`, \`/login\` and \`/_app\` to the instance, so
|
|
1191
|
+
localhost behaves same-origin. Sign in through the proxy on first load.
|
|
1192
|
+
(\`/_app\` carries the sign-in page's own JS/CSS \u2014 without it the login form
|
|
1193
|
+
renders but never hydrates, and you stay signed out silently.)
|
|
1194
|
+
2. Build the thing. Verify in the browser \u2014 a green \`npm run build\` proves the
|
|
1195
|
+
code is well-formed, not that it runs.
|
|
1196
|
+
3. \`turbobase apps push ${t} .\` \u2014 record the source on the instance (source of
|
|
1197
|
+
record lives there, not on this laptop). Nothing goes live.
|
|
1198
|
+
4. \`turbobase apps deploy ${t}\` \u2014 build + go live at \`/a/${t}\`.
|
|
1199
|
+
|
|
1200
|
+
Push and deploy are separate on purpose: push often while iterating, deploy when
|
|
1201
|
+
it's ready.
|
|
1202
|
+
|
|
1203
|
+
## Rules
|
|
1204
|
+
|
|
1205
|
+
- \`.mcp.json\` holds a live access token. It is gitignored \u2014 keep it that way.
|
|
1206
|
+
- Don't add a sign-in page, a login route, or token handling. The instance owns auth.
|
|
1207
|
+
- Don't hardcode an instance hostname; the app is served same-origin.
|
|
1208
|
+
|
|
1209
|
+
## Record what you learn about THIS customer \u2014 continuously
|
|
1210
|
+
|
|
1211
|
+
**\`INSTANCE-LEARNINGS.md\`** is the standing write-up of how this instance's
|
|
1212
|
+
source system is actually set up: which custom field carries which link, which
|
|
1213
|
+
half of a paired document holds the parent id, where a parent id really lives,
|
|
1214
|
+
what a custom record's columns mean, which column is present on every row and
|
|
1215
|
+
populated on none. It feeds the knowledge base, so every claim in it carries the
|
|
1216
|
+
record ids it was verified against.
|
|
1217
|
+
|
|
1218
|
+
Add to it whenever you establish a fact about the CUSTOMER'S SETUP that was not
|
|
1219
|
+
already written down \u2014 especially when the data contradicted an assumption
|
|
1220
|
+
(yours, the catalog's, the knowledge base's, or a field label's). The most
|
|
1221
|
+
valuable entries are the ones that produced a working build and a wrong screen,
|
|
1222
|
+
because nothing else in the system will ever announce them.
|
|
1223
|
+
|
|
1224
|
+
**Both halves, in the same change.** The numbered sections hold the finding;
|
|
1225
|
+
\`## Suggested KB edits\` holds what to DO about it \u2014 the knowledge-base page to
|
|
1226
|
+
change, or "new page for \`<record>\`". When the data contradicts a PUBLISHED
|
|
1227
|
+
knowledge-base claim, the row goes in \`## Knowledge-base corrections\` instead
|
|
1228
|
+
(KB claim / Live value / Verdict); that is the only way a stale published fact
|
|
1229
|
+
gets caught. The lists are what the knowledge base actually consumes, so a
|
|
1230
|
+
finding added without its entry is half-done. Neither waits for the end of a
|
|
1231
|
+
task, and neither waits to be asked.
|
|
1232
|
+
|
|
1233
|
+
Same discipline as the feedback file, different audience: that one is about the
|
|
1234
|
+
platform, this one is about the business.
|
|
1235
|
+
|
|
1236
|
+
## Feed problems back to TurboBase \u2014 continuously
|
|
1237
|
+
|
|
1238
|
+
Keep **\`TURBOBASE-FEEDBACK.md\`** up to date AS YOU WORK. It is the channel to the
|
|
1239
|
+
TurboBase product team, and the entries worth most are the ones written the
|
|
1240
|
+
moment they cost you time \u2014 they evaporate from memory otherwise.
|
|
1241
|
+
|
|
1242
|
+
Append an entry whenever the PLATFORM itself (not your own code) causes trouble:
|
|
1243
|
+
a scaffold gap, a misleading error, a query that compiled but returned the wrong
|
|
1244
|
+
shape, a catalog fact that produced a working build and a wrong screen, a missing
|
|
1245
|
+
tool, a confusing default, a rate limit you had to discover by hitting it. For
|
|
1246
|
+
each, note: what you expected, what happened, the concrete cost, and the fix or
|
|
1247
|
+
workaround. Skip anything that is just your own bug. Keep
|
|
1248
|
+
\`## What would have helped most, in order\` ranked \u2014 the order is the signal, and
|
|
1249
|
+
it is the part the product team reads first.
|
|
1250
|
+
|
|
1251
|
+
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like updating
|
|
1252
|
+
a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
1253
|
+
review, so what you write reaches the knowledge base and the product team instead
|
|
1254
|
+
of evaporating at the end of the session. Keep the section headings exactly as
|
|
1255
|
+
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
1256
|
+
`}var T0="---\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",E0=`---
|
|
1257
|
+
name: ship-app
|
|
1258
|
+
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
1259
|
+
---
|
|
1260
|
+
|
|
1261
|
+
Two verbs, deliberately separate:
|
|
1262
|
+
|
|
1263
|
+
1. \`turbobase apps push <slug> .\` \u2014 records the local tree as a new source
|
|
1264
|
+
revision on the instance. Nothing is built, nothing changes for users. Skip it
|
|
1265
|
+
and the changes exist only on this laptop: the next \`apps pull\`, from any
|
|
1266
|
+
machine, returns the version before them.
|
|
1267
|
+
2. \`turbobase apps deploy <slug>\` \u2014 builds locally and uploads the result. THIS
|
|
1268
|
+
is what goes live, at \`/a/<slug>\`.
|
|
1269
|
+
|
|
1270
|
+
Push freely while iterating; deploy when it's ready. Deploy runs the build, so a
|
|
1271
|
+
broken build fails the deploy rather than shipping a blank page.
|
|
1272
|
+
|
|
1273
|
+
**When someone else has to approve the change, deploy it as a preview first:**
|
|
1274
|
+
|
|
1275
|
+
\`\`\`
|
|
1276
|
+
turbobase apps deploy <slug> --preview --label "what changed"
|
|
1277
|
+
\`\`\`
|
|
1278
|
+
|
|
1279
|
+
That builds and uploads exactly as \`deploy\` does, but serves the result at its
|
|
1280
|
+
own URL and leaves \`/a/<slug>\` untouched. Send the URL to whoever asked for the
|
|
1281
|
+
change \u2014 it opens for anyone who can already open the app, so no new access is
|
|
1282
|
+
granted. Then:
|
|
1283
|
+
|
|
1284
|
+
- \`turbobase apps promote <slug> <preview-id>\` makes it live. The reviewed bytes
|
|
1285
|
+
go live as-is; nothing is rebuilt, so what ships is what was approved.
|
|
1286
|
+
- \`turbobase apps preview discard <slug> <preview-id>\` closes it.
|
|
1287
|
+
- \`turbobase apps preview list <slug>\` shows what's open.
|
|
1288
|
+
|
|
1289
|
+
Previews expire after 7 days. Several can be open at once, each with its own URL.
|
|
1290
|
+
|
|
1291
|
+
Note \`--preview\` needs the CLI to run the build (it sets the bundle's asset
|
|
1292
|
+
paths); it is refused with \`--no-build\` rather than shipping a blank page.
|
|
1293
|
+
|
|
1294
|
+
Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`, \`.git/\`,
|
|
1295
|
+
\`.claude/\` (agent state, and any nested worktrees under it) and anything
|
|
1296
|
+
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
1297
|
+
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
1298
|
+
project root and DO travel \u2014 deploy reads them.
|
|
1299
|
+
`;function R0(t){return`---
|
|
1300
|
+
name: record-learning
|
|
1301
|
+
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.
|
|
1302
|
+
---
|
|
1303
|
+
|
|
1304
|
+
Two standing files at the project root, two audiences. Both are updated in the
|
|
1305
|
+
SAME change that produced the fact. Batching them to the end of a task is how
|
|
1306
|
+
they end up empty: a finding that is not written down while it is still
|
|
1307
|
+
surprising gets normalised into the code and lost.
|
|
1308
|
+
|
|
1309
|
+
**\`INSTANCE-LEARNINGS.md\` \u2014 about the CUSTOMER.** How this instance's source
|
|
1310
|
+
system is actually set up. Append a numbered section when a field holds something
|
|
1311
|
+
other than its name suggests, when a link between two records is found (or found
|
|
1312
|
+
to be ABSENT \u2014 the expensive kind, since nothing in the schema announces it), or
|
|
1313
|
+
when real rows contradict an assumption. Every claim carries the record ids it
|
|
1314
|
+
was checked against; if a fact could not be verified against rows, label it
|
|
1315
|
+
inferred and say from what.
|
|
1316
|
+
|
|
1317
|
+
Then, in the same edit, add the other half:
|
|
1318
|
+
|
|
1319
|
+
- \`## Suggested KB edits\` \u2014 the knowledge-base page to change because of the
|
|
1320
|
+
finding, or "new page for \`<record>\`". One entry per numbered section; a
|
|
1321
|
+
finding with no entry has not been handed to the knowledge base.
|
|
1322
|
+
- \`## Knowledge-base corrections\` \u2014 one table row when a PUBLISHED
|
|
1323
|
+
knowledge-base claim disagrees with the live data: the claim, the live value,
|
|
1324
|
+
and a verdict (stale / refuted / confirmed / rule broken).
|
|
1325
|
+
|
|
1326
|
+
**\`TURBOBASE-FEEDBACK.md\` \u2014 about the PLATFORM.** Where TurboBase itself cost you
|
|
1327
|
+
time \u2014 never your own bugs. Each entry records what you expected, what happened
|
|
1328
|
+
(the error verbatim, because a misleading message IS the finding), the concrete
|
|
1329
|
+
cost, and the fix or workaround. Typical entries:
|
|
1330
|
+
|
|
1331
|
+
${t?`- a scaffold gap, or a default that had to be undone;
|
|
1332
|
+
- a misleading error \u2014 one that named the wrong cause;
|
|
1333
|
+
- a query that compiled and returned the wrong shape;
|
|
1334
|
+
- a limit you only found by hitting it in production.`:`- a fixture shape that did not match the live event payload;
|
|
1335
|
+
- an import the sandbox fenced with no hint of what to use instead;
|
|
1336
|
+
- a hook that passed \`turbobase ext test\` and behaved differently deployed;
|
|
1337
|
+
- a type the generator never emitted, or a deploy error that named nothing.`}
|
|
1338
|
+
|
|
1339
|
+
Then re-rank \`## What would have helped most, in order\`; the ordering is the part
|
|
1340
|
+
the product team acts on first, so it is maintained with the entries.
|
|
1341
|
+
|
|
1342
|
+
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
1343
|
+
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
1344
|
+
`}function P0(t){return`# What this instance's source system actually does
|
|
1345
|
+
|
|
1346
|
+
Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
1347
|
+
Written for the knowledge base, and **everything here is verified against real
|
|
1348
|
+
rows** \u2014 record ids and numbers are included so an editor can re-check rather
|
|
1349
|
+
than take it on trust. Where the knowledge base and the data disagree, the data
|
|
1350
|
+
is what is recorded.
|
|
1351
|
+
|
|
1352
|
+
Companion file: \`TURBOBASE-FEEDBACK.md\` is about the PLATFORM (catalog, sync,
|
|
1353
|
+
CLI, MCP). This file is about the CUSTOMER (how their source system is set up).
|
|
1354
|
+
|
|
1355
|
+
## How this file is maintained
|
|
1356
|
+
|
|
1357
|
+
It is updated **in the same change that establishes the fact** \u2014 not at the end
|
|
1358
|
+
of a task, and never "later". A finding that is not written down while it is
|
|
1359
|
+
still surprising gets normalised into the code and lost.
|
|
1360
|
+
|
|
1361
|
+
Add an entry whenever any of these happens:
|
|
1362
|
+
|
|
1363
|
+
- a field turns out to hold something other than its name suggests, or to be
|
|
1364
|
+
empty where it should be populated;
|
|
1365
|
+
- a link between two records is found \u2014 or found to be absent, which is just as
|
|
1366
|
+
important and much harder to rediscover;
|
|
1367
|
+
- an assumption (yours, the catalog's, the knowledge base's, or a field label's)
|
|
1368
|
+
is contradicted by real rows;
|
|
1369
|
+
- a business rule becomes visible in the data (a naming convention, a subsidiary
|
|
1370
|
+
split, a document that is never used for something).
|
|
1371
|
+
|
|
1372
|
+
Every claim carries the ids it was checked against. If a fact could not be
|
|
1373
|
+
verified against rows, label it as inferred and say from what.
|
|
1374
|
+
|
|
1375
|
+
**A finding is only half an entry.** The numbered sections say what is true;
|
|
1376
|
+
\`## Suggested KB edits\` says what to change in the knowledge base because of it,
|
|
1377
|
+
naming the page. \`## Knowledge-base corrections\` is the sharper case \u2014 a
|
|
1378
|
+
PUBLISHED claim the live data contradicts. Both are written at the same time as
|
|
1379
|
+
the finding, never batched up for later.
|
|
1380
|
+
|
|
1381
|
+
Keep the two headings below exactly as they are: a deploy reads this file and
|
|
1382
|
+
queues each entry for review, and it finds entries by heading.
|
|
1383
|
+
|
|
1384
|
+
---
|
|
1385
|
+
|
|
1386
|
+
<!-- Findings go here, newest last, as numbered sections:
|
|
1387
|
+
|
|
1388
|
+
## 1. <what is actually true, stated as a claim>
|
|
1389
|
+
|
|
1390
|
+
What the data shows, with the ids it was checked against, and the consequence
|
|
1391
|
+
for anything reading it.
|
|
1392
|
+
|
|
1393
|
+
-->
|
|
1394
|
+
|
|
1395
|
+
---
|
|
1396
|
+
|
|
1397
|
+
## Suggested KB edits
|
|
1398
|
+
|
|
1399
|
+
<!-- One entry per numbered section above. Name the page to change \u2014 an existing
|
|
1400
|
+
knowledge-base page, or "new page for <record>" \u2014 and what to say on it. -->
|
|
1401
|
+
|
|
1402
|
+
Each numbered section above should have an entry here. If one does not, the
|
|
1403
|
+
finding has not been handed to the knowledge base yet.
|
|
1404
|
+
|
|
1405
|
+
## Knowledge-base corrections
|
|
1406
|
+
|
|
1407
|
+
<!-- A PUBLISHED knowledge-base claim that the live data contradicts. Quote the
|
|
1408
|
+
claim, give the live value with the ids behind it, and a verdict of
|
|
1409
|
+
stale / refuted / confirmed / rule broken. -->
|
|
1410
|
+
|
|
1411
|
+
| KB claim | Live value | Verdict |
|
|
1412
|
+
|---|---|---|
|
|
1413
|
+
`}function A0(t){return`# Feedback for the TurboBase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
|
|
1414
|
+
|
|
1415
|
+
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
1416
|
+
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
1417
|
+
Facts about this customer's own setup belong in \`INSTANCE-LEARNINGS.md\`.
|
|
1418
|
+
|
|
1419
|
+
## How this file is maintained
|
|
1420
|
+
|
|
1421
|
+
Written **as the problem happens** \u2014 not at the end of a task, and not when
|
|
1422
|
+
asked. An entry written a day later has lost the part that made it useful: what
|
|
1423
|
+
you expected, what you tried, and how long it took to see through.
|
|
1424
|
+
|
|
1425
|
+
Append a numbered section (\`## N. <one-line symptom>\`) whenever the PLATFORM
|
|
1426
|
+
itself, not your own code, causes trouble:
|
|
1427
|
+
|
|
1428
|
+
${t?`- a scaffold gap, a missing tool, or a default that had to be undone;
|
|
1429
|
+
- a misleading error \u2014 one that named the wrong cause and sent you the wrong way;
|
|
1430
|
+
- a query that compiled and returned the wrong shape, or the wrong rows;
|
|
1431
|
+
- a catalog fact that produced a working build and a WRONG SCREEN;
|
|
1432
|
+
- a limit you only found by hitting it in production.`:`- a fixture shape that did not match the live event payload;
|
|
1433
|
+
- an import the sandbox fenced with no hint of what to use instead;
|
|
1434
|
+
- a hook that passed \`turbobase ext test\` and behaved differently deployed;
|
|
1435
|
+
- a misleading CLI error, or a type the generator did not emit.`}
|
|
1436
|
+
|
|
1437
|
+
Each entry records four things:
|
|
1438
|
+
|
|
1439
|
+
- what you expected;
|
|
1440
|
+
- what actually happened \u2014 paste the error verbatim, because a misleading message
|
|
1441
|
+
is itself the finding;
|
|
1442
|
+
- the concrete cost (an investigation, a wrong screen shipped, a wrong answer
|
|
1443
|
+
given to a user);
|
|
1444
|
+
- the fix, or the workaround you had to use.
|
|
1445
|
+
|
|
1446
|
+
Then re-rank \`## What would have helped most, in order\`. The ordering is the part
|
|
1447
|
+
the product team acts on first, so it is maintained with the entries rather than
|
|
1448
|
+
written once.
|
|
1449
|
+
|
|
1450
|
+
Skip anything that is just your own bug. Keep the heading below exactly as it is:
|
|
1451
|
+
a deploy reads this file and reports each finding, and it finds them by heading.
|
|
1452
|
+
|
|
1453
|
+
---
|
|
1454
|
+
|
|
1455
|
+
<!-- Findings go here, newest last:
|
|
1456
|
+
|
|
1457
|
+
## 1. <one-line symptom, stated as what goes wrong>
|
|
1458
|
+
|
|
1459
|
+
Expected / happened / cost / fix.
|
|
1460
|
+
|
|
1461
|
+
-->
|
|
1462
|
+
|
|
1463
|
+
---
|
|
1464
|
+
|
|
1465
|
+
## What would have helped most, in order
|
|
1466
|
+
|
|
1467
|
+
<!-- Rank the findings above by how much time each would have saved. Position is
|
|
1468
|
+
the signal \u2014 1 is the biggest win. -->
|
|
1469
|
+
`}function I0(t,e){let r=e?`
|
|
1470
|
+
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
1471
|
+
# --records focus a previous run stamped into the file, so a refresh never
|
|
1472
|
+
# narrows what an agent deliberately widened.
|
|
1473
|
+
records=$(grep -o 'records=[a-zA-Z0-9_,]*' INSTANCE.md 2>/dev/null | head -1 | cut -d= -f2 || true)
|
|
1474
|
+
turbobase project grounding \${records:+--records "$records"} --query ${JSON.stringify(e.slug)} -o INSTANCE.md >/dev/null 2>&1 \\
|
|
1475
|
+
|| echo "turbobase: grounding refresh skipped (not signed in?)" >&2
|
|
1476
|
+
`:"";return`#!/usr/bin/env bash
|
|
1477
|
+
# SessionStart hook \u2014 refresh ${t} against the current instance schema at
|
|
1478
|
+
# the start of every Claude Code session. Non-fatal: a signed-out / offline
|
|
1479
|
+
# session still starts (types just won't refresh).
|
|
1480
|
+
set -euo pipefail
|
|
1481
|
+
turbobase project types -o ${t} >/dev/null 2>&1 || echo "turbobase: types refresh skipped (not signed in?)" >&2
|
|
1482
|
+
${r}`}var O0=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
|
|
1483
|
+
`,mg="",C0=t=>`node_modules/
|
|
1484
|
+
|
|
1485
|
+
# Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
|
|
1486
|
+
.mcp.json
|
|
1487
|
+
|
|
1488
|
+
.DS_Store
|
|
1489
|
+
`;function gu(t={}){let e=v0.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:C0(r)},{path:"INSTANCE-LEARNINGS.md",content:P0(o)},{path:"TURBOBASE-FEEDBACK.md",content:A0(o)},{path:".claude/settings.json",content:O0},{path:".claude/skills/generate-types/SKILL.md",content:x0(n)},{path:".claude/skills/record-learning/SKILL.md",content:R0(o)},{path:".claude/hooks/session-start-refresh-types.sh",content:I0(n,o),executable:!0}];return r?[{path:"CLAUDE.md",content:S0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:T0},{path:".claude/skills/ship-app/SKILL.md",content:E0}]:[{path:"CLAUDE.md",content:w0},...s,{path:".claude/skills/mock-test/SKILL.md",content:$0},{path:".claude/skills/deploy/SKILL.md",content:k0},{path:"hooks/.gitkeep",content:mg},{path:"samples/.gitkeep",content:mg}]}import{promises as bg}from"node:fs";import{resolve as z0}from"node:path";_i();Lo();var P=t=>{process.stdout.write(`${t}
|
|
1490
|
+
`)},qe=t=>{process.stderr.write(`${t}
|
|
1491
|
+
`)};function T(t){qe(O.red(`turbobase: ${t}`)),process.exit(1)}var Vo=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function yg(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&pu(!1)}async function ze(t){let e=await er(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Rr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";T(`not signed in to ${At(t)}.${n} Run \`turbobase auth login --base-url ${At(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&T("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),pn())try{let n=await fn("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await bi(n);let o=await er();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}T(`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 hn(t,e,r){if(!(t instanceof Ue)||t.status!==403)return;t.body?.error==="approval_required"&&T(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),T(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}var N0=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function j0(t){try{let e=await bg.readFile(t,"utf8");return N0.exec(e)?.[1]??null}catch{return null}}function _g(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 ze(e.baseUrl),o=z0(process.cwd(),e.out),s=e.since?.trim()||await j0(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||T(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${c.status}`);let u=await c.json();if(!u.available){P(`${r} ships no release notes to adopt from (nothing written).`);return}let d=u.releases.reduce((h,p)=>h+p.items.length,0);if(d===0){P(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${u.currentVersion?` (instance is on v${u.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let l=u.currentVersion??u.releases[0]?.version??"",f=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${l}. Re-run to refresh; delete this file once every line is done. -->
|
|
1492
|
+
|
|
1493
|
+
`;await bg.writeFile(o,f+u.markdown,"utf8"),P(`wrote ${o} \u2014 ${d} item(s) across ${u.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}.`)})}Lo();var Ho=["suggested_kb_edit","kb_correction"],M0=[{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}];function L0(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var ZL=new Map(M0.map(t=>[L0(t.heading),t]));function D0(t){return t.diff??!!t.dryRun}var Z0={update_page:"append to the existing page",new_page:"create a NEW page"},Kn=(t,e)=>` ${O.dim(t.padEnd(11))}${e}`,vg=t=>t.ownerEmail??t.ownerId,Ei=t=>O.green(t?` + ${t}`:" +"),U0=t=>O.red(t?` - ${t}`:" -"),mn=t=>O.dim(` ${t}`),q0=` ${O.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,yu=80;function F0(t){let e=[q0];t.target?(e.push(mn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(U0(`visibility: ${t.target.visibility}`)),e.push(Ei("visibility: admin"))):e.push(mn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(mn("title, slug, evidence: untouched")),e.push(mn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(mn("turbobase.document \xB7 new")),e.push(Ei(`title: ${t.pageTitle}`)),e.push(Ei("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(mn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(mn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
1494
|
+
`);for(let n of r.slice(0,yu))e.push(Ei(n?` ${n}`:""));return r.length>yu&&e.push(O.yellow(` \u2026 ${r.length-yu} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function B0(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;r.push(`${String(o+1).padStart(2)}. ${O.bold(n.pageTitle)}`),r.push(Kn("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:O.dim("new \u2014 no existing page matches"))),r.push(Kn("action",Z0[n.action])),r.push(Kn("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?` ${O.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${O.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${O.dim("\xB7")} ${a.title.trim()}${u}${c}`)}),r.push(Kn("confidence",n.withdraws?O.red("WITHDRAWN from readers (text untouched)"):O.dim("untouched"))),n.blockedBy&&r.push(Kn("blocked",O.red(`unpublished work on this page belongs to ${vg(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Kn("ambiguous",O.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),e.diff&&r.push(...F0(n)),r.push("")}),r}function V0(t){let e=c=>t.filter(c).length,r=t.reduce((c,u)=>c+u.entries.length,0),n=e(c=>c.withdraws),o=e(c=>c.blockedBy!=null),s=[`${r} finding${r===1?"":"s"}`,`${t.length} page(s)`,`${e(c=>c.action==="update_page")} appended`,`${e(c=>c.action==="new_page")} created (unpublished)`],i=n>0?O.red(`${n} page(s) WITHDRAWN from readers`):O.dim("no page withdrawn"),a=o>0?` \xB7 ${O.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${s.join(" \xB7 ")} \xB7 ${i}${a}`}function H0(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(`${O.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?vg(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped){n.push(`${O.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?O.green("created "):O.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${O.bold(o.documentId??"?")}`+(o.created?O.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${O.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${O.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${O.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function wg(t){if(t instanceof Ue){let e=t.body;t.status===403&&e?.reason==="admin_required"&&T("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&&T("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}hn(t,"extensions:deploy","learnings push-kb")}async function xg(t,e=r=>new Re(r)){t.section&&!Ho.includes(t.section.trim())&&T(`unknown --section "${t.section}" \u2014 expected one of ${Ho.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&T("--limit must be a positive integer.");let r=await ze(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{}},s;try{s=await Ce("reading the pending queue",()=>n.learningsPending(o))}catch(a){wg(a),T(`could not read the pending queue: ${a instanceof Error?a.message:String(a)}`)}if(s.items.length===0){qe(s.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${s.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(P(B0(s.items,{diff:D0(t)}).join(`
|
|
1495
|
+
`)),P(V0(s.items)),t.dryRun){qe(O.dim("dry run \u2014 nothing was written."));return}let i=s.items.reduce((a,c)=>a+c.entries.length,0);if(!t.yes){if(!pn()){qe(O.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 fn(`Push ${i} finding(s) into the knowledge base as ${s.items.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"){qe("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let a=await Ce("writing pages",()=>n.learningsPushKb(s.planToken,o));P(H0(a.applied,s.items).join(`
|
|
1496
|
+
`))}catch(a){if(a instanceof Ue&&a.status===409){qe(O.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),qe(`re-run \`${Vo} kb push\` to review the current plan.`),process.exitCode=2;return}wg(a),qe(O.red(`turbobase: ${a instanceof Error?a.message:String(a)}`)),process.exitCode=2}}import{promises as $g}from"node:fs";import{join as K0,relative as W0,resolve as G0,sep as J0}from"node:path";var Y0=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),X0=new Set([".mcp.json",".env"]);function Q0(t){return X0.has(t)||t.startsWith(".env.")&&t!==".env.example"}function eT(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function tT(t){return t.includes(0)}async function kg(t){let e=G0(t),r={},n=[],o=[],s=[];async function i(a){let c=await $g.readdir(a,{withFileTypes:!0});for(let u of c){let d=K0(a,u.name);if(u.isDirectory()){if(Y0.has(u.name))continue;await i(d);continue}if(!u.isFile())continue;let l=W0(e,d).split(J0).join("/");if(Q0(u.name)){o.push(l);continue}let f=await $g.readFile(d);if(!eT(f)){n.push(l);continue}tT(f)&&s.push(l),r[l]=f.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as rT}from"node:crypto";var nT="/_tb/app-assets",oT=16,sT=/^[0-9a-f]{32}$/;function Sg(){return rT(oT).toString("hex")}function iT(t){return sT.test(t)}function Tg(t){if(!iT(t))throw new Error(`not a build id: ${t}`);return`${nT}/${t}/`}var Eg=7;var bu=".github/workflows/turbobase-release-deploy.yml",aT=`# \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
|
|
1497
|
+
# TurboBase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
1498
|
+
#
|
|
1499
|
+
# Epic #775 "GitHub is just a link": TurboBase hosts nothing and clones nothing.
|
|
1500
|
+
# This workflow runs in YOUR GitHub repo, on YOUR runner. On every merge to your
|
|
1501
|
+
# default branch it ships your SDF customization project to TurboBase by running
|
|
1502
|
+
# the \`turbobase\` CLI, which UPLOADS the bytes from this checkout. TurboBase
|
|
1503
|
+
# never fetches your code, never holds a GitHub App key, and never mints an
|
|
1504
|
+
# installation token \u2014 the ONLY credential is a personal access token (PAT) that
|
|
1505
|
+
# YOU mint and store as a GitHub Actions secret (one-time setup below).
|
|
1506
|
+
#
|
|
1507
|
+
# \u2500\u2500 One-time setup \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
|
|
1508
|
+
# 1. Mint a \`releases:write\` PAT (you, in your TurboBase app):
|
|
1509
|
+
# Settings \u2192 Access tokens \u2192 "New token"
|
|
1510
|
+
# Scope: releases:write (the only scope this workflow needs)
|
|
1511
|
+
# Copy the token \u2014 it starts with \`tb_pat_\u2026\` and is shown only once.
|
|
1512
|
+
#
|
|
1513
|
+
# 2. Store the PAT as a GitHub Actions SECRET in this repo (you, in GitHub):
|
|
1514
|
+
# Repo \u2192 Settings \u2192 Secrets and variables \u2192 Actions \u2192 "New repository secret"
|
|
1515
|
+
# Name: TURBOBASE_RELEASE_PAT
|
|
1516
|
+
# Value: <the tb_pat_\u2026 token from step 1>
|
|
1517
|
+
# The PAT lives ONLY in your GitHub secret store. TurboBase never sees your
|
|
1518
|
+
# GitHub credentials, and you never paste a TurboBase secret into this file.
|
|
1519
|
+
#
|
|
1520
|
+
# 3. Store your instance base URL as a repo VARIABLE (not a secret \u2014 it isn't
|
|
1521
|
+
# sensitive) so the workflow knows which instance to deploy to:
|
|
1522
|
+
# Repo \u2192 Settings \u2192 Secrets and variables \u2192 Actions \u2192 Variables \u2192 "New"
|
|
1523
|
+
# Name: TURBOBASE_BASE_URL
|
|
1524
|
+
# Value: https://<your-slug>.turbobase.app
|
|
1525
|
+
#
|
|
1526
|
+
# 4. Put this file at \`.github/workflows/turbobase-release-deploy.yml\` (or run
|
|
1527
|
+
# \`turbobase project ci\`, which writes it there for you), commit, and merge.
|
|
1528
|
+
# The next merge to your default branch deploys.
|
|
1529
|
+
#
|
|
1530
|
+
# \u2500\u2500 What it deliberately does NOT do \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
|
|
1531
|
+
# \u2022 No GitHub App, no installation token, no server-side clone \u2014 TurboBase
|
|
1532
|
+
# receives ONLY the bytes this checkout uploads.
|
|
1533
|
+
# \u2022 Defaults to \`--target auto\`. An approval-gated deploy is a guarded,
|
|
1534
|
+
# human-approved action (\`--target approved --approved-by you@co.com\`) and is
|
|
1535
|
+
# intentionally NOT wired to fire automatically on merge.
|
|
1536
|
+
# \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
|
|
1537
|
+
name: TurboBase release deploy
|
|
1538
|
+
|
|
1539
|
+
on:
|
|
1540
|
+
push:
|
|
1541
|
+
# Change \`main\` to your repo's default branch if it differs (e.g. master).
|
|
1542
|
+
branches: [main]
|
|
1543
|
+
|
|
1544
|
+
# Least privilege: this workflow only READS your checkout to upload it. It never
|
|
1545
|
+
# writes to your repo, and it does NOT use GITHUB_TOKEN to reach TurboBase \u2014 the
|
|
1546
|
+
# PAT secret is the only credential that leaves the runner.
|
|
1547
|
+
permissions:
|
|
1548
|
+
contents: read
|
|
1549
|
+
|
|
1550
|
+
# One deploy at a time per branch; a newer merge supersedes any in-flight run.
|
|
1551
|
+
concurrency:
|
|
1552
|
+
group: turbobase-release-\${{ github.ref }}
|
|
1553
|
+
cancel-in-progress: false
|
|
1554
|
+
|
|
1555
|
+
jobs:
|
|
1556
|
+
deploy:
|
|
1557
|
+
runs-on: ubuntu-latest
|
|
1558
|
+
steps:
|
|
1559
|
+
# The checkout IS the upload source. \`turbobase release deploy\` reads the
|
|
1560
|
+
# SDF project's src/ from this working tree and uploads those bytes;
|
|
1561
|
+
# nothing is fetched server-side.
|
|
1562
|
+
- name: Check out the merged commit
|
|
1563
|
+
uses: actions/checkout@v4
|
|
1564
|
+
|
|
1565
|
+
- name: Set up Node
|
|
1566
|
+
uses: actions/setup-node@v4
|
|
1567
|
+
with:
|
|
1568
|
+
node-version: '20'
|
|
1569
|
+
|
|
1570
|
+
# Install the \`turbobase\` CLI. The package is scoped; the command it
|
|
1571
|
+
# installs is plain \`turbobase\`. Pin a version (\`@turbobase/cli@1.2.3\`)
|
|
1572
|
+
# if you would rather CI not track the current release.
|
|
1573
|
+
- name: Install the turbobase CLI
|
|
1574
|
+
run: npm install -g @turbobase/cli
|
|
1575
|
+
|
|
1576
|
+
# Authenticate headlessly: store the PAT for this instance. The token is read
|
|
1577
|
+
# from the GitHub secret via env (never interpolated into the command line,
|
|
1578
|
+
# so it can't leak into the run logs).
|
|
1579
|
+
- name: Authenticate to TurboBase
|
|
1580
|
+
env:
|
|
1581
|
+
TURBOBASE_RELEASE_PAT: \${{ secrets.TURBOBASE_RELEASE_PAT }}
|
|
1582
|
+
run: |
|
|
1583
|
+
turbobase auth login \\
|
|
1584
|
+
--base-url "\${{ vars.TURBOBASE_BASE_URL }}" \\
|
|
1585
|
+
--token "$TURBOBASE_RELEASE_PAT"
|
|
1586
|
+
|
|
1587
|
+
# Ship it. \`--ref \${{ github.sha }}\` records the exact commit these bytes
|
|
1588
|
+
# were built from (a provenance LINK only \u2014 TurboBase never fetches it).
|
|
1589
|
+
# \`--project .\` uploads this checkout's SDF src/; \`--follow\` waits for the
|
|
1590
|
+
# server-side deploy job and fails the run if the deploy fails.
|
|
1591
|
+
- name: Deploy the release
|
|
1592
|
+
run: |
|
|
1593
|
+
turbobase release deploy \\
|
|
1594
|
+
--target auto \\
|
|
1595
|
+
--ref "\${{ github.sha }}" \\
|
|
1596
|
+
--project . \\
|
|
1597
|
+
--follow
|
|
1598
|
+
`;function Rg(){return[{path:bu,content:aT}]}import Ri from"node:fs/promises";import Ko from"node:path";var _u={esbuild:"0.28.1","isolated-vm":"6.1.2"},wu="@turbobase/isolated-vm-prebuilds";function vu(t,e){return`${t}-${e}`}function xu(t=process.versions){return`abi${t.modules}`}var Pg=["darwin-x64","win32-arm64"];async function Ag(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=vu(e,r),o=Ko.join(t.home,"node_modules"),s=Ko.join(o,...wu.split("/"),"prebuilds",n),i=Ko.join(o,"isolated-vm","prebuilds",n),a;try{a=await Ri.readdir(s)}catch{return[]}let c=[];await Ri.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let d=Ko.join(i,u);try{await Ri.copyFile(Ko.join(s,u),d,Ri.constants?.COPYFILE_EXCL??1),c.push(u)}catch{}}return c}import{homedir as cT}from"node:os";import{join as Ig}from"node:path";import{promises as $u}from"node:fs";function Cg(){let t=process.env.TURBOBASE_HOME??Ig(cT(),".turbobase");return{dir:t,file:Ig(t,"sandboxes.json")}}var uT={s:1e3,m:6e4,h:36e5,d:864e5};function lT(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*uT[e[2]]}function dT(t,e=Date.now()){return new Date(e+lT(t)).toISOString()}function pT(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function fT(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 hT(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 mT="[REDACTED]",ku=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 gT(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new ku(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:mT:n[o]=s}return n}function yT(t,e,r){return e.map(n=>gT(t,n,r))}var Og=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),bT=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function _T(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 wT(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 bT)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=_T(t);if(!Og.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Og].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function vT(t,e=xT){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function xT(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function $T(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function kT(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Su(){let{file:t}=Cg();try{let e=await $u.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function zg(t){let{dir:e,file:r}=Cg();await $u.mkdir(e,{recursive:!0}),await $u.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
1599
|
+
`,{mode:384})}async function ST(t){let e=await Su();e.push(t),await zg(e)}async function Ng(t){let e=await Su(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await zg(e),n??null}async function Pi(){return Su()}function Tu(t,e=Date.now()){let r=[],n=[];for(let o of t)pT(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function jg(t,e){wT(t.target());let r=fT(e.sample),n=e.now??Date.now(),o=(e.nameGen??(c=>vT(c)))(e.fromTenant),s=$T(o);await t.createDatabase(s),await t.replayMigrations(s);let i=await t.readSourceTables(e.fromTenant);for(let c of i){let u=hT(c.rows,r),d=yT(c.table,u,c.classification);d.length>0&&await t.copyRows(s,c.table,d)}let a={name:o,fromTenant:e.fromTenant,database:s,createdAt:new Date(n).toISOString(),expiresAt:dT(e.ttl,n),sampleFraction:r,url:kT(o,e.baseUrl)};return await ST(a),a}async function Mg(t,e){let n=(await Pi()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Ng(e),n):null}async function Eu(t,e=Date.now()){let r=await Pi(),{expired:n}=Tu(r,e);for(let o of n){try{await t.dropDatabase(o.database)}catch{}await Ng(o.name)}return n}var Wo={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","data:read"],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"}},iD=Object.keys(Wo).filter(t=>Wo[t].mintable);var uD=Wo.pat.prefix,TT=Object.entries(Wo).map(([t,e])=>[e.prefix,t]),ET=/^[A-Za-z0-9_-]{20,}$/;function RT(t){if(typeof t!="string")return null;for(let[e,r]of TT)if(t.startsWith(e)&&ET.test(t.slice(e.length)))return r;return null}function Lg(t){return RT(t)==="pat"}var Go="bundle.json",Ai="turbobase";function Zg(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 PT(a)}function PT(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(Dg)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Dg)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Dg(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Ug(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}")`}}async function Y1(t,e){try{let r=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)return null;let n=await r.json();return typeof n.token=="string"&&n.token.length>0?n.token:null}catch{return null}}async function X1(t){let e=await Rr();e.length===0&&T("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),pn()||T("this command needs an explicit <base-url> in a non-interactive shell.");try{return await fn(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{T("cancelled.")}}async function Q1(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}`}}async function ej(t,e,r){let n=await Zm({baseUrl:t,token:e}),o=(await Rr()).length-1;if(P(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),!r)return;let s=await Q1(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(qe(`warning: ${n.baseUrl} did not respond to the TurboBase API (/v1) \u2014 got ${s.detail}.`),qe(" In local dev the TurboBase API is on :4100, not the app dev-server port (e.g. :5173)."),qe(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?qe(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):qe(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function tj(t){let e=await Uo(t),r=c=>{let u=new RegExp(`${c}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return u?u[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(e),o=r("id");if(n){let c=r("on"),u=r("recordType"),d=r("source");return(!o||!u||!c||!d)&&T(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:o,recordType:u,event:c,source:d,sourceCode:e,extensionKind:"conduit"}}let s=r("recordType"),i=r("event"),a=r("source")??"standalone";return(!o||!s||!i)&&T(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:o,recordType:s,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function So(t,e,r,n){try{return await we.access(t),"skipped"}catch{}return await we.mkdir(Qs(t),{recursive:!0}),await we.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await we.chmod(t,n),"wrote"}async function N$(t,e){if(M$(t)!==".gitignore")return So(t,e.content,e.executable,e.mode);let r=await we.readFile(t,"utf8").catch(()=>null);if(r===null)return So(t,e.content,e.executable,e.mode);let n=gg(r);return n===null?"skipped":(await we.writeFile(t,n,"utf8"),"merged")}function Bh(t){if(t!==void 0){if(t==="junit"||t==="json")return t;T(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function rj(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 nj(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 oj(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 Kh({includeInternal:t=!0}={}){let e=new um;e.name("turbobase").description("Author, test, and deploy TurboBase extensions against your instance.").version("1.1.7").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",g=>g.command.parent?"":`${fu()}
|
|
1600
|
+
`),e.hook("preAction",(g,y)=>{yg(e.opts(),y.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.");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 g=>{let y=At(g.baseUrl);g.token||T(`auth login needs --token. Mint a PAT in your TurboBase app (Settings \u203A Access tokens), then:
|
|
1601
|
+
${Vo} auth login --base-url ${y} --token tb_pat_\u2026`),Lg(g.token)||T("--token does not look like a TurboBase PAT (tb_pat_\u2026)."),await ej(y,g.token,g.verify)}),r.command("status").description("Show the active instance (the no-`--base-url` default) and every stored sign-in.").action(async()=>{let g=await Rr();if(g.length===0){P("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`.");return}let y=await er(),_=w=>!!y&&w.baseUrl===y.baseUrl;if(xt())P(Ti(g.map(w=>[_(w)?O.green("*"):" ",O.bold(w.baseUrl),O.dim(w.updatedAt)]),{head:["","instance","updated"]}));else for(let w of g)P(`${_(w)?"* ":" "}${w.baseUrl} (updated ${w.updatedAt})`);y||qe("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async g=>{let y=g??await X1("Pick the active instance:"),_=await bi(y);if(!_){let w=await Rr();T(`no stored sign-in for ${At(y)}.`+(w.length?` Stored: ${w.map(x=>x.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${At(y)} --token tb_pat_\u2026\`.`)}P(`active instance \u2192 ${_.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 g=>{if(g.all){let w=await Rr();for(let x of w)await ru(x.baseUrl);P(`removed ${w.length} stored sign-in${w.length===1?"":"s"}.`);return}let y=await ru(g.baseUrl);y||T(g.baseUrl?`no stored sign-in for ${At(g.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let _=await er();P(`signed out of ${y}.`+(_?` Active instance \u2192 ${_.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 g=>{let{baseUrl:y,token:_}=await ze(g.baseUrl),w;try{w=await Er({baseUrl:y,token:_,recordsOnly:g.recordsOnly})}catch($){let A=$ instanceof Error?$.message:String($);if(!g.recordsOnly&&/openapi\.json failed \(401/.test(A)){let I=await Y1(y,_);if(I)try{w=await Er({baseUrl:y,token:I,recordsOnly:!1});let M=$e(process.cwd(),g.out);await we.writeFile(M,w,"utf8"),P(`wrote ${M} (${w.split(`
|
|
1602
|
+
`).length} lines).`);return}catch{}qe("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{w=await Er({baseUrl:y,token:_,recordsOnly:!0})}catch(M){T(`types generation failed: ${M instanceof Error?M.message:String(M)}`)}}else T(`types generation failed: ${A}`)}let x=$e(process.cwd(),g.out);await we.writeFile(x,w,"utf8"),P(`wrote ${x} (${w.split(`
|
|
1603
|
+
`).length} lines).`)}),_g(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 g=>{let{baseUrl:y,token:_}=await ze(g.baseUrl),w=new URLSearchParams;g.records&&w.set("records",g.records),g.query&&w.set("query",g.query);let x=w.toString(),$=await fetch(`${y}/v1/catalog/grounding${x?`?${x}`:""}`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});$.ok||T(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${$.status}`);let I=((await $.json()).markdown??"").trim(),M=$e(process.cwd(),g.out),L=g.records?` records=${g.records}`:"",D=`<!-- GENERATED by \`turbobase project grounding\` against ${y}${L} \u2014 do not edit; re-run to refresh. -->
|
|
1604
|
+
|
|
1605
|
+
`;await we.writeFile(M,D+(I?`${I}
|
|
1606
|
+
`:`(no grounding available yet)
|
|
1607
|
+
`),"utf8"),P(`wrote ${M}${I?"":" (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 (${Ho.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",g=>Number.parseInt(g,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("--yes","Skip the confirmation (for scripted runs).").action(g=>xg(g));let i=o.command("new").description("Scaffold a new extension file.");i.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 g=>{let y;try{y=Hn("hook",{recordType:g.record,event:g.event,template:g.template,field:g.field,regex:g.regex,source:g.source,id:g.id})}catch(x){T(x instanceof Error?x.message:String(x))}let _=$e(process.cwd(),y.relativePath);await So(_,y.content)==="skipped"&&T(`refusing to overwrite existing file: ${_}`),P(`wrote ${_}`)}),i.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 g=>{let y;try{y=Hn("conduit",{recordType:g.record,source:g.source,to:g.to,toRecordType:g.toRecord,event:g.event,id:g.id})}catch(x){T(x instanceof Error?x.message:String(x))}let _=$e(process.cwd(),y.relativePath);await So(_,y.content)==="skipped"&&T(`refusing to overwrite existing file: ${_}`),P(`wrote ${_}`)}),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(g,y)=>{let _=Bh(y.reporter),w=await Uo($e(process.cwd(),g)),x=$e(process.cwd(),y.samples),$=await Zo(x);$.length===0&&!_&&P(`no samples found under ${x} \u2014 add JSON fixtures to dry-run against.`);let A;try{A=await xi(w,$.map(L=>L.fixture))}catch(L){T(`bundle failed: ${L instanceof Error?L.message:String(L)}`)}if(_){let L=rj(A);P(ki(L,_)),L.cases.some(D=>D.status==="failed")&&process.exit(1);return}let I=0;for(let L of A){let D=L.pass?O.green("PASS"):O.red("FAIL");L.pass||(I+=1);let le=L.error?` (error: ${L.error})`:L.observed!==L.expected?` (expected ${L.expected}, observed ${L.observed})`:L.rejection?` (rejected: ${L.rejection.code??"rejected"})`:"";P(` ${D} ${L.name}${le}`)}let M=`${A.length-I}/${A.length} sample(s) passed.`;P(`
|
|
1608
|
+
${I===0?O.green(M):O.yellow(M)}`),I>0&&process.exit(1)}),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 bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(g,y)=>{if(y.to){let A=await Vh(),{baseUrl:I,token:M}=await ze(y.baseUrl),L=new Re({baseUrl:I,token:M});try{let D=await Ce(`applying bundle to ${y.to}`,()=>L.configApply(A));P(`applied bundle to ${y.to}: +${D.applied.add} ~${D.applied.change} -${D.applied.destroy}`+(D.backfillsQueued.length?` (${D.backfillsQueued.length} backfill(s) queued)`:""))}catch(D){D instanceof Ue&&D.status===403&&T("apply forbidden (403) \u2014 the stored PAT is not for an admin."),T(`bundle apply failed: ${D instanceof Error?D.message:String(D)}`)}return}g||T("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:_,token:w}=await ze(y.baseUrl),x=await tj($e(process.cwd(),g)),$=new Re({baseUrl:_,token:w});try{let A=await Ce(`deploying ${M$(g)}`,()=>$.deploy(x));xt()?P(Ar("Deployed",[`${O.bold(A.id)} ${Fo(A.status)} ${O.dim(A.outcome)}`])):P(`deployed ${A.id} \u2192 status=${A.status} (${A.outcome}).`)}catch(A){A instanceof Ue&&A.status===403&&T("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),T(`deploy failed: ${A instanceof Error?A.message:String(A)}`)}});let a=e.command("apps").description("Manage hosted apps served in your TurboBase app.");a.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.").action(async(g,y,_)=>{let w=$e(process.cwd(),y??".");await we.mkdir(w,{recursive:!0});let x=_.proposal??await p(w),{baseUrl:$,token:A}=await ze(_.baseUrl),I=new Re({baseUrl:$,token:A}),M=!1;try{M=(await I.appsList()).some(ae=>ae.slug===g||ae.id===g)}catch(ae){hn(ae,"extensions:deploy","deploy"),T(`could not reach ${$}: ${ae instanceof Error?ae.message:String(ae)}`)}if(!M){_.create||T(`no app "${g}" on ${$} \u2014 create it with \`turbobase apps create ${g}\`, or pass --create.`);let ae=await Ce(`creating app ${g}`,()=>u($,A,{slug:g},{tolerateExisting:!0}));ae.existed||P(`created ${ae.slug??g}.`)}let L=ae=>we.stat(zn(w,ae)).then(()=>!0).catch(()=>!1),D=g,le=w,te=_.build!==!1;if(te&&!await L("package.json"))if(await L("index.html"))P("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),te=!1;else if(_.pull===!1)T(`${w} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ae=await Ce(`pulling ${g}`,()=>d($,A,g));D=ae.slug??g,await l(w,ae.files,!0),P(`pulled generated source (rev ${ae.rev}).`)}let De;if(te){let ae=Sg();if(De={buildId:ae,assetBase:Tg(ae)},_.install!==!1&&!await L("node_modules")){P("installing dependencies\u2026");try{await b(["install"],w)}catch(Et){T(`npm install failed: ${Et instanceof Error?Et.message:String(Et)}`)}}P("building\u2026");try{await b(["run","build"],w,{TURBOBASE_ASSET_BASE:De.assetBase})}catch(Et){T(`build failed: ${Et instanceof Error?Et.message:String(Et)}`)}await L("dist")||T(`no dist/ after build in ${w} \u2014 check the app's build script.`),le=zn(w,"dist")}_.preview&&!De&&T(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${D}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let pe=await B($,A,D,le,_.entry,x,De,_.preview?{label:_.label}:void 0);if(_.preview){let ae=pe.previewUrl??"(no url returned)",Et=pe.expiresAt?new Date(pe.expiresAt).toLocaleDateString():`${Eg} days`;xt()?P(Ar("Preview deployed",[`${O.bold(D)} ${O.green(`v${pe.version??"?"}`)} ${O.dim("not live")}`,`${O.bold(ae)}`,O.dim(`expires ${Et}`)])):P(`preview ${D} v${pe.version??"?"} \u2192 ${ae} (expires ${Et}; /a/${D} unchanged).`),P(`next: turbobase apps promote ${D} ${pe.previewId??"<preview-id>"} # make it live`),P(` turbobase apps preview discard ${pe.previewId??"<preview-id>"}`);return}xt()?P(Ar("Deployed",[`${O.bold(D)} ${O.green(`v${pe.version??"?"}`)} ${O.dim(pe.url??`/a/${D}`)}`])):P(`deployed ${D} \u2192 v${pe.version??"?"} (${pe.url??`/a/${D}`}).`),G(pe)}),a.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(g,y,_)=>{let{baseUrl:w,token:x}=await ze(_.baseUrl),$=await Ce(`promoting ${y}`,()=>R(w,x,g,"promote",{previewId:y}));xt()?P(Ar("Promoted",[`${O.bold(g)} ${O.green(`v${$.version??"?"}`)} ${O.dim($.url??`/a/${g}`)}`])):P(`promoted ${g} \u2192 v${$.version??"?"} is now live at ${$.url??`/a/${g}`}.`),G($)});let c=a.command("preview").description("Inspect and manage an app's open previews.");c.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).").action(async(g,y)=>{let{baseUrl:_,token:w}=await ze(y.baseUrl),x=await C(_,w,g);if(x.previews.length===0){P(`no open previews for ${g}.`);return}for(let $ of x.previews){let A=$.label?` ${$.label}`:"",I=$.expiresAt?new Date($.expiresAt).toLocaleDateString():"?";P(`v${$.version} ${$.previewId}${A} ${$.url} (expires ${I})`)}}),c.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(g,y,_)=>{let{baseUrl:w,token:x}=await ze(_.baseUrl);await Ce(`discarding ${y}`,()=>R(w,x,g,"discard",{previewId:y})),P(`discarded ${y}.`)}),a.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(g,y)=>{let{baseUrl:_,token:w}=await ze(y.baseUrl),x=await Ce(`creating ${g}`,()=>u(_,w,{slug:g,name:y.name,description:y.description})),$=x.slug??g;xt()?P(Ar("Created",[`${O.bold($)} ${O.dim(x.url??`/a/${$}`)}`])):P(`created ${$} (${x.url??`/a/${$}`}).`),P(`next: turbobase apps push ${$} . # store the source`),P(` turbobase apps deploy ${$} # build + go live`)});async function u(g,y,_,w={}){let x=`${g.replace(/\/+$/,"")}/v1/apps`,$;try{$=await fetch(x,{method:"POST",headers:{Authorization:`Bearer ${y}`,"content-type":"application/json"},body:JSON.stringify({slug:_.slug,name:_.name??_.slug,description:_.description})})}catch(A){T(`create request failed: ${A instanceof Error?A.message:String(A)}`)}if($.status===401&&T("create unauthorized (401) \u2014 re-run `turbobase auth login`."),$.status===403&&T("create forbidden (403) \u2014 the PAT is not for an admin."),$.status===409){if(w.tolerateExisting)return{slug:_.slug,existed:!0};T(`an app with slug "${_.slug}" already exists.`)}return $.ok||T(`create failed: HTTP ${$.status} ${(await $.text().catch(()=>"")).slice(0,200)}`),await $.json().catch(()=>({}))}async function d(g,y,_){let w=`${g.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/pull`,x;try{x=await fetch(w,{headers:{Authorization:`Bearer ${y}`}})}catch($){T(`pull request failed: ${$ instanceof Error?$.message:String($)}`)}return x.status===401&&T("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),x.status===403&&T("pull forbidden (403) \u2014 the PAT is not for an admin."),x.status===404&&T(`no generated source for "${_}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),x.ok||T(`pull failed: HTTP ${x.status} ${(await x.text().catch(()=>"")).slice(0,200)}`),await x.json()}async function l(g,y,_){let w=$e(g),x=0;for(let[$,A]of Object.entries(y)){let I=$e(w,$);I!==w&&!I.startsWith(w+z$)&&T(`refusing to write outside ${w}: ${$}`),_||await we.stat(I).then(()=>!0).catch(()=>!1)&&T(`${I} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await we.mkdir(Qs(I),{recursive:!0}),await we.writeFile(I,A,"utf8"),x+=1}return x}function f(g){let y=g.indexOf(","),_=g.startsWith("data:")?y>=0?g.slice(y+1):"":g;if(!_)return null;try{let w=Buffer.from(_,"base64");return w.length>0?new Uint8Array(w):null}catch{return null}}async function h(g,y,_){let w=$e(g),x=async(A,I)=>{let M=$e(w,A);M!==w&&!M.startsWith(w+z$)&&T(`refusing to write outside ${w}: ${A}`),_||await we.stat(M).then(()=>!0).catch(()=>!1)&&T(`${M} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await we.mkdir(Qs(M),{recursive:!0}),await we.writeFile(M,I)},$=`# ${y.title||"App change request"}
|
|
1609
|
+
|
|
1610
|
+
> Widget proposal \`${y.proposalId}\` \u2014 build this change, then ship it with
|
|
1611
|
+
> \`turbobase apps deploy ${y.appSlug}\`. The deploy stamps this proposal complete.
|
|
1612
|
+
|
|
1613
|
+
${y.bodyMarkdown||"_No description provided._"}
|
|
1614
|
+
|
|
1615
|
+
## Screen context
|
|
1616
|
+
|
|
1617
|
+
`+(y.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.
|
|
1618
|
+
`);if(await x("PROPOSAL.md",$),y.screenshot){let A=f(y.screenshot);A&&await x("proposal-screenshot.png",A)}await x(zn(".turbobase","proposal.json"),`${JSON.stringify({proposalId:y.proposalId},null,2)}
|
|
1619
|
+
`)}async function p(g){try{let y=await we.readFile(zn(g,".turbobase","proposal.json"),"utf8"),_=JSON.parse(y);return typeof _.proposalId=="string"&&_.proposalId?_.proposalId:void 0}catch{return}}async function m(g,y,_,w,x,$){let A=new Re({baseUrl:g,token:y});try{return await A.appsPush(_,w,{note:x,proposalId:$})}catch(I){if(I instanceof Ue){let M=I.body;if(I.status===401&&T("push unauthorized (401) \u2014 re-run `turbobase auth login`."),I.status===403&&M?.error==="admin_required"&&T("push forbidden (403) \u2014 the PAT is not for an admin."),I.status===403&&hn(I,"extensions:deploy","push app source"),I.status===404&&T(`no app "${_}" on this instance \u2014 create it with \`turbobase apps create ${_}\`.`),I.status===413&&(M?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&T("push rejected: the request body exceeded the instance limit."),T(`push rejected: ${M?.error??"too large"} (limit ${M?.limit??"?"}).`)),I.status===400){let L=M?.path?` in ${M.path}`:"",D=M?.reason?` (${M.reason})`:"";T(`push rejected: ${M?.error??"bad request"}${D}${L}.`)}}T(`push failed: ${I instanceof Error?I.message:String(I)}`)}}function b(g,y,_){return new Promise((w,x)=>{let $=j$("npm",g,{cwd:y,stdio:"inherit",..._?{env:{...process.env,..._}}:{}});$.on("error",x),$.on("exit",A=>A===0?w():x(new Error(`npm ${g.join(" ")} exited ${A??"?"}`)))})}async function S(g,y,_,w){let x=`${g.replace(/\/+$/,"")}${_}`,$;try{$=await fetch(x,{method:w.method,headers:{Authorization:`Bearer ${y}`,...w.body?{"content-type":"application/json"}:{}},...w.body?{body:JSON.stringify(w.body)}:{}})}catch(A){T(`request failed: ${A instanceof Error?A.message:String(A)}`)}if($.status===401&&T("unauthorized (401) \u2014 re-run `turbobase auth login`."),$.status===403&&T("forbidden (403) \u2014 the PAT is not for an admin."),!$.ok){let A=await $.text().catch(()=>""),I=A.slice(0,300);try{let M=JSON.parse(A);I=M.message??M.error??I}catch{}T(`failed: HTTP ${$.status} ${I}`)}return await $.json().catch(()=>({}))}async function R(g,y,_,w,x){return await S(g,y,`/v1/apps/${encodeURIComponent(_)}/preview/${w}`,{method:"POST",body:x})}async function C(g,y,_){return{previews:(await S(g,y,`/v1/apps/${encodeURIComponent(_)}/previews`,{method:"GET"})).previews??[]}}async function B(g,y,_,w,x,$,A,I){let M;try{M=await Ce(`zipping ${w}`,()=>ng(w))}catch(te){T(`could not zip ${w}: ${te instanceof Error?te.message:String(te)}`)}M.fileCount===0&&T(`${w} is empty \u2014 the build produced nothing.`);let L={Authorization:`Bearer ${y}`,"Content-Type":"application/zip"};x&&(L["x-app-entry"]=x),$&&(L["x-proposal-id"]=$),A&&(L["x-app-build-id"]=A.buildId,L["x-app-asset-base"]=A.assetBase),I&&(L["x-app-channel"]="preview",I.label&&(L["x-app-preview-label"]=encodeURIComponent(I.label)));let D=`${g.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(_)}/deploy`,le;try{le=await Ce(`deploying ${_} (${M.fileCount} file${M.fileCount===1?"":"s"})`,()=>fetch(D,{method:"POST",headers:L,body:new Uint8Array(M.buffer)}))}catch(te){T(`deploy request failed: ${te instanceof Error?te.message:String(te)}`)}if(le.status===401&&T("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),le.status===403&&T("deploy forbidden (403) \u2014 the PAT is not for an admin."),le.status===404&&T(`no app "${_}" on ${g} \u2014 create it with \`turbobase apps create ${_}\`.`),!le.ok){let te=await le.text().catch(()=>""),De=te.slice(0,300);try{let pe=JSON.parse(te);De=pe.message??pe.error??De}catch{}T(`deploy failed: HTTP ${le.status} ${De}`)}return await le.json().catch(()=>({}))}function G(g){let y=hg(g);y&&P(y.level==="warn"?O.yellow(y.message):O.dim(y.message))}a.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(g,y,_)=>{let{baseUrl:w,token:x}=await ze(_.baseUrl);if(_.proposal){let M=new Re({baseUrl:w,token:x}),L;try{L=await Ce(`fetching proposal ${_.proposal}`,()=>M.appPullContext(_.proposal))}catch(pe){hn(pe,"extensions:deploy","pull proposal"),pe instanceof Ue&&pe.status===404&&T(`no widget proposal "${_.proposal}" on ${w}.`),T(`could not fetch proposal ${_.proposal}: ${pe instanceof Error?pe.message:String(pe)}`)}let D=await Ce(`pulling ${L.appSlug}`,()=>d(w,x,L.appSlug)),le=y??g,te=$e(process.cwd(),le??L.appSlug);await we.mkdir(te,{recursive:!0});let De=await l(te,D.files,!!_.force);await h(te,L,!!_.force),P(`pulled ${De} file${De===1?"":"s"} \u2192 ${te} (rev ${D.rev}), linked to proposal ${L.proposalId}.`),P(`next: cd ${Fh(process.cwd(),te)||"."} && turbobase apps deploy ${L.appSlug}`);return}g||T("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let $=await Ce(`pulling ${g}`,()=>d(w,x,g)),A=$e(process.cwd(),y??$.slug??g);await we.mkdir(A,{recursive:!0});let I=await l(A,$.files,!!_.force);P(`pulled ${I} file${I===1?"":"s"} \u2192 ${A} (rev ${$.rev}).`),P(`next: cd ${Fh(process.cwd(),A)||"."} && turbobase apps deploy ${$.slug}`)}),a.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(g,y,_)=>{let w=$e(process.cwd(),y??g),x=await er(_.baseUrl).catch(()=>null),{scaffoldAppFiles:$,starterApp:A}=await Promise.resolve().then(()=>(ry(),ty)),I=_.title??g,M=$({slug:g,title:I,appTsx:A(I),instanceOrigin:x?.baseUrl});await we.mkdir(w,{recursive:!0});let L=await l(w,M,!!_.force);if(P(`scaffolded ${L} file${L===1?"":"s"} \u2192 ${w}`),_.claude!==!1){let le=gu({baseUrl:x?.baseUrl,token:x?.token,appSlug:g}),te=0;for(let De of le){let pe=await N$(zn(w,De.path),De);(pe==="wrote"||pe==="merged")&&(te+=1)}P(`wired Claude Code: ${te} file${te===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),x||qe("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 D=Fh(process.cwd(),w)||".";P(`next: cd ${D} && npm install && npm run dev`),P(` turbobase apps create ${g}`),P(` turbobase apps push ${g} .`),P(` turbobase apps deploy ${g} .`)}),a.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 g=>{let{baseUrl:y,token:_}=await ze(g.baseUrl),w=new Re({baseUrl:y,token:_}),x;try{x=await w.appsList()}catch($){hn($,"extensions:deploy","list apps"),T(`list apps failed: ${$ instanceof Error?$.message:String($)}`)}if(g.json)return P(JSON.stringify(x,null,2));if(x.length===0)return P("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");P(Ti(x.map($=>[$.slug,$.name,$.deployed?"yes":"no",$.sourceRev===null?"\u2014":`rev ${$.sourceRev}`,$.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),a.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(g,y,_)=>{let w=$e(process.cwd(),y??".");await we.stat(w).then(pe=>pe.isDirectory()).catch(()=>!1)||T(`${w} is not a directory.`);let{baseUrl:$,token:A}=await ze(_.baseUrl),I=_.proposal??await p(w),{files:M,skipped:L,secrets:D,unstorable:le}=await kg(w),te=Object.keys(M).length;if(te===0&&T(`no source files found under ${w} (build output and node_modules are skipped).`),le.length>0){for(let pe of le)qe(`${pe} contains a NUL byte (U+0000), which cannot be stored.`);T(`push aborted: ${le.length} ${le.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let pe of L)qe(O.dim(`skipped binary file ${pe}`));for(let pe of D)qe(O.dim(`skipped ${pe} (holds credentials \u2014 never pushed)`));let De=await Ce(`pushing ${te} file${te===1?"":"s"}`,()=>m($,A,g,M,_.note,I));P(`pushed ${De.files} file${De.files===1?"":"s"} \u2192 ${De.slug} rev ${De.rev} (source only, nothing deployed).`),P(`next: turbobase apps deploy ${De.slug}`)}),o.command("plan").description("Diff the local bundle (turbobase/bundle.json) 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 g=>{let y=await Vh(),{baseUrl:_,token:w}=await ze(g.baseUrl),x=new Re({baseUrl:_,token:w}),$;try{$=await Ce(`planning against ${g.to??_}`,()=>x.configPlan(y))}catch(A){T(`plan failed: ${A instanceof Error?A.message:String(A)}`)}ij($,g.to??_)}),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).").action(async g=>{let y=await Vh(),{baseUrl:_,token:w}=await ze(g.baseUrl),x=y.tenant??aj(_),$=Ug(g.confirm,x);$.ok||T(`promote refused (fail-closed): ${$.reason}`);let A=new Re({baseUrl:_,token:w});try{let I=await Ce(`promoting ${g.from} \u2192 ${g.to} (${x})`,()=>A.configApply(y));if(xt()){let M=[`${O.bold(`${g.from} \u2192 ${g.to}`)} ${O.dim(x??"")}`,`${Pr.add(String(I.applied.add))} ${Pr.change(String(I.applied.change))} ${Pr.destroy(String(I.applied.destroy))}`];I.backfillsQueued.length&&M.push(O.dim(`${I.backfillsQueued.length} backfill(s) queued`)),P(Ar("Promoted",M))}else P(`promoted ${g.from} \u2192 ${g.to} (${x}): +${I.applied.add} ~${I.applied.change} -${I.applied.destroy}`+(I.backfillsQueued.length?` (${I.backfillsQueued.length} backfill(s) queued)`:""))}catch(I){I instanceof Ue&&I.status===403&&T("promote forbidden (403) \u2014 the stored PAT is not for an admin."),T(`promote failed: ${I instanceof Error?I.message:String(I)}`)}});let Ve=async(g,y)=>{let{baseUrl:_,token:w}=await ze(y.baseUrl),x=new Re({baseUrl:_,token:w}),$=y.limit?Number(y.limit):void 0;if(y.follow){try{await dg(x,g,{follow:!0,limit:$,intervalMs:y.intervalMs?Number(y.intervalMs):void 0,sink:P})}catch(A){T(`logs --follow failed: ${A instanceof Error?A.message:String(A)}`)}return}try{let A=await x.logs(g,$);A.length===0&&P(`no logs for ${g}.`);for(let I of A)P(` [${I.level}] ${I.ts??""} ${I.message}`)}catch(A){T(`logs failed: ${A instanceof Error?A.message:String(A)}`)}};o.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(Ve),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(g,y)=>{let _=Bh(y.reporter),w=$e(process.cwd(),g),x=await Uo(w),$=sg(x);_?P(ki(nj(g,$),_)):P(ig(g,$,{warn:O.yellow,ok:O.green,dim:O.dim})),y.ci&&$.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(g,y)=>{let _=Bh(y.reporter),w=await Ym($e(process.cwd(),g));if(y.against){y.against!=="sandbox"&&T(`unknown --against target '${y.against}' (only 'sandbox' is supported).`);try{await Gm(uu(w))}catch(A){T(A instanceof Error?A.message:String(A))}return}y.fixture||T("replay needs a --fixture <file> (offline) or --against sandbox (online).");let x;try{x=await Jm($e(process.cwd(),y.fixture))}catch(A){T(`could not read fixture ${y.fixture}: ${A instanceof Error?A.message:String(A)}`)}let $=await Wm(w,x,y.fixture);if(_){let A=oj($);P(ki(A,_)),A.cases.some(I=>I.status==="failed")&&process.exit(1);return}P(Xm($,!!y.trace)),$.error&&process.exit(1)}),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 g=>{let{baseUrl:y,token:_}=await ze(g.baseUrl),w=new Re({baseUrl:y,token:_});try{await pg(w,{status:g.status,retry:g.retry,limit:g.limit?Number(g.limit):void 0,sink:P})}catch(x){x instanceof Ue&&x.status===403&&T("forbidden (403) \u2014 binding --retry requires an admin PAT."),x instanceof Ue&&x.status===409&&T("binding is not retryable (only divergent/blocked bindings can be retried)."),T(`ext binding failed: ${x instanceof Error?x.message:String(x)}`)}}),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(g,y)=>{let _=g.lastIndexOf("@"),w=_>0?g.slice(0,_):g,x=_>0?g.slice(_+1):void 0,$=nu();$||T(`marketplace not configured \u2014 set ${Bn} and ${wi}.
|
|
1620
|
+
Ask TurboBase support to issue a registry token for your instance (it is separate from your PAT).`);let A=ou($.registryUrl);A&&T(A);let{baseUrl:I,token:M}=await ze(y.baseUrl),L=new Mo($),D;try{D=await Ce(`fetching ${g}`,()=>L.fetchBundle(w,x))}catch(ae){T(`marketplace fetch failed for ${g}: ${ae instanceof Error?ae.message:String(ae)}`)}let le=fi(D.manifest),te=null;if(le.length>0){if(!y.connection){let ae=le.map(Et=>Et.source_system).join(", ");T(`${D.name}@${D.version} declares a connection input (source: ${ae}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}te=y.connection}let De=sj(D.bundle,D.name,D.kind),pe=new Re({baseUrl:I,token:M});try{let ae=await Ce(`installing ${D.name}@${D.version}`,()=>pe.deploy({...De,provenance:"marketplace",...te?{connectionId:te}:{}}));P(`installed ${D.name}@${D.version} \u2192 ${ae.id} (status=${ae.status}, ${ae.outcome})`+(te?` bound to connection ${te}.`:"."))}catch(ae){ae instanceof Ue&&ae.status===403&&T("install forbidden (403) \u2014 the stored PAT is not for an admin."),T(`install failed: ${ae instanceof Error?ae.message:String(ae)}`)}}),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(g,y)=>{let _=nu();_||T(`marketplace not configured \u2014 set ${Bn} and ${wi}.
|
|
1621
|
+
Ask TurboBase support to issue a registry token for your instance (it is separate from your PAT).`);let w=ou(_.registryUrl);w&&T(w);let x=$e(process.cwd(),g),$=await Uo(x),A=/\bdefineConduit\s*[<(]/.test($)?"conduit":"hook",I={};if(y.manifest){let D=$e(process.cwd(),y.manifest),le;try{le=await we.readFile(D,"utf8")}catch{T(`manifest not found at ${y.manifest}.`)}let te;try{te=JSON.parse(le)}catch{T(`manifest is not valid JSON: ${y.manifest}.`)}(typeof te!="object"||te===null||Array.isArray(te))&&T("manifest must be a JSON object."),I=te}try{Fc(I,$)}catch(D){D instanceof Tr&&T(D.message),T(`manifest validation failed: ${D instanceof Error?D.message:String(D)}`)}let M=new Mo(_);try{await Ce(`publishing ${y.name}@${y.pkgVersion}`,()=>M.publish({name:y.name,version:y.pkgVersion,kind:A,bundle:$,manifest:I}))}catch(D){D instanceof Ue&&D.status===403&&T("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),D instanceof Ue&&D.status===409&&T(`version already published \u2014 ${y.name}@${y.pkgVersion} exists. Bump the version.`),T(`publish failed: ${D instanceof Error?D.message:String(D)}`)}let L=fi(I);P(`published ${y.name}@${y.pkgVersion} (kind=${A}) to the marketplace.`),L.length>0&&P(` declares ${L.length} connection input(s): ${L.map(D=>D.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 g=>{let y=await er(g.baseUrl).catch(()=>null),_=gu({baseUrl:y?.baseUrl,token:y?.token}),w=0,x=0,$=0;for(let A of _){let I=$e(process.cwd(),A.path),M=await N$(I,A);M==="wrote"?(w+=1,P(` wrote ${A.path}`)):M==="merged"?($+=1,P(` merged ${A.path} (added the .mcp.json rule)`)):(x+=1,P(` skipped ${A.path} (exists)`))}P(`
|
|
1622
|
+
project init: ${w} written, ${$} merged, ${x} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${bu} (non-destructive).`).action(async()=>{let g=Rg(),y=0,_=0;for(let w of g){let x=$e(process.cwd(),w.path);await So(x,w.content,w.executable)==="wrote"?(y+=1,P(` wrote ${w.path}`)):(_+=1,P(` skipped ${w.path} (exists)`))}P(`
|
|
1623
|
+
project ci: ${y} written, ${_} skipped.`),y>0&&(P(`
|
|
1624
|
+
Next: mint a releases:write PAT in your TurboBase app (Settings \u203A Access tokens),`),P("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),P("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 g=>{let{baseUrl:y,token:_}=await ze(g.baseUrl),w=new Re({baseUrl:y,token:_}),x;try{x=await w.catalogRecords()}catch(L){L instanceof Ue&&(L.status===401||L.status===403)&&T("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),T(`catalog fetch failed: ${L instanceof Error?L.message:String(L)}`)}if(x.length===0){P("no records in the instance catalog \u2014 nothing to generate.");return}let $=$e(process.cwd(),g.out),A=eg(x,{event:g.event}),I=0,M=0;for(let{recordType:L,fixture:D}of A){let le=zn($,`${L}.json`),te=`${JSON.stringify(D,null,2)}
|
|
1625
|
+
`;g.force?(await we.mkdir(Qs(le),{recursive:!0}),await we.writeFile(le,te,{mode:420}),I+=1,P(` wrote ${g.out}/${L}.json`)):await So(le,te)==="wrote"?(I+=1,P(` wrote ${g.out}/${L}.json`)):(M+=1,P(` skipped ${g.out}/${L}.json (exists \u2014 use --force to overwrite)`))}P(`
|
|
1626
|
+
samples init: ${I} written, ${M} skipped.`)});let He=e.command("sandbox").description("Ephemeral local authoring sandboxes.");He.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 g=>{process.env.TURBOBASE_SANDBOX="1";let y=Hh(),_;try{_=await jg(y,{fromTenant:g.from,ttl:g.ttl,sample:g.sample,baseUrl:g.baseUrl})}catch(x){T(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}let w=await cj(_.name);P(`sandbox ${_.name} ready.`),P(` source: ${_.fromTenant} (sampled ${Math.round(_.sampleFraction*100)}%, redacted)`),P(` url: ${_.url}`),P(` expires: ${_.expiresAt}`),P(` mounted: ${w.hooks} hook(s), ${w.conduits} conduit(s)`)}),He.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async g=>{let y=Hh();await Eu(y).catch(()=>[]);let _;try{_=await Mg(y,g)}catch(w){T(`sandbox destroy failed: ${w instanceof Error?w.message:String(w)}`)}_||T(`no sandbox named '${g}'.`),P(`destroyed sandbox ${_.name} (dropped ${_.database}).`)}),He.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let g=Hh(),y=await Eu(g).catch(()=>[]),_=await Pi(),{active:w}=Tu(_);if(w.length===0)P("no active sandboxes.");else{for(let x of w)P(` ${x.name} from=${x.fromTenant} expires=${x.expiresAt} ${x.url}`);P(`
|
|
1627
|
+
${w.length} active sandbox(es).`)}y.length>0&&P(`(reaped ${y.length} expired sandbox(es).)`)}),o.command("export").description("Snapshot the live instance into turbobase/bundle.json.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Ai).action(async g=>{let{baseUrl:y,token:_}=await ze(g.baseUrl),w=new Re({baseUrl:y,token:_}),x;try{x=await Ce("exporting instance config",()=>w.configExport())}catch(I){I instanceof Ue&&(I.status===401||I.status===403)&&T("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),T(`ext export failed: ${I instanceof Error?I.message:String(I)}`)}let $=typeof x.serialized=="string"?x.serialized:`${JSON.stringify(x.manifest??x,null,2)}
|
|
1628
|
+
`,A=$e(process.cwd(),g.out,Go);await we.mkdir(Qs(A),{recursive:!0}),await we.writeFile(A,$,"utf8"),P(`wrote ${g.out}/${Go} (${$.split(`
|
|
1629
|
+
`).length} lines).`)});let ur=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),To=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],vr=()=>process.env.TURBOBASE_HOME?.trim()||zn(J1(),".turbobase"),Eo=()=>"1.1.7",Wr=async()=>Promise.all(To.map(async g=>{try{return await import(g.name),{...g,present:!0}}catch{return{...g,present:!1}}}));return ur.command("status").description("Report which optional native packages are installed.").action(async()=>{let g=await Wr();for(let y of g)P(`${y.present?$t.success("installed"):$t.warn("missing")} ${O.bold(y.name)} \u2014 ${y.needs}`);g.some(y=>!y.present)&&P(`
|
|
1630
|
+
run \`${Vo} ext extras install\` to fetch them into ${vr()}.`)}),ur.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let g=await Wr();if(g.every(M=>M.present)){P($t.success("extras already installed \u2014 nothing to do."));return}let y=vr();await we.mkdir(y,{recursive:!0});let _=g.filter(M=>!M.present).map(M=>M.name),w=vu(process.platform,process.arch),x=async(M,L)=>{let{code:D,stderr:le}=await ei("npm",["install","--prefix",y,"--no-audit","--no-fund",...M]);D!==0&&T(`extras install failed while installing ${L} (npm exited ${D}).
|
|
1631
|
+
${le.trim()}
|
|
1632
|
+
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},$=_.filter(M=>M!=="isolated-vm");if($.length>0){let M=$.map(L=>`${L}@${_u[L]??"latest"}`);P(`installing ${M.join(", ")} \u2192 ${y}/node_modules \u2026`),await x(M,$.join(", "))}if(_.includes("isolated-vm")){let M=`isolated-vm@${_u["isolated-vm"]}`;if(P(`installing ${M} \u2192 ${y}/node_modules \u2026`),await x(["--ignore-scripts",M],"isolated-vm"),Pg.includes(w)){let D=`${wu}@${Eo()}`;P(`fetching ${D} (no upstream binary for ${w}) \u2026`);let{code:le}=await ei("npm",["install","--prefix",y,"--no-audit","--no-fund","--ignore-scripts",D]);le!==0&&P($t.warn(`could not fetch ${D} \u2014 falling back to a source build.`))}let L=await Ag({home:y});L.length>0&&P(` ${$t.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${w}`)}let A=await Wr(),I=A.filter(M=>!M.present).map(M=>M.name);if(I.includes("isolated-vm")){P($t.warn(`no prebuilt isolated-vm for ${w} / Node ${process.versions.node} (${xu()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:M}=await ei("npm",["rebuild","--prefix",y,"isolated-vm"]);M===0&&(A=await Wr(),I=A.filter(L=>!L.present).map(L=>L.name))}I.length>0&&T(`npm succeeded but ${I.join(", ")} still will not load \u2014 no prebuilt binary for ${w} / Node ${process.versions.node} (${xu()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),P($t.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))}),e.command("mcp").description("Run the local stdio authoring MCP server (for Claude Code via .mcp.json).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async g=>{let{runAuthoringMcpServer:y}=await Promise.resolve().then(()=>(C$(),O$));await y({baseUrl:g.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app"," 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)."].join(`
|
|
1633
|
+
`)),t&&void 0,e}function sj(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 Vh(){let t=$e(process.cwd(),Ai,Go),e;try{e=await we.readFile(t,"utf8")}catch{T(`no bundle found at ${Ai}/${Go} \u2014 run \`turbobase ext export\` first.`)}try{return Zg(e)}catch(r){T(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}function ij(t,e){P(`plan against ${e}:`);for(let r of t.add)P(` ${Pr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)P(` ${Pr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)P(` ${Pr.destroy(`${r.kind} ${r.id}`)}`);P(`
|
|
1634
|
+
${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 aj(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function ei(t,e,r){return new Promise(n=>{let o=j$(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 Hh(){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 ei("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 ei("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},readSourceTables:async r=>{throw new Error("sandbox data copy requires a live local Supabase (no local Postgres in this environment).")},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 cj(t){let e=async r=>{try{return(await we.readdir($e(process.cwd(),r))).filter(o=>/\.(ts|js|mjs)$/.test(o)).length}catch{return 0}};return{hooks:await e("hooks"),conduits:await e("conduits")}}var uj=!1;uj&&Kh().parseAsync(process.argv).catch(t=>T(t instanceof Error?t.message:String(t)));Kh().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
|
|
1635
|
+
`),process.exit(1)});
|