@tessl/cli 0.21.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -3
  2. package/dist/bundle.mjs +364 -364
  3. package/package.json +1 -1
package/dist/bundle.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import*as fs$3 from"node:fs";import fs__default,{watch,existsSync,writeFileSync as writeFileSync$1,statSync,readFileSync as readFileSync$1,appendFileSync,createWriteStream as createWriteStream$1,createReadStream,mkdirSync as mkdirSync$1}from"node:fs";import*as path$5 from"path";import path__default,{join as join$1,dirname,basename,normalize as normalize$3,resolve as resolve$3,relative,sep as sep$2,posix as posix$1}from"path";import*as Url$1 from"url";import Url__default,{fileURLToPath,URL as URL$1}from"url";import fs$4,{readFileSync,existsSync as existsSync$1,mkdirSync,writeFileSync,realpathSync as realpathSync$1,readlinkSync,readdirSync,readdir as readdir$1,lstatSync,createWriteStream,promises}from"fs";import*as require$$0$a from"os";import require$$0__default,{arch,hostname as hostname$1,release,platform as platform$1}from"os";import crypto$4,{randomUUID,createHash,randomFillSync}from"crypto";import os$2,{homedir as homedir$1,EOL,constants as constants$d}from"node:os"
3
3
  ;import*as path$6 from"node:path";import path__default$1,{join,dirname as dirname$1,win32,posix,basename as basename$1,resolve as resolve$2,relative as relative$1,sep as sep$1}from"node:path";import require$$0$d from"@grpc/grpc-js";import{performance as performance$1}from"perf_hooks";import require$$2$6,{TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,ATTR_TELEMETRY_SDK_VERSION,ATTR_TELEMETRY_SDK_LANGUAGE,ATTR_TELEMETRY_SDK_NAME,ATTR_SERVICE_NAME,ATTR_EXCEPTION_TYPE,ATTR_EXCEPTION_MESSAGE,ATTR_EXCEPTION_STACKTRACE}from"@opentelemetry/semantic-conventions";import*as require$$0$b from"util";import require$$0__default$1,{inspect,types as types$4}from"util";import*as http$2 from"http";import http__default from"http";import*as https$2 from"https";import https__default from"https";import*as zlib$2 from"zlib";import zlib__default,{createGunzip as createGunzip$1}from"zlib";import Stream$2,{Readable}from"stream"
4
4
  ;import require$$1$7,{JsonTraceSerializer,JsonLogsSerializer,ProtobufLogsSerializer,JsonMetricsSerializer,ProtobufMetricsSerializer,ProtobufTraceSerializer}from"@opentelemetry/otlp-transformer";import require$$1$8 from"module";import require$$0$e from"tty";import require$$3$2 from"worker_threads";import require$$0$f,{EventEmitter,once as once$1,addAbortListener,on,setMaxListeners}from"node:events";import require$$0$g,{EventEmitter as EventEmitter$1}from"events";import require$$1$a,{AggregationTemporality,InstrumentType,AggregationType}from"@opentelemetry/sdk-metrics";import require$$1$9 from"async_hooks";import*as process$4 from"process";import process__default from"process";import{ATTR_K8S_POD_UID,ATTR_K8S_NAMESPACE_NAME,ATTR_K8S_POD_NAME,ATTR_VCS_REF_BASE_NAME,ATTR_VCS_CHANGE_ID,ATTR_USER_ID,ATTR_USER_EMAIL}from"@opentelemetry/semantic-conventions/incubating";import*as require$$0$c from"child_process";import require$$0__default$2,{execSync}from"child_process"
5
- ;import{createInterface}from"readline";import fsp,{realpath,readlink,readdir,lstat,access,readFile as readFile$1,mkdir,writeFile,chmod,rmdir}from"node:fs/promises";import{dirname as dirname$2}from"path/posix";import require$$1$e,{fileURLToPath as fileURLToPath$1,URL as URL$2}from"node:url";import require$$0$h,{PassThrough,Stream as Stream$3,Readable as Readable$1,Transform as Transform$2,getDefaultHighWaterMark,Duplex,Writable}from"node:stream";import{StringDecoder}from"node:string_decoder";import process$5,{env as env$2,cwd,platform as platform$2,hrtime,execPath,execArgv}from"node:process";import tty$2 from"node:tty";import require$$5$5,{performance as performance$2}from"node:perf_hooks";import require$$0$i from"assert";import require$$0$l,{Buffer as Buffer$1}from"node:buffer";import{pipeline,finished}from"node:stream/promises";import require$$1$d,{createGunzip,createGzip}from"node:zlib";import require$$0$j from"buffer"
5
+ ;import readline$4,{createInterface}from"readline";import fsp,{realpath,readlink,readdir,lstat,access,readFile as readFile$1,mkdir,writeFile,chmod}from"node:fs/promises";import{dirname as dirname$2}from"path/posix";import require$$1$e,{fileURLToPath as fileURLToPath$1,URL as URL$2}from"node:url";import require$$0$h,{PassThrough,Stream as Stream$3,Readable as Readable$1,Transform as Transform$2,getDefaultHighWaterMark,Duplex,Writable}from"node:stream";import{StringDecoder}from"node:string_decoder";import process$5,{env as env$2,cwd,platform as platform$2,hrtime,execPath,execArgv}from"node:process";import tty$2 from"node:tty";import require$$5$5,{performance as performance$2}from"node:perf_hooks";import require$$0$i from"assert";import require$$0$l,{Buffer as Buffer$1}from"node:buffer";import{pipeline,finished}from"node:stream/promises";import require$$1$d,{createGunzip,createGzip}from"node:zlib";import require$$0$j from"buffer"
6
6
  ;import require$$1$i,{createHash as createHash$1,randomUUID as randomUUID$1}from"node:crypto";import{setTimeout as setTimeout$1}from"node:timers";import cp,{ChildProcess,execFile,spawnSync,spawn,execSync as execSync$1}from"node:child_process";import require$$1$b from"string_decoder";import require$$0$k,{createServer}from"net";import{readFile as readFile$2,unlink,mkdir as mkdir$1}from"fs/promises";import{setTimeout as setTimeout$2}from"timers/promises";import require$$0$m from"node:assert";import require$$0$n from"node:net";import require$$2$7 from"node:http";import require$$6$2 from"node:querystring";import require$$0$p from"node:diagnostics_channel";import require$$0$o,{stripVTControlCharacters,isDeepStrictEqual,debuglog,inspect as inspect$1,promisify,callbackify,aborted as aborted$1,styleText}from"node:util";import require$$4$3 from"node:tls";import require$$8$1 from"node:util/types";import require$$1$c from"node:worker_threads"
7
7
  ;import require$$1$f,{AsyncLocalStorage,AsyncResource}from"node:async_hooks";import require$$1$g from"node:console";import require$$1$h from"node:dns";import{query}from"@anthropic-ai/claude-code";import{tsImport}from"tsx/esm/api";import{pipeline as pipeline$1}from"stream/promises";import open from"open";import*as readline$3 from"node:readline";import{createInterface as createInterface$1}from"node:readline";import{setTimeout as setTimeout$3,scheduler as scheduler$1,setImmediate as setImmediate$1}from"node:timers/promises";import{serialize}from"node:v8";import{pino}from"pino";import"pino-pretty";import require$$4$2 from"tls";var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){
8
8
  if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){var r=!1;try{r=this instanceof e}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var main$2={exports:{}},version$6="17.2.1",require$$4$1={version:version$6},hasRequiredMain;function requireMain(){if(hasRequiredMain)return main$2.exports;hasRequiredMain=1
@@ -88,7 +88,7 @@ return globalThis.Object.getOwnPropertyNames(e).reduce((t,r)=>({...t,[r]:Compute
88
88
  function Void(e){return CreateType({[Kind]:"Void",type:"void"},e)}var TypeBuilder=Object.freeze({__proto__:null,Any:Any$1,Argument,Array:Array$1,AsyncIterator,Awaited,BigInt:BigInt$1,Boolean:Boolean$1,Capitalize,Composite,Const,Constructor,ConstructorParameters,Date:Date$1,Enum,Exclude,Extends,Extract,Function:Function$1,Index,InstanceType,Instantiate,Integer,Intersect:Intersect$1,Iterator,KeyOf,Literal,Lowercase,Mapped,Module,Never,Not,Null,Number:Number$1,Object:Object$1,Omit,Optional,Parameters,Partial,Pick,Promise:Promise$1,Readonly,ReadonlyOptional,Record,Recursive,Ref,RegExp:RegExp$1,Required,Rest,ReturnType,String:String$1,Symbol:Symbol$1,TemplateLiteral,Transform:Transform$1,Tuple,Uint8Array:Uint8Array$1,Uncapitalize,Undefined,Union:Union$1,Unknown,Unsafe,Uppercase,Void});const Type=TypeBuilder;function _nullishCoalesce$12(e,t){return null!=e?e:t()}const ProjectConfigSchema=Type.Object({name:Type.Optional(Type.String({description:"Project name"})),
89
89
  ciCommand:Type.Optional(Type.Array(Type.String()))}),CONFIG_DIR_NAME=".tessl",AGENTS_MD_FILENAME="AGENTS.md",SYSTEM_PROMPT_FILENAME="tessl-system-prompt.md",TESSL_CONFIG_FILE_NAME="tessl-config.jsonc",TMP_DIR_NAME="tmp",DEFAULT_TESSL_DIRS={customToolDirectory:join(CONFIG_DIR_NAME,"tools"),frameworkDirectory:join(CONFIG_DIR_NAME,"framework"),tmpDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME),testRunnerDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME,"test-runners"),testResultsDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME,"test-results"),sessionDataDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME,"session-data"),toolOutputLogsDirectory:join(CONFIG_DIR_NAME,TMP_DIR_NAME,"tool-output-logs")};function getDefaultGlobalConfigDir(e,t){const r=_nullishCoalesce$12(t,()=>os$2.homedir()),n=_nullishCoalesce$12(_nullishCoalesce$12(e,()=>"production"),()=>"development");return path__default.join(r,"production"===n?".tessl":`.tessl_${n}`)}function getProvisionedEnvPath(e,t){
90
90
  return join$1(getDefaultGlobalConfigDir(e,t),"dotenv")}function getLocalCliEnvPath(){const e=fileURLToPath(import.meta.url),t=dirname(e),r=join$1(t,"..","..","..","..");return join$1(r,".cli.env")}function loadEnvAndWatch(){loadEnv(),setupFileWatchers()}function loadEnvFile(e){fs__default.existsSync(e)&&mainExports.config({path:e,override:!0,quiet:!0})}function loadEnv(){loadEnvFile(getProvisionedEnvPath("production")),process.env.TESSL_LLM_API_KEY?process.env.ANTHROPIC_AUTH_TOKEN=process.env.TESSL_LLM_API_KEY:delete process.env.ANTHROPIC_AUTH_TOKEN,process.env.TESSL_LLM_BASE_URL?process.env.ANTHROPIC_BASE_URL=process.env.TESSL_LLM_BASE_URL:delete process.env.ANTHROPIC_BASE_URL;const e=getClaudeCodeSdkModels();process.env.ANTHROPIC_MODEL=e.DEFAULT,process.env.ANTHROPIC_SMALL_FAST_MODEL=e.SMALL_FAST}let localCliWatcher=null,provisionedEnvWatcher=null,cleanupRegistered=!1;function createFileWatcher(e,t){const r=dirname(e),n=basename(e);if(!fs__default.existsSync(r))return null
91
- ;const i=watch(r,(e,r)=>{r!==n||"change"!==e&&"rename"!==e||t()});return i.on("error",()=>{}),i.unref(),i}function cleanup(){localCliWatcher&&(localCliWatcher.close(),localCliWatcher=null),provisionedEnvWatcher&&(provisionedEnvWatcher.close(),provisionedEnvWatcher=null)}function setupFileWatchers(){cleanup(),localCliWatcher=createFileWatcher(getLocalCliEnvPath(),loadEnv),provisionedEnvWatcher=createFileWatcher(getProvisionedEnvPath("production"),loadEnv),cleanupRegistered||(process.on("SIGINT",cleanup),process.on("SIGTERM",cleanup),cleanupRegistered=!0)}function getTesslCmdName(){return"tessl"}process.env={...process.env,ROLLUP_BUNDLING_CLI:!0,NODE_ENV:"production",GLOBAL_CONFIG_DIR:".tessl",STAMPED_REVISION:"1b07fe35e6be40363eddd9e8ea9b60666a216013",STAMPED_RELEASE_DATE:"2025-09-15T19:45:56.832Z",STAMPED_VERSION:"v0.21.0",TESSL_BASE_API_URL:"https://api.tessl.io",WORKOS_CLIENT_ID:"client_01HXSHDD9KV92A4892CWHZZDDR",POSTHOG_API_KEY:"phc_S8tHJaPxa5ORnP0RVyyTaJHeCcft6XMqfjx9ZlJWvkO",
91
+ ;const i=watch(r,(e,r)=>{r!==n||"change"!==e&&"rename"!==e||t()});return i.on("error",()=>{}),i.unref(),i}function cleanup(){localCliWatcher&&(localCliWatcher.close(),localCliWatcher=null),provisionedEnvWatcher&&(provisionedEnvWatcher.close(),provisionedEnvWatcher=null)}function setupFileWatchers(){cleanup(),localCliWatcher=createFileWatcher(getLocalCliEnvPath(),loadEnv),provisionedEnvWatcher=createFileWatcher(getProvisionedEnvPath("production"),loadEnv),cleanupRegistered||(process.on("SIGINT",cleanup),process.on("SIGTERM",cleanup),cleanupRegistered=!0)}function getTesslCmdName(){return"tessl"}process.env={...process.env,ROLLUP_BUNDLING_CLI:!0,NODE_ENV:"production",GLOBAL_CONFIG_DIR:".tessl",STAMPED_REVISION:"c239ff5e4c64c85bb970e5403eb2556f98ad0f8d",STAMPED_RELEASE_DATE:"2025-09-16T11:14:27.886Z",STAMPED_VERSION:"v0.21.1",TESSL_BASE_API_URL:"https://api.tessl.io",WORKOS_CLIENT_ID:"client_01HXSHDD9KV92A4892CWHZZDDR",POSTHOG_API_KEY:"phc_S8tHJaPxa5ORnP0RVyyTaJHeCcft6XMqfjx9ZlJWvkO",
92
92
  POSTHOG_FEEDBACK_SURVEY_ID:"0197d0d3-6704-0000-e36e-569911acb8ee",POSTHOG_FEEDBACK_SURVEY_QUESTION_ID:"e34e48fc-938a-4af1-b255-3c55d6bdcbc7"},loadEnvAndWatch();var _globalThis$2="object"==typeof globalThis?globalThis:global,VERSION$a="1.9.0",re$1=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _makeCompatibilityCheck(e){var t=new Set([e]),r=new Set,n=e.match(re$1);if(!n)return function(){return!1};var i=+n[1],s=+n[2],o=+n[3];if(null!=n[4])return function(t){return t===e};function a(e){return r.add(e),!1}function c(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;var n=e.match(re$1);if(!n)return a(e);var u=+n[1],l=+n[2],d=+n[3];return null!=n[4]||i!==u?a(e):0===i?s===l&&o<=d?c(e):a(e):s<=l?c(e):a(e)}}var isCompatible=_makeCompatibilityCheck(VERSION$a),major=VERSION$a.split(".")[0],GLOBAL_OPENTELEMETRY_API_KEY=Symbol.for("opentelemetry.js.api."+major),_global$1=_globalThis$2;function registerGlobal(e,t,r,n){var i;void 0===n&&(n=!1)
93
93
  ;var s=_global$1[GLOBAL_OPENTELEMETRY_API_KEY]=null!==(i=_global$1[GLOBAL_OPENTELEMETRY_API_KEY])&&void 0!==i?i:{version:VERSION$a};if(!n&&s[e]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(o.stack||o.message),!1}if(s.version!==VERSION$a){o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+VERSION$a);return r.error(o.stack||o.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+VERSION$a+"."),!0}function getGlobal(e){var t,r,n=null===(t=_global$1[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===t?void 0:t.version;if(n&&isCompatible(n))return null===(r=_global$1[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===r?void 0:r[e]}function unregisterGlobal(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+VERSION$a+".");var r=_global$1[GLOBAL_OPENTELEMETRY_API_KEY];r&&delete r[e]}var __read$4=function(e,t){
94
94
  var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,s=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(i)throw i.error}}return o},__spreadArray$3=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))},DiagComponentLogger=function(){function e(e){this._namespace=e.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return logProxy("debug",this._namespace,e)},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return logProxy("error",this._namespace,e)},e.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return logProxy("info",this._namespace,e)},e.prototype.warn=function(){
@@ -320,9 +320,9 @@ const r=process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim()||process.env.OTE
320
320
  })):"prometheus"===r?t.push(new d.PrometheusExporter):e.diag.warn(`Unsupported OTEL_METRICS_EXPORTER value: "${r}". Supported values are: otlp, console, prometheus, none.`)}),t)):t}();if(this._meterProviderConfig||o.length>0){const t=[];this._meterProviderConfig?.reader&&t.push(this._meterProviderConfig.reader),0===t.length&&o.forEach(e=>t.push(e));const r=new p.MeterProvider({resource:this._resource,views:this._meterProviderConfig?.views??[],readers:t});this._meterProvider=r,e.metrics.setGlobalMeterProvider(r);for(const t of this._instrumentations)t.setMeterProvider(e.metrics.getMeterProvider())}}shutdown(){const e=[];return this._tracerProvider&&e.push(this._tracerProvider.shutdown()),this._loggerProvider&&e.push(this._loggerProvider.shutdown()),this._meterProvider&&e.push(this._meterProvider.shutdown()),Promise.all(e).then(()=>{})}configureLoggerProviderFromEnv(){const t=(0,g.getStringListFromEnv)("OTEL_LOGS_EXPORTER")??[]
321
321
  ;if(0===t.length&&(e.diag.debug("OTEL_LOGS_EXPORTER is empty. Using default otlp exporter."),t.push("otlp")),t.includes("none"))return void e.diag.info('OTEL_LOGS_EXPORTER contains "none". Logger provider will not be initialized.');const r=[];t.forEach(t=>{if("otlp"===t){const t=((0,g.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL")??(0,g.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL"))?.trim();switch(t){case"grpc":r.push(new o.OTLPLogExporter);break;case"http/json":r.push(new s.OTLPLogExporter);break;case"http/protobuf":case void 0:case"":r.push(new a.OTLPLogExporter);break;default:e.diag.warn(`Unsupported OTLP logs protocol: "${t}". Using http/protobuf.`),r.push(new a.OTLPLogExporter)}}else"console"===t?r.push(new i.ConsoleLogRecordExporter):e.diag.warn(`Unsupported OTEL_LOGS_EXPORTER value: "${t}". Supported values are: otlp, console, none.`)}),r.length>0&&(this._loggerProviderConfig={
322
322
  logRecordProcessors:r.map(e=>e instanceof i.ConsoleLogRecordExporter?new i.SimpleLogRecordProcessor(e):new i.BatchLogRecordProcessor(e))})}},sdk$1}function requireSrc$3(){return hasRequiredSrc$3||(hasRequiredSrc$3=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.NodeSDK=e.tracing=e.resources=e.node=e.metrics=e.logs=e.core=e.contextBase=e.api=void 0,e.api=require$$0$9,e.contextBase=require$$0$9,e.core=require$$1$6,e.logs=require$$2$2,e.metrics=require$$1$a,e.node=requireSrc$7(),e.resources=require$$5$3,e.tracing=require$$6$1;var t=requireSdk();Object.defineProperty(e,"NodeSDK",{enumerable:!0,get:function(){return t.NodeSDK}})}(src$8)),src$8}var srcExports$4=requireSrc$3(),srcExports$3=requireSrc$7();function register$1(){if(process.env.TELEMETRY_USER){const e="https://7530.tessl.io:443";process.env.OTEL_EXPORTER_OTLP_ENDPOINT=e,process.env.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",
323
- process.env.OTEL_EXPORTER_OTLP_HEADERS=`Authorization=Basic ${Buffer.from(`${process.env.TELEMETRY_USER}:${process.env.TELEMETRY_PASSWORD}`).toString("base64")}`}const e=new srcExports$4.NodeSDK({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:"stepper",[ATTR_K8S_POD_NAME]:process.env.INJECTED_POD_NAME,[ATTR_K8S_NAMESPACE_NAME]:process.env.INJECTED_POD_NAMESPACE,[ATTR_K8S_POD_UID]:process.env.INJECTED_POD_UID,[ATTR_VCS_CHANGE_ID]:"1b07fe35e6be40363eddd9e8ea9b60666a216013",[ATTR_VCS_REF_BASE_NAME]:"1b07fe35e6be40363eddd9e8ea9b60666a216013"}),instrumentations:[new srcExports$5.GrpcInstrumentation({ignoreGrpcMethods:["Check"]})],spanProcessors:[new srcExports$3.SimpleSpanProcessor(process.env.TELEMETRY_USER?new OTLPTraceExporter$1:new srcExports$6.OTLPTraceExporter)]});return e.start(),{shutdown:async()=>{await e.shutdown()}}}"yes"===process.env.TESSL_DEBUG_MONITORING&&diag.setLogger(new DiagConsoleLogger,DiagLogLevel.INFO);const sdk=register$1();function isAbortError$3(e){
323
+ process.env.OTEL_EXPORTER_OTLP_HEADERS=`Authorization=Basic ${Buffer.from(`${process.env.TELEMETRY_USER}:${process.env.TELEMETRY_PASSWORD}`).toString("base64")}`}const e=new srcExports$4.NodeSDK({resource:resourceFromAttributes({[ATTR_SERVICE_NAME]:"stepper",[ATTR_K8S_POD_NAME]:process.env.INJECTED_POD_NAME,[ATTR_K8S_NAMESPACE_NAME]:process.env.INJECTED_POD_NAMESPACE,[ATTR_K8S_POD_UID]:process.env.INJECTED_POD_UID,[ATTR_VCS_CHANGE_ID]:"c239ff5e4c64c85bb970e5403eb2556f98ad0f8d",[ATTR_VCS_REF_BASE_NAME]:"c239ff5e4c64c85bb970e5403eb2556f98ad0f8d"}),instrumentations:[new srcExports$5.GrpcInstrumentation({ignoreGrpcMethods:["Check"]})],spanProcessors:[new srcExports$3.SimpleSpanProcessor(process.env.TELEMETRY_USER?new OTLPTraceExporter$1:new srcExports$6.OTLPTraceExporter)]});return e.start(),{shutdown:async()=>{await e.shutdown()}}}"yes"===process.env.TESSL_DEBUG_MONITORING&&diag.setLogger(new DiagConsoleLogger,DiagLogLevel.INFO);const sdk=register$1();function isAbortError$3(e){
324
324
  return"object"==typeof e&&null!==e&&"AbortError"===e.name}function someErrorIs(e,t,r=32){return!(r<=0)&&(!!t(e)||(!!(e instanceof AggregateError&&e.errors.some(e=>someErrorIs(e,t,r-1)))||!!(e instanceof Error&&"cause"in e&&someErrorIs(e.cause,t,r-1))))}const tracer$1=trace$1.getTracer("stepper/otel");let currentUser,bag;function setOtelUser(e){currentUser=e;const t=trace$1.getActiveSpan();currentUser&&t&&(t.setAttribute(ATTR_USER_ID,currentUser.id),t.setAttribute(ATTR_USER_EMAIL,currentUser.email))}async function withSpan(e,t){return tracer$1.startActiveSpan(e,async e=>{currentUser&&(e.setAttribute(ATTR_USER_ID,currentUser.id),e.setAttribute(ATTR_USER_EMAIL,currentUser.email));try{return await t(e)}catch(t){throw annotateSpanWithError(e,t),t}finally{e.end()}})}function annotateSpanWithError(e,t){let r;someErrorIs(t,e=>isAbortError$3(e))&&e.setAttribute("cancelled",!0),t instanceof Error&&(r=t.message),e.setStatus({code:SpanStatusCode.ERROR,message:r})}function execSyncFailsafe(e){try{
325
- return execSync(e,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",cwd:import.meta.dirname}).trim()}catch(e){return"unknown"}}function isGitDirty(){return"clean"}function initSysinfo(e={}){bag||(bag={}),bag.gitRevision="1b07fe35e6be40363eddd9e8ea9b60666a216013",bag.gitDirty=isGitDirty(),bag.releaseDate="2025-09-15T19:45:56.832Z",bag.version="v0.21.0",bag.osImplementation=os$2.type(),bag.osRelease=os$2.release(),bag.argv=JSON.stringify(process.argv),bag.nodeVersion=process.version,bag.nodeExecPath=process.execPath,bag.nodeFirstPath=execSyncFailsafe("which node"),Object.assign(bag,e)}function getSysinfo(){if(!bag)throw new Error("Sysinfo not initialized");return{...bag}}const GLOBAL_DIR_NAME=".tessl",PROJECTS_DIR_NAME="projects";function getGlobalDir(){const e=process.env.TESSL_GLOBAL_DIR;if(e&&""!==e.trim())return e;let t=GLOBAL_DIR_NAME;return join(homedir$1(),t)}function getProjectCacheDir(){const e=process.env.TESSL_PROJECT_CACHE_DIR;if(e&&""!==e.trim())return e
325
+ return execSync(e,{stdio:["ignore","pipe","ignore"],encoding:"utf-8",cwd:import.meta.dirname}).trim()}catch(e){return"unknown"}}function isGitDirty(){return"clean"}function initSysinfo(e={}){bag||(bag={}),bag.gitRevision="c239ff5e4c64c85bb970e5403eb2556f98ad0f8d",bag.gitDirty=isGitDirty(),bag.releaseDate="2025-09-16T11:14:27.886Z",bag.version="v0.21.1",bag.osImplementation=os$2.type(),bag.osRelease=os$2.release(),bag.argv=JSON.stringify(process.argv),bag.nodeVersion=process.version,bag.nodeExecPath=process.execPath,bag.nodeFirstPath=execSyncFailsafe("which node"),Object.assign(bag,e)}function getSysinfo(){if(!bag)throw new Error("Sysinfo not initialized");return{...bag}}const GLOBAL_DIR_NAME=".tessl",PROJECTS_DIR_NAME="projects";function getGlobalDir(){const e=process.env.TESSL_GLOBAL_DIR;if(e&&""!==e.trim())return e;let t=GLOBAL_DIR_NAME;return join(homedir$1(),t)}function getProjectCacheDir(){const e=process.env.TESSL_PROJECT_CACHE_DIR;if(e&&""!==e.trim())return e
326
326
  ;const t=getGlobalDir(),r=getProjectDir().replace(/[/\\:]/g,"-").replace(/^-+/,"");return join(t,PROJECTS_DIR_NAME,r)}function getProjectDir(e=!1){const t=process.env.TESSL_PROJECT_DIR;if(t&&""!==t.trim())return t;let r=process.cwd();for(;;){const t=join(r,CONFIG_DIR_NAME);if(existsSync(t))return r;const n=dirname$1(r);if(n===r||n===homedir$1()){if(e)throw new Error("Tessl project root not found");return process.cwd()}r=n}}const T_AND_C_FILE="terms-and-conditions",T_AND_C_URL="https://tessl.io/policies/terms",T_AND_C_QUESTION=`You'll need to review and accept our Terms of Service at ${T_AND_C_URL} before running Tessl.\n\nAccept Terms of Service? [Y/n] `;async function checkLegal(){const e=getGlobalDir(),t=join$1(e,T_AND_C_FILE);if(!existsSync$1(t)||"accepted"!==readFileSync(t,"utf-8")){const e=createInterface({input:process.stdin,output:process.stdout}),r=await new Promise(t=>{e.question(T_AND_C_QUESTION,r=>{e.close(),t(r.toLowerCase())})});if("n"!==r){const e=dirname(t)
327
327
  ;return existsSync$1(e)||mkdirSync(e,{recursive:!0}),writeFileSync(t,"accepted","utf-8"),!0}return!1}return!0}const balanced=(e,t,r)=>{const n=e instanceof RegExp?maybeMatch(e,r):e,i=t instanceof RegExp?maybeMatch(t,r):t,s=null!==n&&null!=i&&range$2(n,i,r);return s&&{start:s[0],end:s[1],pre:r.slice(0,s[0]),body:r.slice(s[0]+n.length,s[1]),post:r.slice(s[1]+i.length)}},maybeMatch=(e,t)=>{const r=t.match(e);return r?r[0]:null},range$2=(e,t,r)=>{let n,i,s,o,a,c=r.indexOf(e),u=r.indexOf(t,c+1),l=c;if(c>=0&&u>0){if(e===t)return[c,u];for(n=[],s=r.length;l>=0&&!a;){if(l===c)n.push(l),c=r.indexOf(e,l+1);else if(1===n.length){const e=n.pop();void 0!==e&&(a=[e,u])}else i=n.pop(),void 0!==i&&i<s&&(s=i,o=u),u=r.indexOf(t,l+1);l=c<u&&c>=0?c:u}n.length&&void 0!==o&&(a=[s,o])}return a
328
328
  },escSlash="\0SLASH"+Math.random()+"\0",escOpen="\0OPEN"+Math.random()+"\0",escClose="\0CLOSE"+Math.random()+"\0",escComma="\0COMMA"+Math.random()+"\0",escPeriod="\0PERIOD"+Math.random()+"\0",escSlashPattern=new RegExp(escSlash,"g"),escOpenPattern=new RegExp(escOpen,"g"),escClosePattern=new RegExp(escClose,"g"),escCommaPattern=new RegExp(escComma,"g"),escPeriodPattern=new RegExp(escPeriod,"g"),slashPattern=/\\\\/g,openPattern=/\\{/g,closePattern=/\\}/g,commaPattern=/\\,/g,periodPattern=/\\./g;function numeric(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}function escapeBraces(e){return e.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}function unescapeBraces(e){return e.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}function parseCommaParts(e){if(!e)return[""]
@@ -443,8 +443,8 @@ level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function _supportsColor$1(e,{stream
443
443
  function stringEncaseCRLFWithFirstIndex(e,t,r,n){let i=0,s="";do{const o="\r"===e[n-1];s+=e.slice(i,o?n-1:n)+t+(o?"\r\n":"\n")+r,i=n+1,n=e.indexOf("\n",i)}while(-1!==n);return s+=e.slice(i),s}const{stdout:stdoutColor,stderr:stderrColor}=supportsColor,GENERATOR=Symbol("GENERATOR"),STYLER=Symbol("STYLER"),IS_EMPTY=Symbol("IS_EMPTY"),levelMapping=["ansi","ansi","ansi256","ansi16m"],styles$2=Object.create(null),applyOptions=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const r=stdoutColor?stdoutColor.level:0;e.level=void 0===t.level?r:t.level},chalkFactory=e=>{const t=(...e)=>e.join(" ");return applyOptions(t,e),Object.setPrototypeOf(t,createChalk.prototype),t};function createChalk(e){return chalkFactory(e)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(const[e,t]of Object.entries(ansiStyles$3))styles$2[e]={get(){
444
444
  const r=createBuilder(this,createStyler(t.open,t.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,e,{value:r}),r}};styles$2.visible={get(){const e=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:e}),e}};const getModelAnsi=(e,t,r,...n)=>"rgb"===e?"ansi16m"===t?ansiStyles$3[r].ansi16m(...n):"ansi256"===t?ansiStyles$3[r].ansi256(ansiStyles$3.rgbToAnsi256(...n)):ansiStyles$3[r].ansi(ansiStyles$3.rgbToAnsi(...n)):"hex"===e?getModelAnsi("rgb",t,r,...ansiStyles$3.hexToRgb(...n)):ansiStyles$3[r][e](...n),usedModels=["rgb","hex","ansi256"];for(const e of usedModels){styles$2[e]={get(){const{level:t}=this;return function(...r){const n=createStyler(getModelAnsi(e,levelMapping[t],"color",...r),ansiStyles$3.color.close,this[STYLER]);return createBuilder(this,n,this[IS_EMPTY])}}};const t="bg"+e[0].toUpperCase()+e.slice(1);styles$2[t]={get(){const{level:t}=this;return function(...r){
445
445
  const n=createStyler(getModelAnsi(e,levelMapping[t],"bgColor",...r),ansiStyles$3.bgColor.close,this[STYLER]);return createBuilder(this,n,this[IS_EMPTY])}}}}const proto=Object.defineProperties(()=>{},{...styles$2,level:{enumerable:!0,get(){return this[GENERATOR].level},set(e){this[GENERATOR].level=e}}}),createStyler=(e,t,r)=>{let n,i;return void 0===r?(n=e,i=t):(n=r.openAll+e,i=t+r.closeAll),{open:e,close:t,openAll:n,closeAll:i,parent:r}},createBuilder=(e,t,r)=>{const n=(...e)=>applyStyle(n,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(n,proto),n[GENERATOR]=e,n[STYLER]=t,n[IS_EMPTY]=r,n},applyStyle=(e,t)=>{if(e.level<=0||!t)return e[IS_EMPTY]?"":t;let r=e[STYLER];if(void 0===r)return t;const{openAll:n,closeAll:i}=r;if(t.includes(""))for(;void 0!==r;)t=stringReplaceAll(t,r.close,r.open),r=r.parent;const s=t.indexOf("\n");return-1!==s&&(t=stringEncaseCRLFWithFirstIndex(t,i,n,s)),n+t+i};Object.defineProperties(createChalk.prototype,styles$2);const chalk=createChalk()
446
- ;function _nullishCoalesce$11(e,t){return null!=e?e:t()}function _optionalChain$19(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}createChalk({level:stderrColor?stderrColor.level:0});const LATEST_TXT_URL=_nullishCoalesce$11(process.env.TESSL_LATEST_URL,()=>"https://install.tessl.io/metadata/latest.txt");function getCurrentVersion(){const{version:e}=getSysinfo();return e&&"unknown"!==e?e:"v0.0.0-development"}function isDevelopmentBuild(){try{const{version:e}=getSysinfo();return!e||"unknown"===e}catch(e){return!0}}async function getLatestVersion(e){const t=_nullishCoalesce$11(_optionalChain$19([e,"optionalAccess",e=>e.timeout]),()=>2e3),r=new AbortController,n=setTimeout(()=>r.abort(),t);try{const t=Date.now(),i=await fetch(LATEST_TXT_URL,{signal:r.signal})
447
- ;if(_optionalChain$19([e,"optionalAccess",e=>e.logger,"optionalAccess",e=>e.debug,"call",e=>e({requestDurationMs:Date.now()-t},"Latest version fetched successfully")]),clearTimeout(n),!i.ok)throw new Error("Failed to fetch latest version. Please check your internet connection or try again later.");return(await i.text()).trim()}catch(e){if(clearTimeout(n),e instanceof Error&&"AbortError"===e.name)throw new Error(`Version check timed out after ${t/1e3} seconds`);throw e}}async function printVersion({logger:e}){const{version:t}=getSysinfo(),r=await getLatestVersion({logger:e,timeout:5e3});console.log(t),console.log(""),r!==t&&printUpdateGuidance({latestVersion:r})}function printUpdateGuidance({latestVersion:e}){console.info(`You are not running the latest version (${e}). Run ${chalk.blue("tessl update")} to update to it.\n`)}function _nullishCoalesce$10(e,t){return null!=e?e:t()}
446
+ ;function _nullishCoalesce$11(e,t){return null!=e?e:t()}function _optionalChain$18(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}createChalk({level:stderrColor?stderrColor.level:0});const LATEST_TXT_URL=_nullishCoalesce$11(process.env.TESSL_LATEST_URL,()=>"https://install.tessl.io/metadata/latest.txt");function getCurrentVersion(){const{version:e}=getSysinfo();return e&&"unknown"!==e?e:"v0.0.0-development"}function isDevelopmentBuild(){try{const{version:e}=getSysinfo();return!e||"unknown"===e}catch(e){return!0}}async function getLatestVersion(e){const t=_nullishCoalesce$11(_optionalChain$18([e,"optionalAccess",e=>e.timeout]),()=>2e3),r=new AbortController,n=setTimeout(()=>r.abort(),t);try{const t=Date.now(),i=await fetch(LATEST_TXT_URL,{signal:r.signal})
447
+ ;if(_optionalChain$18([e,"optionalAccess",e=>e.logger,"optionalAccess",e=>e.debug,"call",e=>e({requestDurationMs:Date.now()-t},"Latest version fetched successfully")]),clearTimeout(n),!i.ok)throw new Error("Failed to fetch latest version. Please check your internet connection or try again later.");return(await i.text()).trim()}catch(e){if(clearTimeout(n),e instanceof Error&&"AbortError"===e.name)throw new Error(`Version check timed out after ${t/1e3} seconds`);throw e}}async function printVersion({logger:e}){const{version:t}=getSysinfo(),r=await getLatestVersion({logger:e,timeout:5e3});console.log(t),console.log(""),r!==t&&printUpdateGuidance({latestVersion:r})}function printUpdateGuidance({latestVersion:e}){console.info(`You are not running the latest version (${e}). Run ${chalk.blue("tessl update")} to update to it.\n`)}function _nullishCoalesce$10(e,t){return null!=e?e:t()}
448
448
  const DEPRECATED_EXIT_CODE=146,DEPRECATION_STATUS_CACHE_KEY="deprecation-status-cache",CACHE_EXPIRY_MS=1728e5,DEPRECATION_INFO_URL=_nullishCoalesce$10(process.env.TESSL_DEPRECATION_URL,()=>"https://install.tessl.io/metadata/deprecation-info.json");function isVersionDeprecated(e,t){for(const r of t)if(matchesVersionPattern(e,r))return!0;return!1}function isDeprecationInfo(e){return null!==e&&"object"==typeof e&&"deprecated_versions"in e&&"message"in e&&"install_url"in e&&Array.isArray(e.deprecated_versions)&&"string"==typeof e.message&&"string"==typeof e.install_url}function isDeprecationMessage(e){return null!==e&&"object"==typeof e&&"message"in e&&"installUrl"in e&&"string"==typeof e.message&&"string"==typeof e.installUrl}function isDeprecationStatusCache(e){return null!==e&&"object"==typeof e&&"data"in e&&"timestamp"in e&&"number"==typeof e.timestamp&&(null===e.data||isDeprecationMessage(e.data))}async function readStatusCache(){try{
449
449
  const e=await projectCache().readText(DEPRECATION_STATUS_CACHE_KEY);if(!e)return;const t=JSON.parse(e);if(!isDeprecationStatusCache(t))return;if(Date.now()-t.timestamp>CACHE_EXPIRY_MS)return;return t.data}catch(e){return}}async function writeStatusCache(e){try{const t={data:e,timestamp:Date.now()};await projectCache().writeText(DEPRECATION_STATUS_CACHE_KEY,JSON.stringify(t))}catch(e){}}function matchesVersionPattern(e,t){if(e===t)return!0;if(t.endsWith("*")){const r=t.slice(0,-1);return e.startsWith(r)}return!1}async function fetchDeprecationInfo(e=2e3){const t=new AbortController,r=setTimeout(()=>t.abort(),e);try{const e=await fetch(DEPRECATION_INFO_URL,{signal:t.signal});if(clearTimeout(r),!e.ok)return null;const n=await e.json();return isDeprecationInfo(n)?n:null}catch(e){return clearTimeout(r),null}}async function checkDeprecationStatus(e=2e3){if(isDevelopmentBuild())return null;const t=getCurrentVersion(),r=await fetchDeprecationInfo(e);if(!r)return null
450
450
  ;return isVersionDeprecated(t,r.deprecated_versions)?{message:r.message,installUrl:r.install_url}:null}async function checkDeprecationStatusWithCache(e=2e3){try{const t=await readStatusCache();if(void 0!==t)return(async()=>{try{const t=await checkDeprecationStatus(e);await writeStatusCache(t)}catch(e){}})().catch(()=>{}),t;const r=await checkDeprecationStatus(e);return await writeStatusCache(r),r}catch(t){return checkDeprecationStatus(e)}}class ExpectedError extends Error{}class RequiresLoginError extends ExpectedError{constructor(...e){super(...e),RequiresLoginError.prototype.__init.call(this)}__init(){this.message="You must be logged in to run this command. Run `tessl login` to authenticate."}}class RequiresInitError extends ExpectedError{constructor(...e){super(...e),RequiresInitError.prototype.__init2.call(this)}__init2(){this.message="Tessl isn't initialized in this directory yet. Run `tessl init` to get started, or `tessl help` to learn more."}}
@@ -958,10 +958,10 @@ if(hasRequiredPack)return pack;hasRequiredPack=1;const{Readable:e,Writable:t,get
958
958
  ;if(this._pack._finalized)return e(new Error("pack stream is already finalized"));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){return this._isLinkname?(this._linkname=this._linkname?n.concat([this._linkname,e]):e,t(null)):this._isVoid?e.byteLength>0?t(new Error("No body allowed for this entry")):t():(this.written+=e.byteLength,this._pack.push(e)?t():void(this._pack._drain=t))}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?n.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header)),l(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(new Error("Size mismatch"));this._finish(),e(null)}_getError(){return r(this)||new Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),
959
959
  this._continuePack(this._finished?null:this._getError()),e()}}class c extends e{constructor(e){super(e),this._drain=u,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,r){if(this._finalized||this.destroying)throw new Error("already finalized or destroyed");"function"==typeof t&&(r=t,t=null),r||(r=u),e.size&&"symlink"!==e.type||(e.size=0),e.type||(e.type=function(e){switch(e&i.S_IFMT){case i.S_IFBLK:return"block-device";case i.S_IFCHR:return"character-device";case i.S_IFDIR:return"directory";case i.S_IFIFO:return"fifo";case i.S_IFLNK:return"symlink"}return"file"}(e.mode)),e.mode||(e.mode="directory"===e.type?493:420),e.uid||(e.uid=0),e.gid||(e.gid=0),e.mtime||(e.mtime=new Date),"string"==typeof t&&(t=n.from(t));const s=new a(this,e,r);return n.isBuffer(t)?(e.size=t.byteLength,s.write(t),s.end(),s):(s._isVoid,s)}finalize(){this._stream||this._pending.length>0?this._finalizing=!0:this._finalized||(this._finalized=!0,this.push(o),this.push(null))}_done(e){
960
960
  e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){const t=s.encode(e);if(t)return void this.push(t)}this._encodePax(e)}_encodePax(e){const t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),r={name:"PaxHeader",mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:"pax-header",linkname:e.linkname&&"PaxHeader",uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(r)),this.push(t),l(this,t.byteLength),r.size=e.size,r.type=e.type,this.push(s.encode(r))}_doDrain(){const e=this._drain;this._drain=u,e()}_predestroy(){const e=r(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){const t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}}function u(){}function l(e,t){(t&=511)&&e.push(o.subarray(0,512-t))}function d(e){return n.isBuffer(e)?e:n.from(e)}
961
- return pack=function(e){return new c(e)}}function requireTarStream(){return hasRequiredTarStream||(hasRequiredTarStream=1,tarStream.extract=requireExtract(),tarStream.pack=requirePack()),tarStream}var tarStreamExports=requireTarStream(),tar=getDefaultExportFromCjs(tarStreamExports);function _optionalChain$18(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const WELL_KNOWN_PACKAGE_TILE_MANIFEST_FILENAME="package.tile.json";function parsePackageTileManifest(e){const t=JSON.parse(e);return _optionalChain$18([t,"optionalAccess",e=>e.spec])?t:void 0}function findPackageTileManifest(e){const t=e[WELL_KNOWN_PACKAGE_TILE_MANIFEST_FILENAME];return t?parsePackageTileManifest(t):void 0}function getPackageSpec(e,t){if(_optionalChain$18([t,"optionalAccess",e=>e.spec])){const r=e[t.spec]
962
- ;if(r)return{path:t.spec,content:r}}}function _optionalChain$17(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function extractFilesFromNpmPackage(e,{npmRegistryUrl:t}){const r=purlToNpmTarballUrl(e,t),n=await fetchFilesFromTarGz(r);if(!n.ok)return n;const i=n.files["package.json"],s=findPackageTileManifest(n.files),o=getPackageSpec(n.files,s),a=findReadme(n.files),c={};return i&&(c["package.json"]=i),s&&(c[WELL_KNOWN_PACKAGE_TILE_MANIFEST_FILENAME]=JSON.stringify(s)),o&&(c[o.path]=o.content),{ok:!0,packageTileManifest:s,packageSpec:_optionalChain$17([o,"optionalAccess",e=>e.content]),readme:a,files:c}}async function fetchFilesFromTarGz(e){const t=validateFetchResponse(await fetch(e));if(!t.ok)return t;const r={},n=tar.extract();return n.on("entry",(e,t,n)=>{
961
+ return pack=function(e){return new c(e)}}function requireTarStream(){return hasRequiredTarStream||(hasRequiredTarStream=1,tarStream.extract=requireExtract(),tarStream.pack=requirePack()),tarStream}var tarStreamExports=requireTarStream(),tar=getDefaultExportFromCjs(tarStreamExports);function _optionalChain$17(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const WELL_KNOWN_PACKAGE_TILE_MANIFEST_FILENAME="package.tile.json";function parsePackageTileManifest(e){const t=JSON.parse(e);return _optionalChain$17([t,"optionalAccess",e=>e.spec])?t:void 0}function findPackageTileManifest(e){const t=e[WELL_KNOWN_PACKAGE_TILE_MANIFEST_FILENAME];return t?parsePackageTileManifest(t):void 0}function getPackageSpec(e,t){if(_optionalChain$17([t,"optionalAccess",e=>e.spec])){const r=e[t.spec]
962
+ ;if(r)return{path:t.spec,content:r}}}function _optionalChain$16(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function extractFilesFromNpmPackage(e,{npmRegistryUrl:t}){const r=purlToNpmTarballUrl(e,t),n=await fetchFilesFromTarGz(r);if(!n.ok)return n;const i=n.files["package.json"],s=findPackageTileManifest(n.files),o=getPackageSpec(n.files,s),a=findReadme(n.files),c={};return i&&(c["package.json"]=i),s&&(c[WELL_KNOWN_PACKAGE_TILE_MANIFEST_FILENAME]=JSON.stringify(s)),o&&(c[o.path]=o.content),{ok:!0,packageTileManifest:s,packageSpec:_optionalChain$16([o,"optionalAccess",e=>e.content]),readme:a,files:c}}async function fetchFilesFromTarGz(e){const t=validateFetchResponse(await fetch(e));if(!t.ok)return t;const r={},n=tar.extract();return n.on("entry",(e,t,n)=>{
963
963
  if(shouldCollectFile(e)){let i="";t.on("data",e=>i+=e.toString()),t.on("end",()=>{r[e.name.replace(/^package\//,"")]=i,n()})}else t.resume(),t.on("end",n)}),await pipeline(Readable$1.fromWeb(t.body),createGunzip(),n),{ok:!0,files:r}}function shouldCollectFile({type:e,name:t}){if("file"!==e)return!1;if("package/package.json"===t)return!0;if(t===`package/${WELL_KNOWN_PACKAGE_TILE_MANIFEST_FILENAME}`)return!0;if("package/readme.md"===t.toLowerCase())return!0;return[".md",".markdown",".mdown"].some(e=>t.toLowerCase().endsWith(e))}function purlToNpmTarballUrl(e,t){return`${t}/${e.namespace?`${e.namespace}/${e.name}`:e.name}/-/${e.name}-${e.version}.tgz`}function validateFetchResponse(e){return e.ok&&e.body?{ok:!0,body:e.body}:404===e.status?{ok:!1,reason:`Tarball not found at ${e.url}`}:{ok:!1,reason:`Failed to fetch tarball from ${e.url} Status: ${e.statusText}`}}function findReadme(e){for(const[t,r]of Object.entries(e))if(r&&"readme.md"===t.toLowerCase())return r}
964
- function _optionalChain$16(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const npmRegistryUrl="https://registry.npmjs.org";async function extractPackageContents(e){return _optionalChain$16([e,"access",e=>e.qualifiers,"optionalAccess",e=>e.repository_url])?{ok:!1,reason:`PackageURL with repository_url is not yet supported: ${e.toString()}`}:e.qualifiers&&Object.keys(e.qualifiers).length>0?{ok:!1,reason:`PackageURL with qualifiers is not yet supported: ${e.toString()}`}:e.version?"npm"===e.type?await extractFilesFromNpmPackage(e,{npmRegistryUrl}):{ok:!1,reason:`Unsupported package type: ${e.type}`}:{ok:!1,reason:"PackageURL must include a version"}}function purlToPackageDisplayName(e){if("npm"===e.type)return e.namespace?`${e.namespace}/${e.name}`:e.name
964
+ function _optionalChain$15(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const npmRegistryUrl="https://registry.npmjs.org";async function extractPackageContents(e){return _optionalChain$15([e,"access",e=>e.qualifiers,"optionalAccess",e=>e.repository_url])?{ok:!1,reason:`PackageURL with repository_url is not yet supported: ${e.toString()}`}:e.qualifiers&&Object.keys(e.qualifiers).length>0?{ok:!1,reason:`PackageURL with qualifiers is not yet supported: ${e.toString()}`}:e.version?"npm"===e.type?await extractFilesFromNpmPackage(e,{npmRegistryUrl}):{ok:!1,reason:`Unsupported package type: ${e.type}`}:{ok:!1,reason:"PackageURL must include a version"}}function purlToPackageDisplayName(e){if("npm"===e.type)return e.namespace?`${e.namespace}/${e.name}`:e.name
965
965
  ;throw new Error("Unsupported package type. Only npm is supported")}const processPackageParamsSchema=objectType({purl:stringType()}),processPackage={name:"process-package",type:"fsd",impl:processPackageImpl,paramsSchema:processPackageParamsSchema,description:"Extracts metadata from a Package URL and publishes to the Tile Directory",visibility:"private"};async function processPackageImpl({utils:e,params:t,rc:r}){const n=r.tilePackagesClient;if(!n)throw new Error("Tile Packages client is not available in the request context");const i=packageurlJsExports.PackageURL.fromString(t.purl);r.logger.debug({purl:t.purl},"Processing package with purl");const s=await extractPackageContents(i);if(!s.ok)return r.logger.error({purl:t.purl},s.reason),await r.emitMgmt({id:"setOutput",value:{ok:!1,message:s.reason}}),0;const o=s.packageSpec,a=s.readme;if(!o)return r.logger.warn({purl:t.purl},"package spec not found"),await r.emitMgmt({id:"setOutput",value:{ok:!1,message:"Package is not a Tile package"}
966
966
  }),0;const{summaryText:c,descriptionMarkdown:u,lookupText:l}=await generateText(e.script,i,o,a);return await n.submitTilePackageVersion({purl:i.toString(),summaryText:c,descriptionMarkdown:u,lookupText:l,readmeText:a,filesJson:JSON.stringify(s.files)}),await r.emitMgmt({id:"setOutput",value:{ok:!0,message:"Package processed successfully"}}),0}async function generateText(e,t,r,n){const i=purlToPackageDisplayName(t),s=stripIndent`
967
967
  You are a software engineer tasked with summarizing the contents of a published software package.
@@ -1151,13 +1151,13 @@ td:!0,th:!0,TD:!0,TH:!0},TD:{td:!0,th:!0,TD:!0,TH:!0},th:{td:!0,th:!0,TD:!0,TH:!
1151
1151
  },l=Object.keys(u),d=l.map(e=>new RegExp(`^${e}$`,"i")),p=l.filter(e=>Boolean(u[e])).map(e=>new RegExp(`^${e}$`,"i"));function E(e){return p.some(t=>t.test(e))}function b(e){return d.some(t=>t.test(e))}const C=(e,t)=>[e-x,t-x],I=new h(null,{},"",null,[0,e.length],a,t);let v=I;const w=[I];let S,_,D=-1;e=`<${y}>${e}</${y}>`;const{lowerCaseTagName:B,fixNestedATags:R}=t,T=e.length-(y.length+2),x=y.length+2;for(;_=A.exec(e);){let{0:r,1:i,2:s,3:u,4:l}=_;const d=r.length,p=A.lastIndex-d,I=A.lastIndex;if(D>-1&&D+d<I){const t=e.substring(D,p);v.appendChild(new c.default(t,v,C(D,p)))}if(D=A.lastIndex,s!==y)if("!"!==r[1]){if(B&&(s=s.toLowerCase()),!i){const r={};for(let e;e=f.exec(u);){const{1:t,2:n}=e,i="'"===n[0]||'"'===n[0];r[t.toLowerCase()]=i?n.slice(1,n.length-1):n}const o=v.rawTagName;!l&&g[o]&&g[o][s]&&(w.pop(),v=(0,n.default)(w)),!R||"a"!==s&&"A"!==s||(void 0!==S&&(w.splice(S),v=(0,n.default)(w)),S=w.length);const p=A.lastIndex,m=p-d
1152
1152
  ;if(v=v.appendChild(new h(s,r,u.slice(1),null,C(m,p),a,t)),w.push(v),b(s)){const t=`</${s}>`,r=B?e.toLocaleLowerCase().indexOf(t,A.lastIndex):e.indexOf(t,A.lastIndex),n=-1===r?T:r;if(E(s)){const t=e.substring(p,n);t.length>0&&/\S/.test(t)&&v.appendChild(new c.default(t,v,C(p,n)))}-1===r?D=A.lastIndex=e.length+1:(D=A.lastIndex=r+t.length,i="/")}}if(i||l||a.isVoidElement(s))for(;;){if(null==S||"a"!==s&&"A"!==s||(S=void 0),v.rawTagName===s){v.range[1]=C(-1,Math.max(D,I))[1],w.pop(),v=(0,n.default)(w);break}{const e=v.tagName;if(m[e]&&m[e][s]){w.pop(),v=(0,n.default)(w);continue}break}}}else if(t.comment){const t=e.substring(p+4,I-3);v.appendChild(new o.default(t,v,C(p,I)))}}return w}function b(e,t={}){const r=E(e,t),[i]=r;for(;r.length>1;){const e=r.pop(),i=(0,n.default)(r);e.parentNode&&e.parentNode.parentNode&&(e.parentNode===i&&e.tagName===i.tagName?!0!==t.parseNoneClosedTags&&(i.removeChild(e),e.childNodes.forEach(e=>{i.parentNode.appendChild(e)}),
1153
1153
  r.pop()):!0!==t.parseNoneClosedTags&&(i.removeChild(e),e.childNodes.forEach(e=>{i.appendChild(e)})))}return i}function C(e){return e.map(e=>"string"==typeof e?new c.default(e):(e.remove(),e))}function I(e,t){return e.map(e=>(e.parentNode=t,e))}return html.base_parse=E,html.parse=b,html}var parse$4={},hasRequiredParse$3;function requireParse$3(){return hasRequiredParse$3||(hasRequiredParse$3=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var t=requireHtml();Object.defineProperty(e,"default",{enumerable:!0,get:function(){return t.parse}})}(parse$4)),parse$4}var valid={},hasRequiredValid,hasRequiredDist$3;function requireValid(){if(hasRequiredValid)return valid;hasRequiredValid=1,Object.defineProperty(valid,"__esModule",{value:!0});const e=requireHtml();return valid.default=function(t,r={}){const n=(0,e.base_parse)(t,r);return Boolean(1===n.length)},valid}function requireDist$3(){if(hasRequiredDist$3)return dist$3;hasRequiredDist$3=1
1154
- ;var e=dist$3&&dist$3.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(dist$3,"__esModule",{value:!0}),dist$3.NodeType=dist$3.TextNode=dist$3.Node=dist$3.valid=dist$3.CommentNode=dist$3.HTMLElement=dist$3.parse=void 0;const t=e(requireComment$1());dist$3.CommentNode=t.default;const r=e(requireHtml());dist$3.HTMLElement=r.default;const n=e(requireNode$4());dist$3.Node=n.default;const i=e(requireText());dist$3.TextNode=i.default;const s=e(requireType$1());dist$3.NodeType=s.default;const o=e(requireParse$3()),a=e(requireValid());function c(e,t={}){return(0,o.default)(e,t)}return dist$3.valid=a.default,dist$3.default=c,dist$3.parse=c,c.parse=o.default,c.HTMLElement=r.default,c.CommentNode=t.default,c.valid=a.default,c.Node=n.default,c.TextNode=i.default,c.NodeType=s.default,dist$3}var distExports$1=requireDist$3(),htmlParser=getDefaultExportFromCjs(distExports$1);function _nullishCoalesce$Y(e,t){return null!=e?e:t()}function _optionalChain$15(e){
1155
- let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function createSections(e){const t=new distExports$1.HTMLElement("section",{}),r=[{level:0,container:t}],n=()=>r[r.length-1],i=Array.from(e.childNodes);for(const e of i)if(e instanceof distExports$1.HTMLElement){const t=e.tagName.match(/^H([1-6])$/);if(t&&!isAlreadyNested(e)){const i=parseInt(_nullishCoalesce$Y(t[1],()=>"0"));for(;r.length>1&&_optionalChain$15([n,"call",e=>e(),"optionalAccess",e=>e.level])>=i;)r.pop();const s=new distExports$1.HTMLElement("section",{});for(const t of e.classList.values())s.classList.add(t);s.appendChild(e),n().container.appendChild(s),r.push({level:i,container:s})}else e.classList.contains("section")||n().container.appendChild(e)}else n().container.appendChild(e);return t}function isAlreadyNested(e){
1156
- const t=e.parentNode;return"SECTION"===_optionalChain$15([t,"optionalAccess",e=>e.tagName])&&t.firstChild===e}function parseHtml(e){return htmlParser.parse(e,{comment:!0,blockTextElements:{code:!0}})}function findParent(e,t,r){let n=e.parentNode;for(;n;){if(t.includes(n.tagName))return n;if(r&&r.includes(n.tagName))return;n=n.parentNode}}function _nullishCoalesce$X(e,t){return null!=e?e:t()}function _optionalChain$14(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function htmlDomToMarkdown(e){const t=renderChildren(e).trim();return e.parentNode?t:t+"\n"}const isTextNode=e=>e.nodeType===distExports$1.NodeType.TEXT_NODE,isElementNode=e=>e.nodeType===distExports$1.NodeType.ELEMENT_NODE,canRenderTag=e=>e in elementRenderers,elementRenderers={a:renderLink,b:renderBold,
1157
- blockquote:renderBlockQuote,br:()=>"\n",code:renderCodeInline,div:renderChildren,em:renderItalic,h1:renderHeading,h2:renderHeading,h3:renderHeading,h4:renderHeading,h5:renderHeading,h6:renderHeading,hr:()=>"---",i:renderItalic,img:renderImage,li:renderListItem,ol:renderList,p:renderParagraph,pre:renderPre,section:renderChildren,span:renderChildren,strong:renderBold,ul:renderList,input:renderInput};function renderChildren(e){let t="";for(const r of e.childNodes){const e=renderNode(r);t=isBlockElement(r)?appendBlockElementToBuffer(t,e):appendInlineElementToBuffer(t,e)}return t}function renderNode(e){if(isTextNode(e))return renderTextNode(e);if(isElementNode(e)){const t=_optionalChain$14([e,"access",e=>e.tagName,"optionalAccess",e=>e.toLowerCase,"call",e=>e()]);return canRenderTag(t)?elementRenderers[t](e):renderChildren(e)}throw new Error(`Unknown node type: ${e.nodeType}`)}function renderTextNode(e){return e.text.replace(/\s*\n\s*/g," ").trim()}function renderItalic(e){
1154
+ ;var e=dist$3&&dist$3.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(dist$3,"__esModule",{value:!0}),dist$3.NodeType=dist$3.TextNode=dist$3.Node=dist$3.valid=dist$3.CommentNode=dist$3.HTMLElement=dist$3.parse=void 0;const t=e(requireComment$1());dist$3.CommentNode=t.default;const r=e(requireHtml());dist$3.HTMLElement=r.default;const n=e(requireNode$4());dist$3.Node=n.default;const i=e(requireText());dist$3.TextNode=i.default;const s=e(requireType$1());dist$3.NodeType=s.default;const o=e(requireParse$3()),a=e(requireValid());function c(e,t={}){return(0,o.default)(e,t)}return dist$3.valid=a.default,dist$3.default=c,dist$3.parse=c,c.parse=o.default,c.HTMLElement=r.default,c.CommentNode=t.default,c.valid=a.default,c.Node=n.default,c.TextNode=i.default,c.NodeType=s.default,dist$3}var distExports$1=requireDist$3(),htmlParser=getDefaultExportFromCjs(distExports$1);function _nullishCoalesce$Y(e,t){return null!=e?e:t()}function _optionalChain$14(e){
1155
+ let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function createSections(e){const t=new distExports$1.HTMLElement("section",{}),r=[{level:0,container:t}],n=()=>r[r.length-1],i=Array.from(e.childNodes);for(const e of i)if(e instanceof distExports$1.HTMLElement){const t=e.tagName.match(/^H([1-6])$/);if(t&&!isAlreadyNested(e)){const i=parseInt(_nullishCoalesce$Y(t[1],()=>"0"));for(;r.length>1&&_optionalChain$14([n,"call",e=>e(),"optionalAccess",e=>e.level])>=i;)r.pop();const s=new distExports$1.HTMLElement("section",{});for(const t of e.classList.values())s.classList.add(t);s.appendChild(e),n().container.appendChild(s),r.push({level:i,container:s})}else e.classList.contains("section")||n().container.appendChild(e)}else n().container.appendChild(e);return t}function isAlreadyNested(e){
1156
+ const t=e.parentNode;return"SECTION"===_optionalChain$14([t,"optionalAccess",e=>e.tagName])&&t.firstChild===e}function parseHtml(e){return htmlParser.parse(e,{comment:!0,blockTextElements:{code:!0}})}function findParent(e,t,r){let n=e.parentNode;for(;n;){if(t.includes(n.tagName))return n;if(r&&r.includes(n.tagName))return;n=n.parentNode}}function _nullishCoalesce$X(e,t){return null!=e?e:t()}function _optionalChain$13(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function htmlDomToMarkdown(e){const t=renderChildren(e).trim();return e.parentNode?t:t+"\n"}const isTextNode=e=>e.nodeType===distExports$1.NodeType.TEXT_NODE,isElementNode=e=>e.nodeType===distExports$1.NodeType.ELEMENT_NODE,canRenderTag=e=>e in elementRenderers,elementRenderers={a:renderLink,b:renderBold,
1157
+ blockquote:renderBlockQuote,br:()=>"\n",code:renderCodeInline,div:renderChildren,em:renderItalic,h1:renderHeading,h2:renderHeading,h3:renderHeading,h4:renderHeading,h5:renderHeading,h6:renderHeading,hr:()=>"---",i:renderItalic,img:renderImage,li:renderListItem,ol:renderList,p:renderParagraph,pre:renderPre,section:renderChildren,span:renderChildren,strong:renderBold,ul:renderList,input:renderInput};function renderChildren(e){let t="";for(const r of e.childNodes){const e=renderNode(r);t=isBlockElement(r)?appendBlockElementToBuffer(t,e):appendInlineElementToBuffer(t,e)}return t}function renderNode(e){if(isTextNode(e))return renderTextNode(e);if(isElementNode(e)){const t=_optionalChain$13([e,"access",e=>e.tagName,"optionalAccess",e=>e.toLowerCase,"call",e=>e()]);return canRenderTag(t)?elementRenderers[t](e):renderChildren(e)}throw new Error(`Unknown node type: ${e.nodeType}`)}function renderTextNode(e){return e.text.replace(/\s*\n\s*/g," ").trim()}function renderItalic(e){
1158
1158
  return`_${renderChildren(e)}_`}function renderBold(e){return`**${renderChildren(e)}**`}function renderLink(e){return`[${renderChildren(e)}](${_nullishCoalesce$X(e.getAttribute("href"),()=>"")})`}function renderCodeInline(e){return`\`${e.text}\``}function renderImage(e){const t=_nullishCoalesce$X(e.getAttribute("src"),()=>"");return`![${_nullishCoalesce$X(e.getAttribute("alt"),()=>"")}](${t})`}function renderInput(e){if("checkbox"===e.getAttribute("type")){return e.hasAttribute("checked")?"[x]":"[ ]"}return""}function renderParagraph(e){return`\n\n${renderChildren(e)}\n\n`}function renderHeading(e){const t=parseInt(e.tagName[1],10);return`\n\n${"#".repeat(t)} ${renderChildren(e)}${renderAttributes(e)}\n\n`}function renderBlockQuote(e){const t=renderChildren(e).trim().split("\n").map(e=>`> ${e}`).join("\n"),r=e.parentNode;return r.tagName&&"li"===r.tagName.toLowerCase()&&r.lastElementChild===e?"\n"+t:`\n\n${t}\n\n`}function renderPre(e){const t=e.querySelector("code")
1159
- ;if(t)return renderCodeBlock(t);return`\n\n\`\`\`${ensureLeadingNewLine(ensureTrailingNewline(e.text))}\`\`\`\n\n`}function renderCodeBlock(e){const t=(_optionalChain$14([e,"access",e=>e.getAttribute,"call",e=>e("class"),"optionalAccess",e=>e.split,"call",e=>e(/\s+/)])||[]).find(e=>e.startsWith("language-"));return`\n\n\`\`\`${t?t.replace(/^language-/,""):""}${renderAttributes(e,{ignoreLanguageClass:!0})}\n${ensureTrailingNewline(e.text)}\`\`\`\n\n`}function renderList(e){const t=e.childNodes.filter(isElementNode).filter(e=>"li"===e.tagName.toLowerCase()).map(e=>renderListItem(e)).join("\n"),r=e.parentNode;return r.tagName&&"li"===r.tagName.toLowerCase()&&r.lastElementChild===e?"\n"+t:"\n\n"+t+"\n\n"}function renderListItem(e){const t=renderListItemChildren(e,renderAttributes(e)).replace(/^\n+/,"").replace(/\n+$/,"\n"),r=countPreviousSiblingElements(e),n="ol"===e.parentNode.tagName.toLowerCase()?`${r+1}.`:"-",i=t.split("\n"),s=`${n} ${i[0]}`,o=" ".repeat(n.length+1)
1160
- ;return[s,...i.slice(1).map(e=>e.trimStart()?`${o}${e}`:"")].join("\n")}function renderListItemChildren(e,t){let r="",n=!1,i=0;for(const s of e.childNodes){const o=e.childNodes[i+1];let a=renderNode(s);!t||n||o&&!isBlockElement(o)||(n=!0,a+=a?t:t.trim()),r=isBlockElement(s)?appendBlockElementToBuffer(r,a):appendInlineElementToBuffer(r,a),i++}return trimLeadingNewlines(r)}function renderAttributes(e,t){const r=e.getAttribute("id");let n=_optionalChain$14([e,"access",e=>e.getAttribute,"call",e=>e("class"),"optionalAccess",e=>e.split,"call",e=>e(/\s+/),"access",e=>e.filter,"call",e=>e(Boolean)])||[];_optionalChain$14([t,"optionalAccess",e=>e.ignoreLanguageClass])&&(n=n.filter(e=>!e.startsWith("language-")));const i=[];return r&&i.push(`#${r}`),i.push(...n.map(e=>`.${e}`)),0===i.length?"":_optionalChain$14([t,"optionalAccess",e=>e.hang])?`\n \n{ ${i.join(" ")} }`:` { ${i.join(" ")} }`}
1159
+ ;if(t)return renderCodeBlock(t);return`\n\n\`\`\`${ensureLeadingNewLine(ensureTrailingNewline(e.text))}\`\`\`\n\n`}function renderCodeBlock(e){const t=(_optionalChain$13([e,"access",e=>e.getAttribute,"call",e=>e("class"),"optionalAccess",e=>e.split,"call",e=>e(/\s+/)])||[]).find(e=>e.startsWith("language-"));return`\n\n\`\`\`${t?t.replace(/^language-/,""):""}${renderAttributes(e,{ignoreLanguageClass:!0})}\n${ensureTrailingNewline(e.text)}\`\`\`\n\n`}function renderList(e){const t=e.childNodes.filter(isElementNode).filter(e=>"li"===e.tagName.toLowerCase()).map(e=>renderListItem(e)).join("\n"),r=e.parentNode;return r.tagName&&"li"===r.tagName.toLowerCase()&&r.lastElementChild===e?"\n"+t:"\n\n"+t+"\n\n"}function renderListItem(e){const t=renderListItemChildren(e,renderAttributes(e)).replace(/^\n+/,"").replace(/\n+$/,"\n"),r=countPreviousSiblingElements(e),n="ol"===e.parentNode.tagName.toLowerCase()?`${r+1}.`:"-",i=t.split("\n"),s=`${n} ${i[0]}`,o=" ".repeat(n.length+1)
1160
+ ;return[s,...i.slice(1).map(e=>e.trimStart()?`${o}${e}`:"")].join("\n")}function renderListItemChildren(e,t){let r="",n=!1,i=0;for(const s of e.childNodes){const o=e.childNodes[i+1];let a=renderNode(s);!t||n||o&&!isBlockElement(o)||(n=!0,a+=a?t:t.trim()),r=isBlockElement(s)?appendBlockElementToBuffer(r,a):appendInlineElementToBuffer(r,a),i++}return trimLeadingNewlines(r)}function renderAttributes(e,t){const r=e.getAttribute("id");let n=_optionalChain$13([e,"access",e=>e.getAttribute,"call",e=>e("class"),"optionalAccess",e=>e.split,"call",e=>e(/\s+/),"access",e=>e.filter,"call",e=>e(Boolean)])||[];_optionalChain$13([t,"optionalAccess",e=>e.ignoreLanguageClass])&&(n=n.filter(e=>!e.startsWith("language-")));const i=[];return r&&i.push(`#${r}`),i.push(...n.map(e=>`.${e}`)),0===i.length?"":_optionalChain$13([t,"optionalAccess",e=>e.hang])?`\n \n{ ${i.join(" ")} }`:` { ${i.join(" ")} }`}
1161
1161
  const blockTags=["h1","h2","h3","h4","h5","h6","p","pre","blockquote","ul","ol","li","div","span"],blockTagsSet=new Set(blockTags),isBlockElement=e=>isElementNode(e)&&blockTagsSet.has(e.tagName.toLowerCase());function countPreviousSiblingElements(e){let t=0,r=e.previousElementSibling;for(;r;)t++,r=r.previousElementSibling;return t}const ensureTrailingNewline=e=>e.endsWith("\n")?e:e+"\n",ensureLeadingNewLine=e=>e.startsWith("\n")?e:"\n"+e,trimTrailingNewlines=e=>{let t=e.length;for(;t>0&&10===e.charCodeAt(t-1);)t--;return t===e.length?e:e.slice(0,t)},trimLeadingNewlines=e=>{let t=0;for(;t<e.length&&10===e.charCodeAt(t);)t++;return 0===t?e:e.slice(t)};function appendInlineElementToBuffer(e,t){return t?(!e||e.endsWith("\n")||"\n"===t?e+=t:e+=` ${t}`,e):e}function appendBlockElementToBuffer(e,t){if(!t)return e;const r=trimTrailingNewlines(e),n=trimLeadingNewlines(t),i=e.length-r.length,s=t.length-n.length,o=Math.max(i,s);return r+(o>=2?"\n\n":1===o?"\n":"")+n}const decodeCache={}
1162
1162
  ;function getDecodeCache(e){let t=decodeCache[e];if(t)return t;t=decodeCache[e]=[];for(let e=0;e<128;e++){const r=String.fromCharCode(e);t.push(r)}for(let r=0;r<e.length;r++){const n=e.charCodeAt(r);t[n]="%"+("0"+n.toString(16).toUpperCase()).slice(-2)}return t}function decode$1(e,t){"string"!=typeof t&&(t=decode$1.defaultChars);const r=getDecodeCache(t);return e.replace(/(%[a-f0-9]{2})+/gi,function(e){let t="";for(let n=0,i=e.length;n<i;n+=3){const s=parseInt(e.slice(n+1,n+3),16);if(s<128)t+=r[s];else{if(192==(224&s)&&n+3<i){const r=parseInt(e.slice(n+4,n+6),16);if(128==(192&r)){const e=s<<6&1984|63&r;t+=e<128?"��":String.fromCharCode(e),n+=3;continue}}if(224==(240&s)&&n+6<i){const r=parseInt(e.slice(n+4,n+6),16),i=parseInt(e.slice(n+7,n+9),16);if(128==(192&r)&&128==(192&i)){const e=s<<12&61440|r<<6&4032|63&i;t+=e<2048||e>=55296&&e<=57343?"���":String.fromCharCode(e),n+=6;continue}}if(240==(248&s)&&n+9<i){
1163
1163
  const r=parseInt(e.slice(n+4,n+6),16),i=parseInt(e.slice(n+7,n+9),16),o=parseInt(e.slice(n+10,n+12),16);if(128==(192&r)&&128==(192&i)&&128==(192&o)){let e=s<<18&1835008|r<<12&258048|i<<6&4032|63&o;e<65536||e>1114111?t+="����":(e-=65536,t+=String.fromCharCode(55296+(e>>10),56320+(1023&e))),n+=9;continue}}t+="�"}}return t})}decode$1.defaultChars=";/?:@&=+$,#",decode$1.componentChars="";const encodeCache={};function getEncodeCache(e){let t=encodeCache[e];if(t)return t;t=encodeCache[e]=[];for(let e=0;e<128;e++){const r=String.fromCharCode(e);/^[0-9a-z]$/i.test(r)?t.push(r):t.push("%"+("0"+e.toString(16).toUpperCase()).slice(-2))}for(let r=0;r<e.length;r++)t[e.charCodeAt(r)]=e[r];return t}function encode$2(e,t,r){"string"!=typeof t&&(r=t,t=encode$2.defaultChars),void 0===r&&(r=!0);const n=getEncodeCache(t);let i="";for(let t=0,s=e.length;t<s;t++){const o=e.charCodeAt(t);if(r&&37===o&&t+2<s&&/^[0-9a-f]{2}$/i.test(e.slice(t+1,t+3)))i+=e.slice(t,t+3),
@@ -1256,30 +1256,30 @@ position:-2,type:"softbreak"},{position:-1,type:"text",content:e.hasDelimiters("
1256
1256
  switch(typeof o[e]){case"boolean":case"number":case"string":if(u[e]!==o[e])return a;break;case"function":if(!o[e](u[e]))return a;break;case"object":if(i(o[e])){if(!1===o[e].every(t=>t(u[e])))return a;break}default:throw new Error(`Unknown type of pattern test (key: ${e}). Test should be of type boolean, number, string, function or array of functions.`)}}return a.match=!0,a}function n(e){return Array.isArray(e)&&e.length&&e.every(e=>"object"==typeof e)}function i(e){return Array.isArray(e)&&e.length&&e.every(e=>"function"==typeof e)}function s(e){return e.slice(-1)[0]||{}}return markdownItAttrs$1=function(n,i){let s=Object.assign({},t);s=Object.assign(s,i);const o=e(s);n.core.ruler.before("linkify","curly_attributes",function(e){const t=e.tokens;for(let e=0;e<t.length;e++)for(let n=0;n<o.length;n++){const i=o[n];let s=null;if(i.tests.every(n=>{const i=r(t,e,n);return null!==i.j&&(s=i.j),i.match}))try{i.transform(t,e,s),"inline attributes"!==i.name&&"inline nesting 0"!==i.name||n--
1257
1257
  }catch(e){console.error(`markdown-it-attrs: Error in pattern '${i.name}': ${e.message}`),console.error(e.stack)}}})},markdownItAttrs$1}var markdownItAttrsExports=requireMarkdownItAttrs(),markdownItAttrs=getDefaultExportFromCjs(markdownItAttrsExports),markdownItTaskCheckbox,hasRequiredMarkdownItTaskCheckbox;function requireMarkdownItTaskCheckbox(){if(hasRequiredMarkdownItTaskCheckbox)return markdownItTaskCheckbox;function e(e,t,r){var n=e.attrIndex(t),i=[t,r];n<0?e.attrPush(i):e.attrs[n]=i}function t(e,t){for(var r=e[t].level-1,n=t-1;n>=0;n--)if(e[n].level===r)return n;return-1}function r(e,t){return"inline"===e[t].type&&function(e){return"paragraph_open"===e.type}(e[t-1])&&function(e){return"list_item_open"===e.type}(e[t-2])&&function(e){return/^\[[xX \u00A0]\][ \u00A0]/.test(e.content)}(e[t])}function n(e,t,r,n){var i;i=r.idPrefix+t,e.children[0].content=e.children[0].content.slice(3),e.children.unshift(function(e,t){var r=new t("label_open","label",1);return r.attrs=[["for",e]],r
1258
1258
  }(i,n)),e.children.push(function(e){return new e("label_close","label",-1)}(n)),e.children.unshift(function(e,t,r,n){var i=new n("checkbox_input","input",0);i.attrs=[["type","checkbox"],["id",t]];var s=/^\[[xX]\][ \u00A0]/.test(e.content);!0===s&&i.attrs.push(["checked","true"]);!0===r.disabled&&i.attrs.push(["disabled","true"]);return i}(e,i,r,n)),r.divWrap&&(e.children.unshift(function(e,t){var r=new t("checkbox_open","div",0);return r.attrs=[["class",e.divClass]],r}(r,n)),e.children.push(function(e){var t=new e("checkbox_close","div",-1);return t}(n)))}return hasRequiredMarkdownItTaskCheckbox=1,markdownItTaskCheckbox=function(i,s){var o;o={disabled:!0,divWrap:!1,divClass:"checkbox",idPrefix:"cbx_",ulClass:"task-list",liClass:"task-list-item"},s=Object.assign({},o,s),i.core.ruler.after("inline","github-task-lists",function(i){for(var o=i.tokens,a=0,c=2;c<o.length;c++)r(o,c)&&(n(o[c],a,s,i.Token),a+=1,e(o[c-2],"class",s.liClass),e(o[t(o,c-2)],"class",s.ulClass))})},
1259
- markdownItTaskCheckbox}var markdownItTaskCheckboxExports=requireMarkdownItTaskCheckbox(),mic=getDefaultExportFromCjs(markdownItTaskCheckboxExports);function _nullishCoalesce$W(e,t){return null!=e?e:t()}function _optionalChain$13(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const mdi=new MarkdownIt({breaks:!0}).use(markdownItAttrs,{allowedAttributes:["id","class"]}).use(mic,{ulClass:"",liClass:""}),renderTokenOriginal=mdi.renderer.renderToken.bind(mdi.renderer);function markdownToHtml(e){return mdi.render(e)}function _nullishCoalesce$V(e,t){return null!=e?e:t()}function _optionalChain$12(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,
1260
- r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}mdi.renderer.renderToken=(e,t,r)=>{const n=e[t];if(n.map&&1===n.nesting){const[e,t]=n.map;n.attrSet("data-source-lines",`${e+1}-${t}`)}return renderTokenOriginal(e,t,r)},mdi.renderer.rules.fence=(e,t,r,n,i)=>{const s=e[t],[o,a]=_nullishCoalesce$W(_optionalChain$13([s,"optionalAccess",e=>e.map]),()=>[0,0]),c=s.info.trim().split(/\s+/)[0],u=`data-source-lines="${o+1}-${a}"`,l=[c?`language-${c}`:"",s.attrGet("class")||""].filter(Boolean).join(" ");l&&s.attrSet("class",l);return`<pre><code ${u}${i.renderAttrs(s)}>${s.content}</code></pre>\n`};const SPEC_FILE_EXTENSION=".spec.md",SPECIAL_LINK_TEXTS=["@describes","@describe","@generate","@generates","@satisfied-by","@use","@test"];function specFromMarkdown(e){return specFromDom(parseHtml(markdownToHtml(e)))}function specFromDom(e){const t=createSections(e);return decorateTestLinks(t),decorateTests(t),decorateUseLinks(t),decorateGenerateLinks(t),
1259
+ markdownItTaskCheckbox}var markdownItTaskCheckboxExports=requireMarkdownItTaskCheckbox(),mic=getDefaultExportFromCjs(markdownItTaskCheckboxExports);function _nullishCoalesce$W(e,t){return null!=e?e:t()}function _optionalChain$12(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const mdi=new MarkdownIt({breaks:!0}).use(markdownItAttrs,{allowedAttributes:["id","class"]}).use(mic,{ulClass:"",liClass:""}),renderTokenOriginal=mdi.renderer.renderToken.bind(mdi.renderer);function markdownToHtml(e){return mdi.render(e)}function _nullishCoalesce$V(e,t){return null!=e?e:t()}function _optionalChain$11(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,
1260
+ r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}mdi.renderer.renderToken=(e,t,r)=>{const n=e[t];if(n.map&&1===n.nesting){const[e,t]=n.map;n.attrSet("data-source-lines",`${e+1}-${t}`)}return renderTokenOriginal(e,t,r)},mdi.renderer.rules.fence=(e,t,r,n,i)=>{const s=e[t],[o,a]=_nullishCoalesce$W(_optionalChain$12([s,"optionalAccess",e=>e.map]),()=>[0,0]),c=s.info.trim().split(/\s+/)[0],u=`data-source-lines="${o+1}-${a}"`,l=[c?`language-${c}`:"",s.attrGet("class")||""].filter(Boolean).join(" ");l&&s.attrSet("class",l);return`<pre><code ${u}${i.renderAttrs(s)}>${s.content}</code></pre>\n`};const SPEC_FILE_EXTENSION=".spec.md",SPECIAL_LINK_TEXTS=["@describes","@describe","@generate","@generates","@satisfied-by","@use","@test"];function specFromMarkdown(e){return specFromDom(parseHtml(markdownToHtml(e)))}function specFromDom(e){const t=createSections(e);return decorateTestLinks(t),decorateTests(t),decorateUseLinks(t),decorateGenerateLinks(t),
1261
1261
  decorateDescribeLinks(t),t}function decorateTestLinks(e){for(const t of e.querySelectorAll("a"))"@test"===t.text&&t.classList.add("test")}function isDeprecatedDepUsageLink(e){return"a"===e.tagName.toLowerCase()&&"@satisfied-by"===e.text}function decorateUseLinks(e){for(const t of e.querySelectorAll("a"))("@use"===t.text||isDeprecatedDepUsageLink(t))&&t.classList.add("use")}function isDeprecatedGenerateLink(e){return"a"===e.tagName.toLowerCase()&&"@generates"===e.text}function decorateGenerateLinks(e){for(const t of e.querySelectorAll("a"))("@generate"===t.text||isDeprecatedGenerateLink(t))&&t.classList.add("generate")}function isDeprecatedDescribeLink(e){return"a"===e.tagName.toLowerCase()&&"@describes"===e.text}function decorateDescribeLinks(e){for(const t of e.querySelectorAll("a"))("@describe"===t.text||isDeprecatedDescribeLink(t))&&t.classList.add("describe")}function decorateTests(e){
1262
- for(const t of e.querySelectorAll("a.test"))_optionalChain$12([findParent,"call",e=>e(t,["LI"],["UL","OL"]),"optionalAccess",e=>e.classList,"access",e=>e.add,"call",e=>e("test")]);for(const t of e.querySelectorAll(".locked,.impl")){const e=t.classList.contains("locked"),r=t.classList.contains("impl");t.querySelectorAll("a.test").forEach(t=>{e&&t.classList.add("locked"),r&&t.classList.add("impl")})}for(const t of e.querySelectorAll("a.test:not(.locked):not(.impl)"))t.classList.add("draft")}function getApi(e){const t=e.querySelectorAll("code.api");if(0===t.length)throw new Error("Api not found");return t.map(e=>e.innerHTML)}function findApi(e){try{return getApi(e)}catch(e){return[]}}function getUsePaths(e){const t=e.querySelectorAll(".use").map(e=>{if(!_optionalChain$12([e,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()]))throw new Error("The @use link is empty")
1263
- ;return _optionalChain$12([e,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])});if(new Set(t).size!==t.length)throw new Error("Duplicate @use links found");return t}function findGeneratePaths(e){return e.querySelectorAll(".generate").reduce((e,t)=>(_optionalChain$12([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])&&e.push(_optionalChain$12([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])),e),[])}function findDescribePaths(e){return e.querySelectorAll(".describe").reduce((e,t)=>(_optionalChain$12([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])&&e.push(_optionalChain$12([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])),e),[])}function findImplementationPaths(e){return{describe:findDescribePaths(e),generate:findGeneratePaths(e)}}function findTests(e){const t=[]
1262
+ for(const t of e.querySelectorAll("a.test"))_optionalChain$11([findParent,"call",e=>e(t,["LI"],["UL","OL"]),"optionalAccess",e=>e.classList,"access",e=>e.add,"call",e=>e("test")]);for(const t of e.querySelectorAll(".locked,.impl")){const e=t.classList.contains("locked"),r=t.classList.contains("impl");t.querySelectorAll("a.test").forEach(t=>{e&&t.classList.add("locked"),r&&t.classList.add("impl")})}for(const t of e.querySelectorAll("a.test:not(.locked):not(.impl)"))t.classList.add("draft")}function getApi(e){const t=e.querySelectorAll("code.api");if(0===t.length)throw new Error("Api not found");return t.map(e=>e.innerHTML)}function findApi(e){try{return getApi(e)}catch(e){return[]}}function getUsePaths(e){const t=e.querySelectorAll(".use").map(e=>{if(!_optionalChain$11([e,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()]))throw new Error("The @use link is empty")
1263
+ ;return _optionalChain$11([e,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])});if(new Set(t).size!==t.length)throw new Error("Duplicate @use links found");return t}function findGeneratePaths(e){return e.querySelectorAll(".generate").reduce((e,t)=>(_optionalChain$11([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])&&e.push(_optionalChain$11([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])),e),[])}function findDescribePaths(e){return e.querySelectorAll(".describe").reduce((e,t)=>(_optionalChain$11([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])&&e.push(_optionalChain$11([t,"access",e=>e.attributes,"access",e=>e.href,"optionalAccess",e=>e.toString,"call",e=>e()])),e),[])}function findImplementationPaths(e){return{describe:findDescribePaths(e),generate:findGeneratePaths(e)}}function findTests(e){const t=[]
1264
1264
  ;for(const r of e.querySelectorAll("a.test")){const e={path:r.attributes.href&&"#"!==r.attributes.href?r.attributes.href:"",sourceLines:findSourceLines(r),kind:testElementKind(r)};t.push(e)}return t}function findSourceLines(e){let t=e;for(;null!==t;){if("data-source-lines"in t.attributes)return t.attributes["data-source-lines"];t=t.parentNode}}function testElementKind(e){if(e.classList.contains("locked"))return"locked";if(e.classList.contains("impl"))return"impl";if(e.classList.contains("draft"))return"draft";throw new Error(`Unknown test kind for element: ${e.outerHTML}`)}function findTestPaths(e,t){let r=findTests(e);return t&&(r=r.filter(e=>e.kind===t)),r.map(e=>e.path)}function findTest(e,t){const r=findTests(e).find(e=>e.path===t);if(!r)throw new Error(`Test not found: ${t}`);return r}function findParentSection(e,t){return _nullishCoalesce$V(e.closest(`.${t}`),()=>{})}function findAllLinks(e){const t=[];for(const r of e.querySelectorAll("a[href]")){
1265
- const e=_optionalChain$12([r,"access",e=>e.textContent,"optionalAccess",e=>e.trim,"call",e=>e()]),n=_optionalChain$12([r,"access",e=>e.getAttribute,"call",e=>e("href"),"optionalAccess",e=>e.trim,"call",e=>e()]);e&&n&&(n.startsWith("#")||t.push({text:e,href:n}))}return t}function findRegularLinks(e){return findAllLinks(e).filter(e=>!SPECIAL_LINK_TEXTS.includes(e.text))}function pluralize$1(e,t){if(1===t)return e;const r=new Set(["fish"]),n=e.toLowerCase();if(r.has(n))return e;const i={child:"children",person:"people",mouse:"mice"}[n];return void 0!==i?i:n.endsWith("y")&&n.length>1&&!/[aeiou]/.test(n.charAt(n.length-2))?e.slice(0,-1)+"ies":n.endsWith("ch")||n.endsWith("sh")||["s","x","z"].some(e=>n.endsWith(e))?e+"es":n.endsWith("fe")?e.slice(0,-2)+"ves":n.endsWith("f")?e.slice(0,-1)+"ves":e+"s"}function stripSurroundingQuotes(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}
1265
+ const e=_optionalChain$11([r,"access",e=>e.textContent,"optionalAccess",e=>e.trim,"call",e=>e()]),n=_optionalChain$11([r,"access",e=>e.getAttribute,"call",e=>e("href"),"optionalAccess",e=>e.trim,"call",e=>e()]);e&&n&&(n.startsWith("#")||t.push({text:e,href:n}))}return t}function findRegularLinks(e){return findAllLinks(e).filter(e=>!SPECIAL_LINK_TEXTS.includes(e.text))}function pluralize$1(e,t){if(1===t)return e;const r=new Set(["fish"]),n=e.toLowerCase();if(r.has(n))return e;const i={child:"children",person:"people",mouse:"mice"}[n];return void 0!==i?i:n.endsWith("y")&&n.length>1&&!/[aeiou]/.test(n.charAt(n.length-2))?e.slice(0,-1)+"ies":n.endsWith("ch")||n.endsWith("sh")||["s","x","z"].some(e=>n.endsWith(e))?e+"es":n.endsWith("fe")?e.slice(0,-2)+"ves":n.endsWith("f")?e.slice(0,-1)+"ves":e+"s"}function stripSurroundingQuotes(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}
1266
1266
  const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(e=>[e.name,e]),errorConstructors=new Map(list);class NonError extends Error{name="NonError";constructor(e){super(NonError._prepareSuperMessage(e))}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=e=>{toJsonWasCalled.add(e);const t=e.toJSON();return toJsonWasCalled.delete(e),t},newError=e=>{const t=errorConstructors.get(e)??Error;return t===AggregateError?new t([]):new t},destroyCircular=({from:e,seen:t,to:r,forceEnumerable:n,maxDepth:i,depth:s,useToJSON:o,serialize:a})=>{
1267
1267
  if(r||(r=Array.isArray(e)?[]:!a&&isErrorLike(e)?newError(e.name):{}),t.push(e),s>=i)return r;if(o&&"function"==typeof e.toJSON&&!toJsonWasCalled.has(e))return toJSON(e);const c=e=>destroyCircular({from:e,seen:[...t],forceEnumerable:n,maxDepth:i,depth:s,useToJSON:o,serialize:a});for(const[n,i]of Object.entries(e))if(i&&i instanceof Uint8Array&&"Buffer"===i.constructor.name)r[n]="[object Buffer]";else if(null===i||"object"!=typeof i||"function"!=typeof i.pipe){if("function"!=typeof i)if(i&&"object"==typeof i)t.includes(e[n])?r[n]="[Circular]":(s++,r[n]=c(e[n]));else try{r[n]=i}catch{}}else r[n]="[object Stream]";if(a||r instanceof Error)for(const{property:t,enumerable:i}of errorProperties)void 0!==e[t]&&null!==e[t]&&Object.defineProperty(r,t,{value:isErrorLike(e[t])||Array.isArray(e[t])?c(e[t]):e[t],enumerable:!!n||i,configurable:!0,writable:!0});return r};function serializeError(e,t={}){const{maxDepth:r=Number.POSITIVE_INFINITY,useToJSON:n=!0}=t
1268
- ;return"object"==typeof e&&null!==e?destroyCircular({from:e,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e}function deserializeError(e,t={}){const{maxDepth:r=Number.POSITIVE_INFINITY}=t;return e instanceof Error?e:isMinimumViableSerializedError(e)?destroyCircular({from:e,seen:[],to:newError(e.name),maxDepth:r,depth:0,serialize:!1}):new NonError(e)}function isErrorLike(e){return Boolean(e)&&"object"==typeof e&&"string"==typeof e.name&&"string"==typeof e.message&&"string"==typeof e.stack}function isMinimumViableSerializedError(e){return Boolean(e)&&"object"==typeof e&&"string"==typeof e.message&&!Array.isArray(e)}function _optionalChain$11(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
1268
+ ;return"object"==typeof e&&null!==e?destroyCircular({from:e,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e}function deserializeError(e,t={}){const{maxDepth:r=Number.POSITIVE_INFINITY}=t;return e instanceof Error?e:isMinimumViableSerializedError(e)?destroyCircular({from:e,seen:[],to:newError(e.name),maxDepth:r,depth:0,serialize:!1}):new NonError(e)}function isErrorLike(e){return Boolean(e)&&"object"==typeof e&&"string"==typeof e.name&&"string"==typeof e.message&&"string"==typeof e.stack}function isMinimumViableSerializedError(e){return Boolean(e)&&"object"==typeof e&&"string"==typeof e.message&&!Array.isArray(e)}function _optionalChain$10(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
1269
1269
  function assertUnreachable(e){throw new Error(`Statement should be unreachable: ${JSON.stringify(e)}`)}const keysOf=Object.keys,entriesOf=Object.entries,fromEntries=Object.fromEntries;class UnrecognisedPropertiesError extends Error{constructor(e,t){super(`Unrecognised properties found: ${e.join(", ")}`),this.name="UnrecognisedPropertiesError",this.properties=e,this.value=t,Object.setPrototypeOf(this,new.target.prototype)}}function strictCheck(e,t){Check(e,t)||throwValidationError(e,t);const r=[...Errors(enforceNoAdditionalProps(e),t)].filter(e=>e.type===ValueErrorType.ObjectAdditionalProperties).map(e=>e.path.slice(1));if(r.length>0)throw new UnrecognisedPropertiesError(r,t);return!0}function enforceNoAdditionalProps(e){return recursivelyApply(e)}function recursivelyApply(e){switch(e.type){case"object":{const t=e.properties||{},r={};for(const e of Object.keys(t))r[e]=recursivelyApply(t[e]);return{...e,properties:r,additionalProperties:!1}}case"array":return{...e,
1270
- items:recursivelyApply(e.items)};case"union":return{...e,anyOf:e.anyOf.map(recursivelyApply)};case"intersect":return{...e,allOf:e.allOf.map(recursivelyApply)};default:return e}}function throwValidationError(e,t){const r=[...Errors(e,t)],n=r[0];throw new Error(`value does not match schema: ${r.length} errors, e.g. ${n.type}: ${n.message} @ ${n.path}: ${JSON.stringify(n.value)}`,{cause:r})}function extractValidationIssues(e){const t=new Map;if(e.cause&&Array.isArray(e.cause))for(const r of e.cause)if(r&&"object"==typeof r&&"path"in r){const e=r,n=e.path,i=("string"==typeof n?n:"number"==typeof n?String(n):null==n?"":JSON.stringify(n)).replace(/^\//,""),s=e.message,o="string"==typeof s?s:"Invalid value",a=_optionalChain$11([e.schema,"optionalAccess",e=>e.type]),c=e.value,u=i||"unknown",l=t.get(u),d=o.includes("Expected required property");l&&!d||t.set(u,{path:u,message:o,expectedType:a,actualValue:c})}return Array.from(t.values())}function formatValidationError(e){
1270
+ items:recursivelyApply(e.items)};case"union":return{...e,anyOf:e.anyOf.map(recursivelyApply)};case"intersect":return{...e,allOf:e.allOf.map(recursivelyApply)};default:return e}}function throwValidationError(e,t){const r=[...Errors(e,t)],n=r[0];throw new Error(`value does not match schema: ${r.length} errors, e.g. ${n.type}: ${n.message} @ ${n.path}: ${JSON.stringify(n.value)}`,{cause:r})}function extractValidationIssues(e){const t=new Map;if(e.cause&&Array.isArray(e.cause))for(const r of e.cause)if(r&&"object"==typeof r&&"path"in r){const e=r,n=e.path,i=("string"==typeof n?n:"number"==typeof n?String(n):null==n?"":JSON.stringify(n)).replace(/^\//,""),s=e.message,o="string"==typeof s?s:"Invalid value",a=_optionalChain$10([e.schema,"optionalAccess",e=>e.type]),c=e.value,u=i||"unknown",l=t.get(u),d=o.includes("Expected required property");l&&!d||t.set(u,{path:u,message:o,expectedType:a,actualValue:c})}return Array.from(t.values())}function formatValidationError(e){
1271
1271
  const t=extractValidationIssues(e);if(0===t.length)return"Error in environment configuration.\n\nValidation failed. Please check your environment variables.";const r=t.map(e=>{let t=`- ${e.path}`;return void 0===e.actualValue||null===e.actualValue?t+=": missing required variable":e.expectedType?t+=`: expected ${e.expectedType}, got ${typeof e.actualValue}`:t+=`: ${e.message}`,t}).join("\n");return`Error in environment configuration.\n\nMissing or invalid variables:\n${r}\n\nPlease update these variables in the file to continue.\nFor more information about setting up your environment, see the installation instructions.`}function deepFreeze(e){if(Object.freeze(e),!objectLike(e))return e;for(const t of Object.getOwnPropertyNames(e)){const r=e[t];Object.isFrozen(r)||deepFreeze(r)}return e}function objectLike(e){return"object"==typeof e&&null!==e}async function sleep$2(e){return new Promise(t=>setTimeout(t,e))}async function sleepWithAbort(e,t){return new Promise((r,n)=>{
1272
- if(_optionalChain$11([t,"optionalAccess",e=>e.aborted]))return void n(new Error("aborted"));const i=setTimeout(r,e);if(t){const e=()=>{clearTimeout(i),n(new Error("aborted"))};t.addEventListener("abort",e,{once:!0})}})}function throwWhenAborted(e){if(e.aborted)throw new Error("aborted")}function _pick(e,t){const r={};for(const n of t)r[n]=e[n];return r}const clock$2=()=>process.hrtime.bigint();function cerealiseError(e){return JSON.stringify(serializeError(e))}const UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function addError(e,t,r){return e instanceof AggregateError?new AggregateError([...e.errors,t],r):new AggregateError([e,t],r)}const reflectPromise=()=>{let e=()=>{},t=()=>{};return{promise:new Promise((r,n)=>{t=r,e=n}),resRej:{resolve:t,reject:e}}},UNKEYED_RECOGNIZED_LANGUAGES={c:{label:"C",extensions:[".c",".h"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"experimental",defaultTestFramework:"Unity",
1272
+ if(_optionalChain$10([t,"optionalAccess",e=>e.aborted]))return void n(new Error("aborted"));const i=setTimeout(r,e);if(t){const e=()=>{clearTimeout(i),n(new Error("aborted"))};t.addEventListener("abort",e,{once:!0})}})}function throwWhenAborted(e){if(e.aborted)throw new Error("aborted")}function _pick(e,t){const r={};for(const n of t)r[n]=e[n];return r}const clock$2=()=>process.hrtime.bigint();function cerealiseError(e){return JSON.stringify(serializeError(e))}const UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function addError(e,t,r){return e instanceof AggregateError?new AggregateError([...e.errors,t],r):new AggregateError([e,t],r)}const reflectPromise=()=>{let e=()=>{},t=()=>{};return{promise:new Promise((r,n)=>{t=r,e=n}),resRej:{resolve:t,reject:e}}},UNKEYED_RECOGNIZED_LANGUAGES={c:{label:"C",extensions:[".c",".h"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"experimental",defaultTestFramework:"Unity",
1273
1273
  defaultTestCommand:"unity-test-runner {files}"},cplusplus:{label:"C++",extensions:[".cpp",".cxx",".cc",".hpp",".hxx",".hh"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"none",defaultTestFramework:"Google Test",defaultTestCommand:"ctest --test-file {files}"},csharp:{label:"C#",extensions:[".cs"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"none",defaultTestFramework:"NUnit",defaultTestCommand:"dotnet test {files}"},css:{label:"CSS",extensions:[".css"],comments:{block:{start:"/*",end:"*/"}},supportLevel:"none"},dart:{label:"Dart",extensions:[".dart"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"none",defaultTestFramework:"test",defaultTestCommand:"dart test {files}"},go:{label:"Go",extensions:[".go"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"experimental",defaultTestFramework:"go test",defaultTestCommand:"go test ./..."},html:{label:"HTML",extensions:[".html",".htm"],comments:{block:{start:"\x3c!--",
1274
1274
  end:"--\x3e"}},supportLevel:"none"},java:{label:"Java",extensions:[".java"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"stable",defaultTestFramework:"JUnit",defaultTestCommand:"mvn test {maven-classes}"},javascript:{label:"JavaScript",extensions:[".js",".jsx",".mjs",".cjs"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"stable",defaultTestFramework:"Jest",defaultTestCommand:"npx jest {files}"},julia:{label:"Julia",extensions:[".jl"],comments:{single:"#",block:{start:"#=",end:"=#"}},supportLevel:"none",defaultTestFramework:"Test",defaultTestCommand:"julia --project -e 'using Pkg; Pkg.test(test_files=[\"{files}\"])'"},kotlin:{label:"Kotlin",extensions:[".kt",".kts"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"experimental",defaultTestFramework:"JUnit",defaultTestCommand:"./gradlew test --tests {files}"},lua:{label:"Lua",extensions:[".lua"],comments:{single:"--",block:{start:"--[[",end:"]]"}},supportLevel:"none",
1275
1275
  defaultTestFramework:"Busted",defaultTestCommand:"busted {files}"},php:{label:"PHP",extensions:[".php",".phtml",".php3",".php4",".php5"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"none",defaultTestFramework:"PHPUnit",defaultTestCommand:"phpunit {files}"},powershell:{label:"PowerShell",extensions:[".ps1",".psm1",".psd1"],comments:{single:"#",block:{start:"<#",end:"#>"}},supportLevel:"none",defaultTestFramework:"Pester",defaultTestCommand:"Invoke-Pester -Path {files}"},python:{label:"Python",extensions:[".py",".pyw",".pyi"],comments:{single:"#",block:{start:'"""',end:'"""'}},supportLevel:"stable",defaultTestFramework:"pytest",defaultTestCommand:"uv run python -m pytest {files}"},r:{label:"R",extensions:[".r",".R"],comments:{single:"#"},supportLevel:"none",defaultTestFramework:"testthat",defaultTestCommand:"Rscript -e \"testthat::test_file('{files}')\""},ruby:{label:"Ruby",extensions:[".rb",".rbw"],comments:{single:"#"},supportLevel:"experimental",
1276
1276
  defaultTestFramework:"RSpec",defaultTestCommand:"rspec {files}"},rust:{label:"Rust",extensions:[".rs"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"experimental",defaultTestFramework:"cargo test",defaultTestCommand:"cargo test -- {files}"},sass:{label:"Sass",extensions:[".scss",".sass"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"none"},scala:{label:"Scala",extensions:[".scala",".sc"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"experimental",defaultTestFramework:"ScalaTest",defaultTestCommand:'sbt "testOnly {files}"'},shell:{label:"Shell",extensions:[".sh",".bash",".zsh",".fish"],comments:{single:"#"},supportLevel:"none"},sql:{label:"SQL",extensions:[".sql"],comments:{single:"--",block:{start:"/*",end:"*/"}},supportLevel:"none"},swift:{label:"Swift",extensions:[".swift"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"experimental",defaultTestFramework:"XCTest",
1277
1277
  defaultTestCommand:"swift test --filter {files}"},toml:{label:"TOML",extensions:[".toml"],comments:{single:"#"},supportLevel:"none"},typescript:{label:"TypeScript",extensions:[".ts",".tsx",".cts",".mts"],comments:{single:"//",block:{start:"/*",end:"*/"}},supportLevel:"stable",defaultTestFramework:"Vitest",defaultTestCommand:"npx vitest run {files}"},xml:{label:"XML",extensions:[".xml"],comments:{block:{start:"\x3c!--",end:"--\x3e"}},supportLevel:"none"},yaml:{label:"YAML",extensions:[".yml",".yaml"],comments:{single:"#"},supportLevel:"none"}},RECOGNIZED_LANGUAGES=Object.entries(UNKEYED_RECOGNIZED_LANGUAGES).reduce((e,[t,r])=>({...e,[t]:{key:t,...r}}),{});function isStableLanguage(e){return"stable"===e.supportLevel}function isExperimentalLanguage(e){return"experimental"===e.supportLevel}const STABLE_TILE_LANGUAGES=Object.values(RECOGNIZED_LANGUAGES).filter(isStableLanguage);STABLE_TILE_LANGUAGES.map(e=>e.key)
1278
- ;const EXPERIMENTAL_TILE_LANGUAGES=Object.values(RECOGNIZED_LANGUAGES).filter(isExperimentalLanguage);EXPERIMENTAL_TILE_LANGUAGES.map(e=>e.key);const TILE_LANGUAGES=Object.values(RECOGNIZED_LANGUAGES).filter(e=>isStableLanguage(e)||isExperimentalLanguage(e)),TILE_LANGUAGE_KEYS=TILE_LANGUAGES.map(e=>e.key),EXTENSION_TO_LANGUAGE_MAP=Object.values(RECOGNIZED_LANGUAGES).reduce((e,t)=>(t.extensions.forEach(r=>{e.set(r.toLowerCase(),t)}),e),new Map);function detectLanguage(e){const t=path__default.extname(e).toLowerCase();return EXTENSION_TO_LANGUAGE_MAP.get(t)}function isRecognizedLanguage(e){return e in RECOGNIZED_LANGUAGES}function _optionalChain$10(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function calculateSpecHash(e){
1278
+ ;const EXPERIMENTAL_TILE_LANGUAGES=Object.values(RECOGNIZED_LANGUAGES).filter(isExperimentalLanguage);EXPERIMENTAL_TILE_LANGUAGES.map(e=>e.key);const TILE_LANGUAGES=Object.values(RECOGNIZED_LANGUAGES).filter(e=>isStableLanguage(e)||isExperimentalLanguage(e)),TILE_LANGUAGE_KEYS=TILE_LANGUAGES.map(e=>e.key),EXTENSION_TO_LANGUAGE_MAP=Object.values(RECOGNIZED_LANGUAGES).reduce((e,t)=>(t.extensions.forEach(r=>{e.set(r.toLowerCase(),t)}),e),new Map);function detectLanguage(e){const t=path__default.extname(e).toLowerCase();return EXTENSION_TO_LANGUAGE_MAP.get(t)}function isRecognizedLanguage(e){return e in RECOGNIZED_LANGUAGES}function _optionalChain$$(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function calculateSpecHash(e){
1279
1279
  return createHash("sha256").update(e).digest("hex").substring(0,8)}
1280
1280
  const VERSION_PATTERN=".*",FILE_PATH_PATTERN=".*",HASH_TAG_PATTERN="\\((?:spec|code):[a-f0-9]{8}\\)",TIMESTAMP_PATTERN="\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z",COMMENT_PREFIX="\\s*(//|#|--)",MULTI_LINE_CODE_TAG=["GENERATED FROM SPEC - DO NOT EDIT\\s*",`@generated with Tessl ${VERSION_PATTERN} from ${FILE_PATH_PATTERN}(?:\\s*`,`(?: ?${HASH_TAG_PATTERN}){0,2}(?: at ${TIMESTAMP_PATTERN})?)?`].map(e=>`\\s*${COMMENT_PREFIX} ${e}`).join("\\n"),SINGLE_LINE_CODE_TAG=`${COMMENT_PREFIX} @generated with Tessl ${VERSION_PATTERN} from ${FILE_PATH_PATTERN}\\s*(?: ${HASH_TAG_PATTERN}){0,2}\\s*(?: at ${TIMESTAMP_PATTERN})?`,XML_CODE_TAG=["\x3c!--\\s*GENERATED FROM SPEC - DO NOT EDIT\\s*--\x3e",`\x3c!--\\s*@generated with Tessl ${VERSION_PATTERN} from ${FILE_PATH_PATTERN}\\s*--\x3e(?:`,`\x3c!--\\s*(?: ${HASH_TAG_PATTERN}){0,2}(?: at ${TIMESTAMP_PATTERN})?\\s*--\x3e)?`].join("\\s*\\n\\s*"),CODE_TAG_REGEX=new RegExp(`^(${MULTI_LINE_CODE_TAG}|${SINGLE_LINE_CODE_TAG}|${XML_CODE_TAG})$`,"m")
1281
1281
  ;function extractCodeTag(e){return e.match(CODE_TAG_REGEX)}function calculateCodeHash(e){const t=removeGeneratedCodeTag(e).trim();return createHash("md5").update(t).digest("hex").substring(0,8)}function removeGeneratedCodeTag(e){const t=e.match(CODE_TAG_REGEX);if(t){let r=e.replace(t[0],"");return r=r.trim(),r}return e}function addOrReplaceGeneratedCodeComment(e,t,r,n){const{version:i}=getSysinfo(),s="unknown"===i?"(local)":i,o={spec:r?calculateSpecHash(r):void 0,code:calculateCodeHash(e)},a=detectLanguage(n||t);if(!a)return e;const c=extractCodeTag(e),u=["GENERATED FROM SPEC - DO NOT EDIT",`@generated with Tessl ${s} from ${t}`];let l;if(u.push(Object.entries(o).filter(([,e])=>e).map(([e,t])=>`(${e}:${t})`).join(" ")),"html"===a.key||"xml"===a.key)l=u.map(e=>`\x3c!-- ${e} --\x3e`).join("\n");else{if(!a.comments.single)return e;{const e=a.comments.single;l=u.map(t=>`${e} ${t}`).join("\n")}}
1282
- if(l!==_optionalChain$10([extractCodeTag,"call",e=>e(l),"optionalAccess",e=>e[0]]))throw new Error(`Generated comment does not match the expected format: ${l}`);return c?e.replace(c[0],l):l+"\n\n"+e}function extractSpecHash(e){return _optionalChain$10([e.match(/\(spec:([a-f0-9]{8})\)/),"optionalAccess",e=>e[1]])}function extractCodeHash(e){return _optionalChain$10([e.match(/\(code:([a-f0-9]{8})\)/),"optionalAccess",e=>e[1]])}function isCodeFileDirty(e){const t=extractCodeHash(e);if(!t)return!1;return t!==calculateCodeHash(e)}function getCodeStatus(e,t){if(!t)return"missing";const r=isCodeFileDirty(t),n=extractSpecHash(t)!==e;return r&&n?"dirty-outdated":r?"dirty-up-to-date":n?"outdated":"up-to-date"}var GenerateOption;!function(e){e.never="never";e.missing="missing";e.outdated="outdated";e.dirty="dirty";e.always="always"}(GenerateOption||(GenerateOption={}));const common$2={
1282
+ if(l!==_optionalChain$$([extractCodeTag,"call",e=>e(l),"optionalAccess",e=>e[0]]))throw new Error(`Generated comment does not match the expected format: ${l}`);return c?e.replace(c[0],l):l+"\n\n"+e}function extractSpecHash(e){return _optionalChain$$([e.match(/\(spec:([a-f0-9]{8})\)/),"optionalAccess",e=>e[1]])}function extractCodeHash(e){return _optionalChain$$([e.match(/\(code:([a-f0-9]{8})\)/),"optionalAccess",e=>e[1]])}function isCodeFileDirty(e){const t=extractCodeHash(e);if(!t)return!1;return t!==calculateCodeHash(e)}function getCodeStatus(e,t){if(!t)return"missing";const r=isCodeFileDirty(t),n=extractSpecHash(t)!==e;return r&&n?"dirty-outdated":r?"dirty-up-to-date":n?"outdated":"up-to-date"}var GenerateOption;!function(e){e.never="never";e.missing="missing";e.outdated="outdated";e.dirty="dirty";e.always="always"}(GenerateOption||(GenerateOption={}));const common$2={
1283
1283
  generate:()=>z.array(z.nativeEnum(GenerateOption)).transform(e=>Array.from(new Set(e))).refine(e=>!e.includes(GenerateOption.never)||1===e.length,{message:"'never' cannot be combined with other options"}).describe("Control which files to generate: 'never' skips generating files, 'missing' generates files that did not exist, 'outdated' generates files when the spec has changed but the code file remains unmodified, 'dirty' generates files which were manually modified since the last time we generated them, 'always' generates the files regardless of their current state. You can provide multiple options, e.g. ['missing', 'outdated'] to combine the behaviors.")},DIRTY_STATUSES=["dirty-outdated","dirty-up-to-date"];async function checkShouldUpdate({specPath:e,specHash:t,fsd:r,generate:n,generatedFilePath:i}){let s;if(t)s=t;else{const t=await r.readText(e);if(!t)throw new Error(`Spec file not found: ${e}`);s=calculateSpecHash(t)}const o=getCodeStatus(s,await r.readText(i))
1284
1284
  ;for(const e of n)switch(e){case GenerateOption.never:return!1;case GenerateOption.always:return!0;case GenerateOption.missing:case GenerateOption.outdated:if(e.toString()===o)return!0;break;case GenerateOption.dirty:if(DIRTY_STATUSES.includes(o))return!0;break;default:assertUnreachable(e)}return!1}function findTestsConsidering({generateDraftTests:e,generateLockedTests:t,generateImplTests:r}){const n={draft:e,locked:t,impl:r},i=Object.fromEntries(Object.entries(n).map(([e,t])=>{return[e,(r=t,r.length>0&&!r.some(e=>e===GenerateOption.never))];var r}));return e=>findTests(e).filter(e=>i[e.kind])}function chainImportResolvers(e){return{async resolve(t){for(const r of e){const e=await r.resolve(t);if(e)return e}}}}async function readRootSpec(e,t=!1){if(!await e.isInstalled()){if(!t)throw new Error(`attempting to read root spec from '${e.displayName}', but it does not appear to be installed; please negotiate with the package manager to install it`);return}
1285
1285
  const r=await e.openFsd(),n=await readPackageTileManifest(r);if(n)return await r.readText(n.spec);if(!t)throw new Error(`attempting to read root spec from '${e.displayName}', but it does not appear to have a spec`)}async function readPackageTileManifest(e){const t=await e.readText(WELL_KNOWN_PACKAGE_TILE_MANIFEST_FILENAME);return t?parsePackageTileManifest(t):void 0}function isExternalDependency(e){return!(e.startsWith("./")||e.startsWith("../"))}const dangerousBidiChars=["؜","‎","‏","‪","‫","‬","‭","‮","⁦","⁧","⁨","⁩"],invisibleChars=[{char:"­",code:"U+00AD",name:"SOFT HYPHEN"},{char:"͏",code:"U+034F",name:"COMBINING GRAPHEME JOINER"},{char:"؜",code:"U+061C",name:"ARABIC LETTER MARK"},{char:"ᅟ",code:"U+115F",name:"HANGUL CHOSEONG FILLER"},{char:"ᅠ",code:"U+1160",name:"HANGUL JUNGSEONG FILLER"},{char:"឴",code:"U+17B4",name:"KHMER VOWEL INHERENT AQ"},{char:"឵",code:"U+17B5",name:"KHMER VOWEL INHERENT AA"},{char:"᠎",code:"U+180E",name:"MONGOLIAN VOWEL SEPARATOR"},{char:"​",code:"U+200B",
@@ -1358,11 +1358,11 @@ r[t++]=serializeEdge(this.type,n,e)}),{options:{type:this.type,multi:this.multi,
1358
1358
  ;for(;n=r.next(),!0!==n.done;)i=n.value,addEdge(t,"copy",!1,i.undirected,i.key,i.source.key,i.target.key,assign({},i.attributes));return t}toJSON(){return this.export()}toString(){return"[object Graph]"}inspect(){const e={};this._nodes.forEach((t,r)=>{e[r]=t.attributes});const t={},r={};this._edges.forEach((e,n)=>{const i=e.undirected?"--":"->";let s,o="",a=e.source.key,c=e.target.key;e.undirected&&a>c&&(s=a,a=c,c=s);const u=`(${a})${i}(${c})`;n.startsWith("geid_")?this.multi&&(void 0===r[u]?r[u]=0:r[u]++,o+=`${r[u]}. `):o+=`[${n}]: `,o+=u,t[o]=e.attributes});const n={};for(const e in this)this.hasOwnProperty(e)&&!EMITTER_PROPS.has(e)&&"function"!=typeof this[e]&&"symbol"!=typeof e&&(n[e]=this[e]);return n.attributes=this._attributes,n.nodes=e,n.edges=t,privateProperty(n,"constructor",this.constructor),n}}"undefined"!=typeof Symbol&&(Graph.prototype[Symbol.for("nodejs.util.inspect.custom")]=Graph.prototype.inspect),EDGE_ADD_METHODS.forEach(e=>{["add","merge","update"].forEach(t=>{
1359
1359
  const r=e.name(t),n="add"===t?addEdge:mergeEdge;e.generateKey?Graph.prototype[r]=function(i,s,o){return n(this,r,!0,"undirected"===(e.type||this.type),null,i,s,o,"update"===t)}:Graph.prototype[r]=function(i,s,o,a){return n(this,r,!1,"undirected"===(e.type||this.type),i,s,o,a,"update"===t)}})}),attachNodeAttributesMethods(Graph),attachEdgeAttributesMethods(Graph),attachEdgeIterationMethods(Graph),attachNeighborIterationMethods(Graph);class DirectedGraph extends Graph{constructor(e){const t=assign({type:"directed"},e);if("multi"in t&&!1!==t.multi)throw new InvalidArgumentsGraphError("DirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if("directed"!==t.type)throw new InvalidArgumentsGraphError('DirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}class UndirectedGraph extends Graph{constructor(e){const t=assign({type:"undirected"},e)
1360
1360
  ;if("multi"in t&&!1!==t.multi)throw new InvalidArgumentsGraphError("UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if("undirected"!==t.type)throw new InvalidArgumentsGraphError('UndirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}class MultiGraph extends Graph{constructor(e){const t=assign({multi:!0},e);if("multi"in t&&!0!==t.multi)throw new InvalidArgumentsGraphError("MultiGraph.from: inconsistent indication that the graph should be simple in given options!");super(t)}}class MultiDirectedGraph extends Graph{constructor(e){const t=assign({type:"directed",multi:!0},e);if("multi"in t&&!0!==t.multi)throw new InvalidArgumentsGraphError("MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if("directed"!==t.type)throw new InvalidArgumentsGraphError('MultiDirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}
1361
- class MultiUndirectedGraph extends Graph{constructor(e){const t=assign({type:"undirected",multi:!0},e);if("multi"in t&&!0!==t.multi)throw new InvalidArgumentsGraphError("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if("undirected"!==t.type)throw new InvalidArgumentsGraphError('MultiUndirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}function attachStaticFromMethod(e){e.from=function(t,r){const n=assign({},t.options,r),i=new e(n);return i.import(t),i}}function _optionalChain$$(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function createSpecGraph(e,t){const r=new DirectedGraph,n=new Set;return await async function t(i){if(n.has(i))return;n.add(i);const s=await e.readText(i)
1362
- ;if(void 0===s)return;if(r.mergeNode(i,{type:"file",path:i}),!s.trim())return;const o=specFromMarkdown(s).querySelectorAll("a[href]");for(const e of o){const n=_optionalChain$$([e,"access",e=>e.getAttribute,"call",e=>e("href"),"optionalAccess",e=>e.trim,"call",e=>e()]);if(!n||isAnchor(n))continue;const s=addTargetNode(r,i,n),o=getEdgeFromElement(e);o&&r.mergeEdge(i,s,o),"file"===r.getNodeAttribute(s,"type")&&await t(s)}}(t),r}function addTargetNode(e,t,r){if(isUri(r))return e.mergeNode(r,{type:"uri",uri:r})[0];if(isExternalDependency(r))return e.mergeNode(r,{type:"external-dependency",name:r})[0];const n=resolveRelativeToRoot(t,r),i=isCodeFile(n)?"code":"file";return e.mergeNode(n,{type:i,path:n})[0]}function isCodeFile(e){const t=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".cs",".php",".swift",".kt",".scala",".clj",".hs",".ml",".fs",".v",".zig",".nim"]),r=e.toLowerCase().substring(e.lastIndexOf("."));return t.has(r)}function getEdgeFromElement(e){
1361
+ class MultiUndirectedGraph extends Graph{constructor(e){const t=assign({type:"undirected",multi:!0},e);if("multi"in t&&!0!==t.multi)throw new InvalidArgumentsGraphError("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if("undirected"!==t.type)throw new InvalidArgumentsGraphError('MultiUndirectedGraph.from: inconsistent "'+t.type+'" type in given options!');super(t)}}function attachStaticFromMethod(e){e.from=function(t,r){const n=assign({},t.options,r),i=new e(n);return i.import(t),i}}function _optionalChain$_(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function createSpecGraph(e,t){const r=new DirectedGraph,n=new Set;return await async function t(i){if(n.has(i))return;n.add(i);const s=await e.readText(i)
1362
+ ;if(void 0===s)return;if(r.mergeNode(i,{type:"file",path:i}),!s.trim())return;const o=specFromMarkdown(s).querySelectorAll("a[href]");for(const e of o){const n=_optionalChain$_([e,"access",e=>e.getAttribute,"call",e=>e("href"),"optionalAccess",e=>e.trim,"call",e=>e()]);if(!n||isAnchor(n))continue;const s=addTargetNode(r,i,n),o=getEdgeFromElement(e);o&&r.mergeEdge(i,s,o),"file"===r.getNodeAttribute(s,"type")&&await t(s)}}(t),r}function addTargetNode(e,t,r){if(isUri(r))return e.mergeNode(r,{type:"uri",uri:r})[0];if(isExternalDependency(r))return e.mergeNode(r,{type:"external-dependency",name:r})[0];const n=resolveRelativeToRoot(t,r),i=isCodeFile(n)?"code":"file";return e.mergeNode(n,{type:i,path:n})[0]}function isCodeFile(e){const t=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".cs",".php",".swift",".kt",".scala",".clj",".hs",".ml",".fs",".v",".zig",".nim"]),r=e.toLowerCase().substring(e.lastIndexOf("."));return t.has(r)}function getEdgeFromElement(e){
1363
1363
  return findParentSection(e,"test")?{type:"test",label:e.textContent}:findParentSection(e,"generate")||findParentSection(e,"describe")?{type:"code",label:e.textContent}:findParentSection(e,"use")?{type:"use",label:e.textContent}:{type:"href",label:e.textContent}}function isAnchor(e){return e.startsWith("#")}function isUri(e){try{return new URL(e),!0}catch(e){return!1}}function collectDependencies(e,t,r=1/0,n=new Set){if(!e.hasNode(t))throw new Error(`Node '${t}' does not exist in the graph`);const i=[];if(r<=0)return i;n.add(t);for(const s of e.outEdges(t)){const o=e.target(s),a=e.getEdgeAttributes(s),c=e.getNodeAttributes(o);if("use"===a.type){if(i.push([t,o,c.type]),n.has(o))continue;i.push(...collectDependencies(e,o,r-1,n))}}return i}async function*findNodesByEdgeType(e,t,r,n){const i=n?t.filterEdges(n,(e,t)=>t.type===r):t.filterEdges((e,t)=>t.type===r);for(const r of i){const n=t.target(r),i=await e.readText(n);yield[n,i]}}function extractCodeDependencies(e,t){const r=[]
1364
- ;for(const n of e.outEdges(t)){if("use"!==e.getEdgeAttributes(n).type)continue;const t=e.target(n),i=e.getNodeAttributes(t);"code"===i.type&&r.push({path:i.path})}return r}function _optionalChain$_(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}attachStaticFromMethod(Graph),attachStaticFromMethod(DirectedGraph),attachStaticFromMethod(UndirectedGraph),attachStaticFromMethod(MultiGraph),attachStaticFromMethod(MultiDirectedGraph),attachStaticFromMethod(MultiUndirectedGraph),Graph.Graph=Graph,Graph.DirectedGraph=DirectedGraph,Graph.UndirectedGraph=UndirectedGraph,Graph.MultiGraph=MultiGraph,Graph.MultiDirectedGraph=MultiDirectedGraph,Graph.MultiUndirectedGraph=MultiUndirectedGraph,Graph.InvalidArgumentsGraphError=InvalidArgumentsGraphError,Graph.NotFoundGraphError=NotFoundGraphError,
1365
- Graph.UsageGraphError=UsageGraphError;const KNOWLEDGE_MD_FILENAME$1="KNOWLEDGE.md";async function loadKnowledgeIndex(e){const t=new Map,r=await e.readText(KNOWLEDGE_MD_FILENAME$1);if(!r)return t;const n=specFromMarkdown(r);for(const e of n.querySelectorAll("a[href]")){const r=_optionalChain$_([e,"access",e=>e.getAttribute,"call",e=>e("href"),"optionalAccess",e=>e.trim,"call",e=>e()]);if(!_optionalChain$_([r,"optionalAccess",e=>e.endsWith,"call",e=>e(".md")]))continue;const n=_optionalChain$_([e,"access",e=>e.textContent,"optionalAccess",e=>e.trim,"call",e=>e()]);n&&t.set(n,{packageName:n,mainDocPath:r})}return t}async function _asyncNullishCoalesce$6(e,t){return null!=e?e:await t()}function allowedExtraFiles(e){return!e.includes(DEFAULT_TESSL_DIRS.frameworkDirectory)}async function getSharedFileContext(e){const{filePath:t,extraFiles:r=[],fsd:n,rc:i,allowEmptyFile:s=!1,fileType:o,includeLinkedContent:a}=e,{logger:c,reporter:u}=i;let l=0
1364
+ ;for(const n of e.outEdges(t)){if("use"!==e.getEdgeAttributes(n).type)continue;const t=e.target(n),i=e.getNodeAttributes(t);"code"===i.type&&r.push({path:i.path})}return r}function _optionalChain$Z(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}attachStaticFromMethod(Graph),attachStaticFromMethod(DirectedGraph),attachStaticFromMethod(UndirectedGraph),attachStaticFromMethod(MultiGraph),attachStaticFromMethod(MultiDirectedGraph),attachStaticFromMethod(MultiUndirectedGraph),Graph.Graph=Graph,Graph.DirectedGraph=DirectedGraph,Graph.UndirectedGraph=UndirectedGraph,Graph.MultiGraph=MultiGraph,Graph.MultiDirectedGraph=MultiDirectedGraph,Graph.MultiUndirectedGraph=MultiUndirectedGraph,Graph.InvalidArgumentsGraphError=InvalidArgumentsGraphError,Graph.NotFoundGraphError=NotFoundGraphError,
1365
+ Graph.UsageGraphError=UsageGraphError;const KNOWLEDGE_MD_FILENAME$1="KNOWLEDGE.md";async function loadKnowledgeIndex(e){const t=new Map,r=await e.readText(KNOWLEDGE_MD_FILENAME$1);if(!r)return t;const n=specFromMarkdown(r);for(const e of n.querySelectorAll("a[href]")){const r=_optionalChain$Z([e,"access",e=>e.getAttribute,"call",e=>e("href"),"optionalAccess",e=>e.trim,"call",e=>e()]);if(!_optionalChain$Z([r,"optionalAccess",e=>e.endsWith,"call",e=>e(".md")]))continue;const n=_optionalChain$Z([e,"access",e=>e.textContent,"optionalAccess",e=>e.trim,"call",e=>e()]);n&&t.set(n,{packageName:n,mainDocPath:r})}return t}async function _asyncNullishCoalesce$6(e,t){return null!=e?e:await t()}function allowedExtraFiles(e){return!e.includes(DEFAULT_TESSL_DIRS.frameworkDirectory)}async function getSharedFileContext(e){const{filePath:t,extraFiles:r=[],fsd:n,rc:i,allowEmptyFile:s=!1,fileType:o,includeLinkedContent:a}=e,{logger:c,reporter:u}=i;let l=0
1366
1366
  ;const d=await _asyncNullishCoalesce$6(await n.readText(t),async()=>"");if(d||s||(u.failure(`${o} not found: ${t}`,{filePath:t}),l=FAILURE),d)try{assertSafeText(d)}catch(e){const r=e instanceof Error?e.message:String(e);u.failure(`${o} contains unsafe characters and cannot be processed: ${t}`,{filePath:t,error:r}),l=FAILURE}const p={};for(const e of r.filter(allowedExtraFiles)){const t=await n.readText(e);t?(c.debug({file:e},"Loading context from file"),p[e]=t):(c.error({file:e},"File not found"),u.failure(`File not found: ${e}`,{file:e}),l=FAILURE)}let h={};return a&&(h=await getLinkedContentContext({specPath:t,specContent:d,fsd:n,rc:i})),{fileContent:d,extraFilesContext:p,linkedContentContext:h,exitCode:l}}async function getStandardSpecFileContext(e){const{specPath:t,extraFiles:r=[],fsd:n,rc:i,allowEmptySpec:s=!1,includeLinkedContent:o=!1}=e,{logger:a}=i;let c=0;const{fileContent:u,extraFilesContext:l,linkedContentContext:d,exitCode:p}=await getSharedFileContext({filePath:t,
1367
1367
  extraFiles:r,fsd:n,rc:i,allowEmptyFile:s,fileType:"Spec",includeLinkedContent:o});c=p;let h={},A={};try{u&&(h=await getSpecGraphContext(t,n,i),A=await getCodeDependencyContext(t,n,i))}catch(e){if(e instanceof TargetError)a.error({specPath:t,target:e.target},e.message);else{const r=e;a.error({specPath:t},r.message)}c=1}return{specContent:u,fileContext:{...l,...d,...h,...A},exitCode:c}}async function getStandardPlanFileContext(e){const{planPath:t,extraFiles:r=[],fsd:n,rc:i,allowEmptyPlan:s=!1,includeLinkedContent:o=!1}=e,{fileContent:a,extraFilesContext:c,linkedContentContext:u,exitCode:l}=await getSharedFileContext({filePath:t,extraFiles:r,fsd:n,rc:i,allowEmptyFile:s,fileType:"Plan",includeLinkedContent:o});return{planContent:a,fileContext:{...c,...u},exitCode:l}}async function getSpecGraphContext(e,t,r){const{resolveImport:n}=r,i=collectDependencies(await createSpecGraph(t,e),e),s=await loadKnowledgeIndex(t),o={};for(const[,e,a]of i)if("external-dependency"===a){if(s.has(e))continue
1368
1368
  ;const t=await n.resolve(e);if(!t)throw new TargetError("Could not resolve external dependency",e);const i=await readRootSpec(t,!0);i?o[e]=i:r.logger.debug({},`No content found for ${e} external dependency: is it installed? Does it have a spec?`)}else if("file"===a){const r=await t.readText(e);r&&(o[e]=r)}return o}async function getCodeDependencyContext(e,t,r){const{logger:n}=r,i=extractCodeDependencies(await createSpecGraph(t,e),e),s={};for(const e of i){const r=await t.readText(e.path);r?(n.debug({file:e.path},"Loading code dependency context from file"),s[e.path]=r):n.warn({file:e.path},"Code dependency file not found, skipping")}return s}async function getLinkedContentContext(e){const{specPath:t,specContent:r,fsd:n,rc:i,maxDepth:s=3,currentDepth:o=0,visitedPaths:a=new Set}=e,{logger:c}=i;if(o>=s)return{};a.add(t);const u=findRegularLinks(specFromMarkdown(r)),l={};for(const e of u)try{const r=resolveRelativeToRoot(t,e.href);if(a.has(r)){c.debug({file:r,linkText:e.text
@@ -1450,12 +1450,12 @@ message:"The spec contains both @generate and @describe links",severity:Diagnost
1450
1450
  "unable-to-resolve-spec":{message:"Unable to resolve path to spec '%path%'",severity:DiagnosticSeverity.Error,resolution:{message:"Create a new spec.",tool:"create",params:{spec:"%spec%"}}},"unable-to-resolve-test":{message:"Unable to resolve path to test '%path%'",severity:DiagnosticSeverity.Error,resolution:{message:"Create missing test files",tool:"build-tests",positionalParams:["%spec%"]}},"unable-to-resolve-implementation":{message:"Unable to resolve path to implementation '%path%'",severity:DiagnosticSeverity.Error,resolution:{message:"Create missing implementation files",tool:"build",positionalParams:["%spec%"]}},"empty-test":{message:"The test at '%path%' exists on disk but is empty",severity:DiagnosticSeverity.Error,resolution:{message:"Create a new test file",tool:"build-tests",positionalParams:["%spec%"]}},"empty-spec":{message:"The spec at '%path%' exists on disk but is empty",severity:DiagnosticSeverity.Error,resolution:{message:"Create a new spec.",tool:"create",params:{
1451
1451
  spec:"%spec%",force:!0}}},"empty-implementation":{message:"The implementation at '%path%' exists on disk but is empty",severity:DiagnosticSeverity.Error,resolution:{message:"Create a new implementation file",tool:"build",positionalParams:["%spec%"]}},"generated-code-out-of-sync":{message:"Spec has changed but code has not been regenerated (%path%)",severity:DiagnosticSeverity.Error,resolution:{message:"Regenerate code from the spec",tool:"build",positionalParams:["%spec%"]}},"generated-tests-out-of-sync":{message:"Spec has changed but test has not been regenerated (%path%)",severity:DiagnosticSeverity.Error,resolution:{message:"Regenerate tests from the spec",tool:"build-tests",positionalParams:["%spec%"]}},"generated-code-manually-edited":{message:"Generated code has been manually edited (%path%) and may not match the spec",severity:DiagnosticSeverity.Error,resolution:{message:"Run document to update the spec with any changes made manually to the code",tool:"document",params:{
1452
1452
  spec:"%spec%",code:"%path%","include-impl-details":!0}}},"generated-test-manually-edited":{message:"Generated test has been manually edited (%path%) and may not match the spec",severity:DiagnosticSeverity.Error,resolution:{message:"Run document to update the spec with any changes made manually to the test",tool:"document",params:{spec:"%spec%",code:"%path%","include-impl-details":!0}}},"missing-agents-md":{message:"The project is missing an AGENTS.md file, Tessl tools may be missing project context",severity:DiagnosticSeverity.Error,resolution:{message:"Reinitialize Tessl to create an AGENTS.md file in the project root, then add project context",tool:"init"}},"missing-agents-md-hooks":{message:"The AGENTS.md file is missing required Tessl framework references",severity:DiagnosticSeverity.Warning,resolution:{message:"Reinitialize Tessl to update the AGENTS.md file",tool:"init"}},"orphaned-generated-test":{message:"Orphaned test file '%path%' is no longer referenced in spec",
1453
- severity:DiagnosticSeverity.Error,resolution:{message:"Delete test file %path%"}}},isDiagnosticCode=e=>!(!e||"string"!=typeof e)&&Object.keys(CODES).includes(e),isWarning=e=>e.severity===DiagnosticSeverity.Warning,isError$1=e=>e.severity===DiagnosticSeverity.Error;function formatDiagnosticMessage(e,t,r){return e.replace(/%spec%/g,t||"").replace(/%path%/g,r||"")}function formatResolutionParams(e,t,r){if(!e)return{};const n={};for(const[i,s]of Object.entries(e))n[i]="string"==typeof s?s.replace(/%spec%/g,t||"").replace(/%path%/g,r||""):s;return n}function formatPositionalParams(e,t,r){if(e)return e.map(e=>e.replace(/%spec%/g,t||"").replace(/%path%/g,r||""))}function _nullishCoalesce$U(e,t){return null!=e?e:t()}function _optionalChain$Z(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
1453
+ severity:DiagnosticSeverity.Error,resolution:{message:"Delete test file %path%"}}},isDiagnosticCode=e=>!(!e||"string"!=typeof e)&&Object.keys(CODES).includes(e),isWarning=e=>e.severity===DiagnosticSeverity.Warning,isError$1=e=>e.severity===DiagnosticSeverity.Error;function formatDiagnosticMessage(e,t,r){return e.replace(/%spec%/g,t||"").replace(/%path%/g,r||"")}function formatResolutionParams(e,t,r){if(!e)return{};const n={};for(const[i,s]of Object.entries(e))n[i]="string"==typeof s?s.replace(/%spec%/g,t||"").replace(/%path%/g,r||""):s;return n}function formatPositionalParams(e,t,r){if(e)return e.map(e=>e.replace(/%spec%/g,t||"").replace(/%path%/g,r||""))}function _nullishCoalesce$U(e,t){return null!=e?e:t()}function _optionalChain$Y(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
1454
1454
  async function getDiagnostics(e,t){const r=await createSpecGraph(e,t),n=[],i=await e.readText(t);if(void 0===i)throw new Error(`Unable to read spec file at ${t}`);const s=await getDiagnosticsForSpec(e,r,t,i);return n.push({uri:t,diagnostics:s}),n}async function getDiagnosticsForSpec(e,t,r,n){const i=specFromMarkdown(n),{addDiagnostic:s,diagnostics:o}=trackDiagnostics(n,r);n.trim().split("\n").length<5&&s("tiny-spec");const a=findTests(i);0===a.length&&s("no-tests"),0===findApi(i).length&&s("no-api");const c=findImplementationPaths(i),u=c.generate.length,l=c.describe.length,d=u+l;0===d?s("no-implementation-links"):d>1&&(s("multiple-implementation-links"),u>0&&l>0&&s("mixed-implementation-links"));for await(const[n,i]of findNodesByEdgeType(e,t,"use",r))"file"===t.getNodeAttribute(n,"type")&&(void 0===i&&s("unable-to-resolve-spec",n),""===i&&s("empty-spec",n));for await(const[n,i]of findNodesByEdgeType(e,t,"test",r))void 0===i&&s("unable-to-resolve-test",n),
1455
- ""===_optionalChain$Z([i,"optionalAccess",e=>e.trim,"call",e=>e()])&&s("empty-test",n);for await(const[n,i]of findNodesByEdgeType(e,t,"code",r))void 0===i&&s("unable-to-resolve-implementation",n),""===_optionalChain$Z([i,"optionalAccess",e=>e.trim,"call",e=>e()])&&s("empty-implementation",n);if(1===u&&0===l){const t=calculateSpecHash(n);await checkFilesForOutOfSyncHash(e,c.generate.map(e=>resolveRelativeToRoot(r,e)),t,"generated-code-out-of-sync",s);const i=a.filter(e=>void 0!==e.path).map(e=>resolveRelativeToRoot(r,e.path));await checkFilesForOutOfSyncHash(e,i,t,"generated-tests-out-of-sync",s),await checkForOrphanedGeneratedTests(e,r,i,s),await checkCodeForManualEdits(e,c.generate.map(e=>resolveRelativeToRoot(r,e)),"generated-code-manually-edited",s),await checkCodeForManualEdits(e,i,"generated-test-manually-edited",s)}return o}async function checkForOrphanedGeneratedTests(e,t,r,n){
1455
+ ""===_optionalChain$Y([i,"optionalAccess",e=>e.trim,"call",e=>e()])&&s("empty-test",n);for await(const[n,i]of findNodesByEdgeType(e,t,"code",r))void 0===i&&s("unable-to-resolve-implementation",n),""===_optionalChain$Y([i,"optionalAccess",e=>e.trim,"call",e=>e()])&&s("empty-implementation",n);if(1===u&&0===l){const t=calculateSpecHash(n);await checkFilesForOutOfSyncHash(e,c.generate.map(e=>resolveRelativeToRoot(r,e)),t,"generated-code-out-of-sync",s);const i=a.filter(e=>void 0!==e.path).map(e=>resolveRelativeToRoot(r,e.path));await checkFilesForOutOfSyncHash(e,i,t,"generated-tests-out-of-sync",s),await checkForOrphanedGeneratedTests(e,r,i,s),await checkCodeForManualEdits(e,c.generate.map(e=>resolveRelativeToRoot(r,e)),"generated-code-manually-edited",s),await checkCodeForManualEdits(e,i,"generated-test-manually-edited",s)}return o}async function checkForOrphanedGeneratedTests(e,t,r,n){
1456
1456
  const i=(t.split("/").pop()||"").replace(new RegExp(`\\${SPEC_FILE_EXTENSION}$`),""),s=[`**/*${i}*test*/**/*`,`**/*test*${i}*/**/*`,`**/${i}/**/*.test.*`,`**/${i}/**/*.spec.*`,`**/tests/**/${i}/**/*`,`**/test/**/${i}/**/*`],o=new Set;for(const t of s)try{(await e.glob(t)).forEach(e=>o.add(e))}catch(e){}for(const t of o){const i=await e.readText(t);if(!i)continue;if(!(null!==extractCodeTag(i)))continue;r.includes(t)||n("orphaned-generated-test",t)}}async function checkFilesForOutOfSyncHash(e,t,r,n,i){for(const s of t){const t=await e.readText(s);if(t){const e=extractSpecHash(t);e&&e!==r&&i(n,s)}}}async function checkCodeForManualEdits(e,t,r,n){for(const i of t){const t=await e.readText(i);t&&isCodeFileDirty(t)&&n(r,i)}}function resolutionToCommand(e){if(!e.tool)return"";const t=e.positionalParams?e.positionalParams.map(e=>`"${e.replace(/"/g,'\\"')}"`).join(" "):"",r=e.params?Object.entries(e.params).map(([e,t])=>{if("boolean"==typeof t)return t?`--${e}`:null
1457
1457
  ;return`--${e} "${String(t).replace(/"/g,'\\"')}"`}).filter(e=>null!==e):[],n=t?` ${t}`:"",i=r.length>0?` ${r.join(" ")}`:"";return`tessl ${e.tool}${n}${i}`}async function getProjectDiagnostics(e){const t=[],r=AGENTS_MD_FILENAME,n=await e.readText(r);if(void 0===n){const{addDiagnostic:e,diagnostics:n}=trackDiagnostics("",r);e("missing-agents-md"),n.length>0&&t.push({uri:r,diagnostics:n})}else{const e=getMissingAgentsMdHooks(n,DEFAULT_HOOKS.filter(e=>e!==BOOTSTRAP_HOOK));if(e.length>0){const{addDiagnostic:e,diagnostics:i}=trackDiagnostics(n,r);e("missing-agents-md-hooks"),i.length>0&&t.push({uri:r,diagnostics:i})}}return t}function displayDiagnostics(e,t,r){for(const{diagnostics:n}of e)t.list(r,n.map(e=>{const{message:t,resolution:r}=e,n=resolutionToCommand(r),i=isWarning(e)?"yellow":"red",s=n?`{white - to fix run: {cyan ${n}}}`:`{white - to fix: {cyan ${r.message.charAt(0).toLowerCase()+r.message.slice(1)}}}`;return`{${i} ${figures.cross} ${t}} ${s}`}),""),t.message("\n")}
1458
- function trackDiagnostics(e,t){const r=e.split("\n"),n=_nullishCoalesce$U(_optionalChain$Z([r,"access",e=>e.at,"call",e=>e(-1),"optionalAccess",e=>e.length]),()=>0),i=[];return{addDiagnostic:(e,s,o)=>{if(!CODES[e])throw new Error(`Unknown diagnostic code: ${e}`);const{message:a,resolution:c,...u}=CODES[e];i.push({code:e,...u,message:formatDiagnosticMessage(a,t,s),resolution:{...c,message:formatDiagnosticMessage(c.message,t,s),..."params"in c&&c.params&&{params:formatResolutionParams(c.params,t,s)},..."positionalParams"in c&&c.positionalParams&&{positionalParams:formatPositionalParams(c.positionalParams,t,s)}},...o,range:{start:{line:0,character:0},end:{line:r.length-1,character:n}}})},diagnostics:i}}async function isSpec(e,t){if(t.endsWith(".spec.md"))return!0;if(t.endsWith(".md"))try{return!isInvalidSpec(await getDiagnostics(e,t))}catch(e){return!1}return!1}function isInvalidSpec(e){const t=new Set(["no-api","no-tests","no-implementation-links"])
1458
+ function trackDiagnostics(e,t){const r=e.split("\n"),n=_nullishCoalesce$U(_optionalChain$Y([r,"access",e=>e.at,"call",e=>e(-1),"optionalAccess",e=>e.length]),()=>0),i=[];return{addDiagnostic:(e,s,o)=>{if(!CODES[e])throw new Error(`Unknown diagnostic code: ${e}`);const{message:a,resolution:c,...u}=CODES[e];i.push({code:e,...u,message:formatDiagnosticMessage(a,t,s),resolution:{...c,message:formatDiagnosticMessage(c.message,t,s),..."params"in c&&c.params&&{params:formatResolutionParams(c.params,t,s)},..."positionalParams"in c&&c.positionalParams&&{positionalParams:formatPositionalParams(c.positionalParams,t,s)}},...o,range:{start:{line:0,character:0},end:{line:r.length-1,character:n}}})},diagnostics:i}}async function isSpec(e,t){if(t.endsWith(".spec.md"))return!0;if(t.endsWith(".md"))try{return!isInvalidSpec(await getDiagnostics(e,t))}catch(e){return!1}return!1}function isInvalidSpec(e){const t=new Set(["no-api","no-tests","no-implementation-links"])
1459
1459
  ;return e.some(e=>e.diagnostics.some(e=>isDiagnosticCode(e.code)&&t.has(e.code)))}async function listSpecs(e,t=""){const r=[],n=SPEC_FILE_EXTENSION,i=await e.glob(`**/${t}*${n}`);for(const t of i)await isSpec(e,t)&&r.push(t);return r}const getPath=e=>"string"==typeof e?e:e.path,getPaths=e=>e.map(getPath);async function findAllLinkedFiles(e,t,r){const n=await listSpecs(t,""),i={};return await e.reporter.cMap(n,async(n,s)=>{s(`Checking spec ${n}...`);try{(await specLinkedPaths(t,n,r,e.projectDir)).forEach(t=>{i[t]?e.reporter.alert("error",`Code file ${t} linked by ${n} is already linked by ${i[t]} and ${n}`):i[t]=n})}catch(t){return void e.reporter.alert("error",`Failed to check spec file ${n}: ${t instanceof Error?t.message:String(t)}`)}}),i}function specLinkedPathsFromContents(e,t,r,n,i=!0){const s=dirname(t),o=specFromMarkdown(e),a=[];for(const e of r){const t=e(o);a.push(...t)}const c=a.map(e=>{const t="string"==typeof e?e:e.path,r=resolve$3(n,s,t),i=relative(n,r)
1460
1460
  ;if("string"==typeof e)return i;if("object"==typeof e)return{...e,path:i};throw new Error("Invalid link type")});return i?dedupLinks(c):c}function dedupLinks(e){const t={};return e.forEach(e=>{t[getPath(e)]=e}),Object.values(t)}async function specLinkedPaths(e,t,r,n,i=!0){const s=await e.readText(t);if(void 0===s)throw new Error("Spec file not found");return specLinkedPathsFromContents(s,t,r,n,i)}async function findSpecLinkingFile(e,t,r,n){const i=await listSpecs(t,""),s=relative(e.projectDir,resolve$3(e.projectDir,n));for(const n of i)try{if((await specLinkedPaths(t,n,r,e.projectDir)).includes(s))return n}catch(t){e.reporter.alert("error",`Failed to check spec file ${n}: ${t instanceof Error?t.message:String(t)}`);continue}}const returnSchema={name:"testOutput",schema:objectType({numPassingTests:numberType(),numFailingTests:numberType(),numErrorTests:numberType(),numTotalTests:numberType(),numPassingImplTests:numberType(),numFailingImplTests:numberType(),
1461
1461
  numErrorImplTests:numberType(),testLineCoveragePercentage:numberType(),testBranchCoveragePercentage:numberType(),testFunctionCoveragePercentage:numberType(),testStatementCoveragePercentage:numberType()})};async function analyseResults(e,t){const r=formatRunTestCommandUserPrompt(e);return{...await t(RUN_TEST_COMMAND_SYSTEM_TEMPLATE).user(r).object(returnSchema),fullResponse:e}}
@@ -1783,11 +1783,11 @@ if(!(i&&0<=i&&i<6e4)){const r=e.maxRetries??this.maxRetries;i=this.calculateDefa
1783
1783
  OpenAI.UnprocessableEntityError=UnprocessableEntityError$1,OpenAI.InvalidWebhookSignatureError=InvalidWebhookSignatureError,OpenAI.toFile=toFile$1,OpenAI.Completions=Completions$1,OpenAI.Chat=Chat,OpenAI.Embeddings=Embeddings,OpenAI.Files=Files$2,OpenAI.Images=Images,OpenAI.Audio=Audio,OpenAI.Moderations=Moderations,OpenAI.Models=Models$2,OpenAI.FineTuning=FineTuning,OpenAI.Graders=Graders,OpenAI.VectorStores=VectorStores,OpenAI.Webhooks=Webhooks,OpenAI.Beta=Beta$1,OpenAI.Batches=Batches$2,OpenAI.Uploads=Uploads,OpenAI.Responses=Responses,OpenAI.Evals=Evals,OpenAI.Containers=Containers;const SCRIPT_SHOULD_RETRY=Symbol();function allowRetries(e,{withDelay:t}){return e[SCRIPT_SHOULD_RETRY]={withDelay:t},e}function isShouldRetryFlag(e){if(!(SCRIPT_SHOULD_RETRY in e))return!1;const t=e[SCRIPT_SHOULD_RETRY];return!!t&&"object"==typeof t&&"withDelay"in t&&"boolean"==typeof t.withDelay}function retryableError(e){
1784
1784
  return!(!e||"object"!=typeof e)&&(isShouldRetryFlag(e)?structuredClone(e[SCRIPT_SHOULD_RETRY]):!!retryableAggregatedServerError(e)&&{withDelay:!0})}function retryableAggregatedServerError(e){if(!(e instanceof AggregateError))return!1;const t=e.errors[0];return t instanceof Error&&(!!retryableServerError(t)||!!("cause"in t&&t.cause&&t.cause instanceof Error)&&retryableServerError(t.cause))}function retryableServerError(e){if("code"in e&&e.code&&"string"==typeof e.code)return["ERR_STREAM_PREMATURE_CLOSE","ETIMEDOUT","ECONNREFUSED","ECONNABORTED","ECONNRESET"].includes(e.code);if("type"in e)switch(e.type){case"APIConnectionTimeoutError":case"APIConnectionError":case"APIError":return!0;case"InternalServerError":if("status"in e&&[500,502].includes(e.status))return!0}return!1}function isUnauthorizedError(e){return"object"==typeof e&&null!==e&&"status"in e&&401===e.status}function isAuthenticationError(e){if(isUnauthorizedError(e))return!0
1785
1785
  ;if("object"==typeof e&&null!==e&&"status"in e&&400===e.status){return getMessageFromMaybeError(e).toLowerCase().includes("expired key")}return!1}function getUserFacingMessageFromError(e){const t=getMessageFromMaybeError(e);return isAuthenticationError(e)?t.includes("team not allowed to access model")?"Unrecognized model, please check the value of `--model-name`":"Invalid key, please run `tessl login` and try again.":e instanceof BadRequestError$1&&e.message.includes("Violated OpenAI moderation policy")?"Violated moderation policy":t?`Error communicating with LLM: ${t}`:"Error communicating with LLM"}function chatStreamBuilder(e,t){let r=!1;const n=async e=>{if(r)throw new Error("already consumed");return r=!0,await t(e)};return{asString:n,asObject:async t=>await asObject(e,async()=>n(t))}}async function asObject(e,t,r=!0){if(!e)throw new Error("schema required for asObject");let n,i=await t();if(r){const e=i.trim()
1786
- ;e.startsWith("```json")&&e.endsWith("```")&&(i=e.substring(7,e.length-3).trim())}try{n=JSON.parse(i)}catch(e){throw allowRetries(new AggregateError([e],"asObject: error parsing json: "+i),{withDelay:!1})}try{return[e.parse(n),i]}catch(e){throw allowRetries(new AggregateError([e],"asObject: error validating json: "+JSON.stringify(n)),{withDelay:!1})}}async function sleepInterruptable(e,t){return new Promise((r,n)=>{const i=setTimeout$1(()=>{o(),r()},e);function s(){clearTimeout(i),o(),n(new Error("aborted during nap"))}function o(){t.removeEventListener("abort",s)}t.addEventListener("abort",s),t.aborted&&s()})}async function sleepUntil(e,t){const r=Date.now();if(e<=r)return;const n=e-r;await sleepInterruptable(n,t)}function _optionalChain$Y(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}
1787
- return r}async function streamFakeTypingEvents(e,t,r,n=Date.now(),i="yes"===process.env.SLOWMO){for(const[s,o]of t)i&&await sleepUntil(n+1e3*s,r),await _optionalChain$Y([e,"optionalAccess",e=>e.chunk,"call",e=>e(o)]),throwWhenAborted(r)}function capturingTyper(e,t){const r=clock$2(),n=[];return{events:n,async start(){throwWhenAborted(e),await _optionalChain$Y([t,"optionalAccess",e=>e.start,"call",e=>e()])},async chunk(i){throwWhenAborted(e),n.push([Number(clock$2()-r)/1e9,i]),await _optionalChain$Y([t,"optionalAccess",e=>e.chunk,"call",e=>e(i)])},async countTokens(r){throwWhenAborted(e),await _optionalChain$Y([t,"optionalAccess",e=>e.countTokens,"call",e=>e(r)])},async done(){throwWhenAborted(e),await _optionalChain$Y([t,"optionalAccess",e=>e.done,"call",e=>e()])}}}function _nullishCoalesce$S(e,t){return null!=e?e:t()}function _optionalChain$X(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return
1788
- ;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}class LLMCacheMissError extends Error{constructor(e){super(`Expected an LLM cache hit but no matching entry was found for key ${e}`)}}function serializeInput(e,t){const{indent:r}=_nullishCoalesce$S(t,()=>({})),{args:n,...i}=e;return JSON.stringify({args:sortKeys(n,{deep:!0}),...i},void 0,r)}function cacheKey(e){const t=serializeInput(e);return base32.encode(createHash$1("sha512-256").update(t).digest()).replace(/=/g,"").toLowerCase()}function cacheWrapper(e,t,r){return{cacheKey:e.cacheKey,async streamFromMessages(n,i){const s=_optionalChain$X([i,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);return chatStreamBuilder(s,async o=>{let a=!1;const{string:c,events:u}=await r({method:"streamFromMessages",args:{messages:n},modelInfo:e.cacheKey,retryIdx:_optionalChain$X([i,"optionalAccess",e=>e.retryIdx])},async()=>{a=!0
1786
+ ;e.startsWith("```json")&&e.endsWith("```")&&(i=e.substring(7,e.length-3).trim())}try{n=JSON.parse(i)}catch(e){throw allowRetries(new AggregateError([e],"asObject: error parsing json: "+i),{withDelay:!1})}try{return[e.parse(n),i]}catch(e){throw allowRetries(new AggregateError([e],"asObject: error validating json: "+JSON.stringify(n)),{withDelay:!1})}}async function sleepInterruptable(e,t){return new Promise((r,n)=>{const i=setTimeout$1(()=>{o(),r()},e);function s(){clearTimeout(i),o(),n(new Error("aborted during nap"))}function o(){t.removeEventListener("abort",s)}t.addEventListener("abort",s),t.aborted&&s()})}async function sleepUntil(e,t){const r=Date.now();if(e<=r)return;const n=e-r;await sleepInterruptable(n,t)}function _optionalChain$X(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}
1787
+ return r}async function streamFakeTypingEvents(e,t,r,n=Date.now(),i="yes"===process.env.SLOWMO){for(const[s,o]of t)i&&await sleepUntil(n+1e3*s,r),await _optionalChain$X([e,"optionalAccess",e=>e.chunk,"call",e=>e(o)]),throwWhenAborted(r)}function capturingTyper(e,t){const r=clock$2(),n=[];return{events:n,async start(){throwWhenAborted(e),await _optionalChain$X([t,"optionalAccess",e=>e.start,"call",e=>e()])},async chunk(i){throwWhenAborted(e),n.push([Number(clock$2()-r)/1e9,i]),await _optionalChain$X([t,"optionalAccess",e=>e.chunk,"call",e=>e(i)])},async countTokens(r){throwWhenAborted(e),await _optionalChain$X([t,"optionalAccess",e=>e.countTokens,"call",e=>e(r)])},async done(){throwWhenAborted(e),await _optionalChain$X([t,"optionalAccess",e=>e.done,"call",e=>e()])}}}function _nullishCoalesce$S(e,t){return null!=e?e:t()}function _optionalChain$W(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return
1788
+ ;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}class LLMCacheMissError extends Error{constructor(e){super(`Expected an LLM cache hit but no matching entry was found for key ${e}`)}}function serializeInput(e,t){const{indent:r}=_nullishCoalesce$S(t,()=>({})),{args:n,...i}=e;return JSON.stringify({args:sortKeys(n,{deep:!0}),...i},void 0,r)}function cacheKey(e){const t=serializeInput(e);return base32.encode(createHash$1("sha512-256").update(t).digest()).replace(/=/g,"").toLowerCase()}function cacheWrapper(e,t,r){return{cacheKey:e.cacheKey,async streamFromMessages(n,i){const s=_optionalChain$W([i,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);return chatStreamBuilder(s,async o=>{let a=!1;const{string:c,events:u}=await r({method:"streamFromMessages",args:{messages:n},modelInfo:e.cacheKey,retryIdx:_optionalChain$W([i,"optionalAccess",e=>e.retryIdx])},async()=>{a=!0
1789
1789
  ;const r=capturingTyper(t,o),c=await e.streamFromMessages(n,i),u=await c.asString(r);return s&&await asObject(s,()=>u),{string:u,events:JSON.stringify(r.events)}});return a||await streamFakeTypingEvents(o,JSON.parse(u),t),c})}}}async function considerFsCaching(){if(!process.env.LLM_CACHE_DIR)return;const e=resolve$2(process.env.LLM_CACHE_DIR);return await fsp.mkdir(e,{recursive:!0}),e}async function fsCache(e,t,r){const n=cacheKey(t),i=resolve$2(e,`${n}.toml`),s=await readTextIfExists(i);if(s){return tomlExports.parse(s).output}if("mock"===process.env.LLM_MODE){const r=serializeInput(t,{indent:2});throw await writeText(resolve$2(e,`${n}.input.json`),r),new LLMCacheMissError(n)}if("record"===process.env.LLM_MODE||"real"===process.env.LLM_MODE){const e=process.env.TESSL_LLM_API_KEY;if("dummy-key-replace-me"===e||"a"===e)throw new Error("LLM key is set to dummy value. Please read the integration test documentation and set TESSL_LLM_API_KEY to a real key when recording LLM snapshots.")}
1790
- const o=await r(),a={input:t,output:o};return await writeText(i,tomlExports.stringify(a)),o}async function redisCache(e,t,r){const n="cache:1:"+cacheKey(t);_optionalChain$X([trace$1,"access",e=>e.getActiveSpan,"call",e=>e(),"optionalAccess",e=>e.setAttribute,"call",e=>e("cache.key",n)]);const i=await e.get(n);if(i)return _optionalChain$X([trace$1,"access",e=>e.getActiveSpan,"call",e=>e(),"optionalAccess",e=>e.setAttribute,"call",e=>e("cache.hit",!0)]),JSON.parse(i);_optionalChain$X([trace$1,"access",e=>e.getActiveSpan,"call",e=>e(),"optionalAccess",e=>e.setAttribute,"call",e=>e("cache.hit",!1)]);const s=await r();return await e.set(n,JSON.stringify(s),"EX",2764800),s}function __classPrivateFieldSet(e,t,r,n,i){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}function __classPrivateFieldGet(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter")
1790
+ const o=await r(),a={input:t,output:o};return await writeText(i,tomlExports.stringify(a)),o}async function redisCache(e,t,r){const n="cache:1:"+cacheKey(t);_optionalChain$W([trace$1,"access",e=>e.getActiveSpan,"call",e=>e(),"optionalAccess",e=>e.setAttribute,"call",e=>e("cache.key",n)]);const i=await e.get(n);if(i)return _optionalChain$W([trace$1,"access",e=>e.getActiveSpan,"call",e=>e(),"optionalAccess",e=>e.setAttribute,"call",e=>e("cache.hit",!0)]),JSON.parse(i);_optionalChain$W([trace$1,"access",e=>e.getActiveSpan,"call",e=>e(),"optionalAccess",e=>e.setAttribute,"call",e=>e("cache.hit",!1)]);const s=await r();return await e.set(n,JSON.stringify(s),"EX",2764800),s}function __classPrivateFieldSet(e,t,r,n,i){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}function __classPrivateFieldGet(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter")
1791
1791
  ;if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}let uuid4=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return uuid4=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^r()&15>>+e/4).toString(16))};function isAbortError$1(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const castToError=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{
1792
1792
  return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class AnthropicError extends Error{}class APIError extends AnthropicError{constructor(e,t,r,n){super(`${APIError.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("request-id"),this.error=t}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new APIConnectionError({message:r,cause:castToError(t)});const i=t;return 400===e?new BadRequestError(e,i,r,n):401===e?new AuthenticationError(e,i,r,n):403===e?new PermissionDeniedError(e,i,r,n):404===e?new NotFoundError$1(e,i,r,n):409===e?new ConflictError(e,i,r,n):422===e?new UnprocessableEntityError(e,i,r,n):429===e?new RateLimitError(e,i,r,n):e>=500?new InternalServerError(e,i,r,n):new APIError(e,i,r,n)}}class APIUserAbortError extends APIError{
1793
1793
  constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class APIConnectionError extends APIError{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class APIConnectionTimeoutError extends APIConnectionError{constructor({message:e}={}){super({message:e??"Request timed out."})}}class BadRequestError extends APIError{}class AuthenticationError extends APIError{}class PermissionDeniedError extends APIError{}let NotFoundError$1=class extends APIError{};class ConflictError extends APIError{}class UnprocessableEntityError extends APIError{}class RateLimitError extends APIError{}class InternalServerError extends APIError{}const startsWithSchemeRegexp=/^[a-z][a-z0-9+.-]*:/i,isAbsoluteURL=e=>startsWithSchemeRegexp.test(e);let isArray$2=e=>(isArray$2=Array.isArray,isArray$2(e)),isReadonlyArray=isArray$2;function maybeObj(e){return"object"!=typeof e?{}:e??{}}function isEmptyObj$1(e){if(!e)return!0
@@ -1893,10 +1893,10 @@ return parseRecordDef$1(e,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseL
1893
1893
  $ref:getRelativePath$1(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),parseAnyDef$1(t)):"seen"===t.$refStrategy?parseAnyDef$1(t):void 0}},addMeta$1=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),zodToJsonSchema$2=(e,t)=>{const r=getRefs$1(t);let n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,n])=>({...e,[t]:parseDef$1(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??parseAnyDef$1(r)}),{}):void 0;const i="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,s=parseDef$1(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??parseAnyDef$1(r),o="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==o&&(s.title=o),
1894
1894
  r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===r.$refStrategy?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const a=void 0===i?n?{...s,[r.definitionPath]:n}:s:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:s}};return"jsonSchema7"===r.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("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 index$1=Object.freeze({__proto__:null,addErrorMessage:addErrorMessage$1,defaultOptions:defaultOptions$1,getDefaultOptions:getDefaultOptions$1,
1895
1895
  getRefs:getRefs$1,getRelativePath:getRelativePath$1,ignoreOverride:ignoreOverride$1,parseAnyDef:parseAnyDef$1,parseArrayDef:parseArrayDef$1,parseBigintDef:parseBigintDef$1,parseBooleanDef:parseBooleanDef$1,parseBrandedDef:parseBrandedDef$1,parseCatchDef:parseCatchDef$1,parseDateDef:parseDateDef$1,parseDef:parseDef$1,parseDefaultDef:parseDefaultDef$1,parseEffectsDef:parseEffectsDef$1,parseEnumDef:parseEnumDef$1,parseIntersectionDef:parseIntersectionDef$1,parseLiteralDef:parseLiteralDef$1,parseMapDef:parseMapDef$1,parseNativeEnumDef:parseNativeEnumDef$1,parseNeverDef:parseNeverDef$1,parseNullDef:parseNullDef$1,parseNullableDef:parseNullableDef$1,parseNumberDef:parseNumberDef$1,parseObjectDef:parseObjectDef$1,parseOptionalDef:parseOptionalDef$1,parsePipelineDef:parsePipelineDef$1,parsePromiseDef:parsePromiseDef$1,parseReadonlyDef:parseReadonlyDef$1,parseRecordDef:parseRecordDef$1,parseSetDef:parseSetDef$1,parseStringDef:parseStringDef$1,parseTupleDef:parseTupleDef$1,
1896
- parseUndefinedDef:parseUndefinedDef$1,parseUnionDef:parseUnionDef$1,parseUnknownDef:parseUnknownDef$1,primitiveMappings:primitiveMappings$1,selectParser:selectParser$1,setResponseValueAndErrors:setResponseValueAndErrors$1,zodPatterns:zodPatterns$1,zodToJsonSchema:zodToJsonSchema$2});function _optionalChain$W(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function removeThinking(e){const t=/(?<=<\/think>)([\s\S]*)/;return _optionalChain$W([e,"optionalAccess",e=>e.match,"call",e=>e(t),"optionalAccess",e=>e[0]])||""}function injectMinificationToMessages(e){return"system"===_optionalChain$W([e,"access",e=>e[0],"optionalAccess",e=>e.role])&&(e[0].content=e[0].content+"\nEmit a minified JSON in your response, no whitespace, newlines or tabs."),e}function translateMessagesToArray(e){let t
1897
- ;const r=[],n=[],i=()=>{r.length&&(n.push({role:t,content:r.map(e=>({text:e,type:"text"}))}),r.length=0)};for(const n of e){const e="system"===n.role?"user":n.role;t!==e&&(i(),t=e),r.push(n.content)}return i(),n}function appendSchema(e,t){const r=zodToJsonSchema$2(t);delete r.$schema,delete r.additionalProperties,e[e.length-1].content.push({text:"Return a JSON object matching this exact schema. Your response will be serialized as JSON, so make sure all newlines are properly escaped. Do not include any other text or commentary: "+JSON.stringify(r),type:"text"})}function nonStreamedAsString(e){return async t=>(await _optionalChain$W([t,"optionalAccess",e=>e.start,"call",e=>e()]),await _optionalChain$W([t,"optionalAccess",e=>e.chunk,"call",t=>t(e)]),await _optionalChain$W([t,"optionalAccess",e=>e.done,"call",e=>e()]),e)}function _nullishCoalesce$R(e,t){return null!=e?e:t()}function _optionalChain$V(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
1898
- ("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function handleConfig$2(e){return{max_tokens:4096,temperature:_nullishCoalesce$R(e.modelTemperature,()=>1),model:e.modelName,...e.modelParams}}function anthropicImpl(e,t){const r=new Anthropic({}),n=handleConfig$2(t);return{cacheKey:[n.model,String(n.temperature)],async streamFromMessages(e,t){const i=translateMessagesToArray(structuredClone(e)),s=_optionalChain$V([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);s&&appendSchema(i,s);const o={...n};delete o.model;const a=_optionalChain$V([t,"optionalAccess",e=>e.traceInfo,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.generation,"call",e=>e({name:_optionalChain$V([t,"optionalAccess",e=>e.traceInfo,"optionalAccess",e=>e.generationName]),model:n.model,modelParameters:o,input:i})]),c=await r.messages.create({messages:i,...n})
1899
- ;return _optionalChain$V([a,"optionalAccess",e=>e.end,"call",e=>e({output:c.content,usage:{input:_optionalChain$V([c,"access",e=>e.usage,"optionalAccess",e=>e.input_tokens]),output:_optionalChain$V([c,"access",e=>e.usage,"optionalAccess",e=>e.output_tokens])}})]),chatStreamBuilder(_optionalChain$V([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_optionalChain$V([c,"access",e=>e.content,"access",e=>e.map,"call",e=>e(e=>"text"===e.type?e.text:""),"optionalAccess",e=>e.join,"call",e=>e("\n")])))}}}var objectToString$2=Object.prototype.toString,isArray$1=Array.isArray||function(e){return"[object Array]"===objectToString$2.call(e)};function isFunction$1(e){return"function"==typeof e}function typeStr(e){return isArray$1(e)?"array":typeof e}function escapeRegExp(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(e,t){return null!=e&&"object"==typeof e&&t in e}function primitiveHasOwnProperty(e,t){
1896
+ parseUndefinedDef:parseUndefinedDef$1,parseUnionDef:parseUnionDef$1,parseUnknownDef:parseUnknownDef$1,primitiveMappings:primitiveMappings$1,selectParser:selectParser$1,setResponseValueAndErrors:setResponseValueAndErrors$1,zodPatterns:zodPatterns$1,zodToJsonSchema:zodToJsonSchema$2});function _optionalChain$V(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function removeThinking(e){const t=/(?<=<\/think>)([\s\S]*)/;return _optionalChain$V([e,"optionalAccess",e=>e.match,"call",e=>e(t),"optionalAccess",e=>e[0]])||""}function injectMinificationToMessages(e){return"system"===_optionalChain$V([e,"access",e=>e[0],"optionalAccess",e=>e.role])&&(e[0].content=e[0].content+"\nEmit a minified JSON in your response, no whitespace, newlines or tabs."),e}function translateMessagesToArray(e){let t
1897
+ ;const r=[],n=[],i=()=>{r.length&&(n.push({role:t,content:r.map(e=>({text:e,type:"text"}))}),r.length=0)};for(const n of e){const e="system"===n.role?"user":n.role;t!==e&&(i(),t=e),r.push(n.content)}return i(),n}function appendSchema(e,t){const r=zodToJsonSchema$2(t);delete r.$schema,delete r.additionalProperties,e[e.length-1].content.push({text:"Return a JSON object matching this exact schema. Your response will be serialized as JSON, so make sure all newlines are properly escaped. Do not include any other text or commentary: "+JSON.stringify(r),type:"text"})}function nonStreamedAsString(e){return async t=>(await _optionalChain$V([t,"optionalAccess",e=>e.start,"call",e=>e()]),await _optionalChain$V([t,"optionalAccess",e=>e.chunk,"call",t=>t(e)]),await _optionalChain$V([t,"optionalAccess",e=>e.done,"call",e=>e()]),e)}function _nullishCoalesce$R(e,t){return null!=e?e:t()}function _optionalChain$U(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
1898
+ ("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function handleConfig$2(e){return{max_tokens:4096,temperature:_nullishCoalesce$R(e.modelTemperature,()=>1),model:e.modelName,...e.modelParams}}function anthropicImpl(e,t){const r=new Anthropic({}),n=handleConfig$2(t);return{cacheKey:[n.model,String(n.temperature)],async streamFromMessages(e,t){const i=translateMessagesToArray(structuredClone(e)),s=_optionalChain$U([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);s&&appendSchema(i,s);const o={...n};delete o.model;const a=_optionalChain$U([t,"optionalAccess",e=>e.traceInfo,"optionalAccess",e=>e.parent,"optionalAccess",e=>e.generation,"call",e=>e({name:_optionalChain$U([t,"optionalAccess",e=>e.traceInfo,"optionalAccess",e=>e.generationName]),model:n.model,modelParameters:o,input:i})]),c=await r.messages.create({messages:i,...n})
1899
+ ;return _optionalChain$U([a,"optionalAccess",e=>e.end,"call",e=>e({output:c.content,usage:{input:_optionalChain$U([c,"access",e=>e.usage,"optionalAccess",e=>e.input_tokens]),output:_optionalChain$U([c,"access",e=>e.usage,"optionalAccess",e=>e.output_tokens])}})]),chatStreamBuilder(_optionalChain$U([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_optionalChain$U([c,"access",e=>e.content,"access",e=>e.map,"call",e=>e(e=>"text"===e.type?e.text:""),"optionalAccess",e=>e.join,"call",e=>e("\n")])))}}}var objectToString$2=Object.prototype.toString,isArray$1=Array.isArray||function(e){return"[object Array]"===objectToString$2.call(e)};function isFunction$1(e){return"function"==typeof e}function typeStr(e){return isArray$1(e)?"array":typeof e}function escapeRegExp(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(e,t){return null!=e&&"object"==typeof e&&t in e}function primitiveHasOwnProperty(e,t){
1900
1900
  return null!=e&&"object"!=typeof e&&e.hasOwnProperty&&e.hasOwnProperty(t)}var regExpTest=RegExp.prototype.test;function testRegExp(e,t){return regExpTest.call(e,t)}var nonSpaceRe=/\S/;function isWhitespace(e){return!testRegExp(nonSpaceRe,e)}var entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function escapeHtml$1(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return entityMap[e]})}var whiteRe=/\s*/,spaceRe=/\s+/,equalsRe=/\s*=/,curlyRe=/\s*\}/,tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate$1(e,t){if(!e)return[];var r,n,i,s=!1,o=[],a=[],c=[],u=!1,l=!1,d="",p=0;function h(){if(u&&!l)for(;c.length;)delete a[c.pop()];else c=[];u=!1,l=!1}function A(e){if("string"==typeof e&&(e=e.split(spaceRe,2)),!isArray$1(e)||2!==e.length)throw new Error("Invalid tags: "+e);r=new RegExp(escapeRegExp(e[0])+"\\s*"),n=new RegExp("\\s*"+escapeRegExp(e[1])),i=new RegExp("\\s*"+escapeRegExp("}"+e[1]))}A(t||mustache.tags)
1901
1901
  ;for(var f,g,m,y,E,b,C=new Scanner(e);!C.eos();){if(f=C.pos,m=C.scanUntil(r))for(var I=0,v=m.length;I<v;++I)isWhitespace(y=m.charAt(I))?(c.push(a.length),d+=y):(l=!0,s=!0,d+=" "),a.push(["text",y,f,f+1]),f+=1,"\n"===y&&(h(),d="",p=0,s=!1);if(!C.scan(r))break;if(u=!0,g=C.scan(tagRe)||"name",C.scan(whiteRe),"="===g?(m=C.scanUntil(equalsRe),C.scan(equalsRe),C.scanUntil(n)):"{"===g?(m=C.scanUntil(i),C.scan(curlyRe),C.scanUntil(n),g="&"):m=C.scanUntil(n),!C.scan(n))throw new Error("Unclosed tag at "+C.pos);if(E=">"==g?[g,m,f,C.pos,d,p,s]:[g,m,f,C.pos],p++,a.push(E),"#"===g||"^"===g)o.push(E);else if("/"===g){if(!(b=o.pop()))throw new Error('Unopened section "'+m+'" at '+f);if(b[1]!==m)throw new Error('Unclosed section "'+b[1]+'" at '+f)}else"name"===g||"{"===g||"&"===g?l=!0:"="===g&&A(m)}if(h(),b=o.pop())throw new Error('Unclosed section "'+b[1]+'" at '+C.pos);return nestTokens(squashTokens(a))}function squashTokens(e){
1902
1902
  for(var t,r,n=[],i=0,s=e.length;i<s;++i)(t=e[i])&&("text"===t[0]&&r&&"text"===r[0]?(r[1]+=t[1],r[3]=t[3]):(n.push(t),r=t));return n}function nestTokens(e){for(var t,r=[],n=r,i=[],s=0,o=e.length;s<o;++s)switch((t=e[s])[0]){case"#":case"^":n.push(t),i.push(t),n=t[4]=[];break;case"/":i.pop()[5]=t[2],n=i.length>0?i[i.length-1][4]:r;break;default:n.push(t)}return r}function Scanner(e){this.string=e,this.tail=e,this.pos=0}function Context(e,t){this.view=e,this.cache={".":this.view},this.parent=t}function Writer(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}Scanner.prototype.eos=function(){return""===this.tail},Scanner.prototype.scan=function(e){var t=this.tail.match(e);if(!t||0!==t.index)return"";var r=t[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r},Scanner.prototype.scanUntil=function(e){var t,r=this.tail.search(e);switch(r){case-1:t=this.tail,this.tail="";break;case 0:
@@ -1987,15 +1987,15 @@ if(n&&!r){const e=get$ref(n,t);if(void 0!==e)return"$ref"in e&&t.seenRefs.add(e.
1987
1987
  switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(e,r);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(e,r);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(e,r);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(e,r);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(e,r);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef();case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(r);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(e,r);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(e,r);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(e,r);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(e,r);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(e,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(e,r);case ZodFirstPartyTypeKind.ZodEnum:
1988
1988
  return parseEnumDef(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(e,r);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(e,r);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(e,r);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(e,r);case ZodFirstPartyTypeKind.ZodLazy:return parseDef(e.getter()._def,r);case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(e,r);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef();case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(e,r,n);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef();case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef();case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(e,r);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(e,r);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(e,r);case ZodFirstPartyTypeKind.ZodCatch:
1989
1989
  return parseCatchDef(e,r);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(e,r);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:default:return}},addMeta=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),zodToJsonSchema$1=(e,t)=>{const r=getRefs(t),n="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,i=parseDef(e._def,void 0===n?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(i.title=s);const o=(()=>{if(isEmptyObj(r.definitions))return;const e={},t=new Set;for(let n=0;n<500;n++){const n=Object.entries(r.definitions).filter(([e])=>!t.has(e));if(0===n.length)break;for(const[i,s]of n)e[i]=parseDef(zodDef(s),{...r,currentPath:[...r.basePath,r.definitionPath,i]},!0)??{},t.add(i)}return e})(),a=void 0===n?o?{...i,[r.definitionPath]:o
1990
- }:i:"duplicate-ref"===r.nameStrategy?{...i,...o||r.seenRefs.size?{[r.definitionPath]:{...o,...r.seenRefs.size?{[n]:i}:void 0}}:void 0}:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return"jsonSchema7"===r.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===r.target&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function zodToJsonSchema(e,t){return zodToJsonSchema$1(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function zodResponseFormat(e,t,r){return makeParseableResponseFormat({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:zodToJsonSchema(e,{name:t})}},t=>e.parse(JSON.parse(t)))}function _nullishCoalesce$Q(e,t){return null!=e?e:t()}function _optionalChain$U(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
1991
- ("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function handleConfigBase(e){return{temperature:_nullishCoalesce$Q(e.modelTemperature,()=>1),reasoning_effort:e.modelReasoningEffort,model:e.modelName,...e.modelParams}}function modelSuspectOfMinificationBug(e){return e.startsWith("o3")||e.startsWith("o4")}function openAiImpl(e,t){const r={key:_optionalChain$U([e,"access",e=>e.keys,"optionalAccess",e=>e.openAi]),forTesting:e.forTesting,abortSignal:e.abortSignal,userHash:e.userHash,baseUrl:_optionalChain$U([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.openAi]),shareUsageData:e.shareUsageData},n=handleConfigBase(t);if(!r.key)throw new Error("LLM key is missing: try running `tessl login`");const i=new OpenAI({apiKey:r.key,fetch:_optionalChain$U([r,"access",e=>e.forTesting,"optionalAccess",e=>e.openAiFetch]),baseURL:r.baseUrl});return{
1992
- cacheKey:[n.model,String(n.temperature)],streamFromMessages:async(e,t={})=>withSpan("openAiClient.streamFromMessages",async s=>{const o=_optionalChain$U([t,"access",e=>e.traceInfo,"optionalAccess",e=>e.parent])?{"langfuse.traceId":t.traceInfo.parent.traceId,"langfuse.traceUrl":t.traceInfo.parent.getTraceUrl()}:{};let a;s.setAttributes(o),s.setAttribute("streaming",!0),t.respondObject&&(a=zodResponseFormat(t.respondObject.schema,t.respondObject.name)),a&&modelSuspectOfMinificationBug(n.model)&&(e=injectMinificationToMessages(structuredClone(e)));const c="true"===process.env.TESSL_DISABLE_LLM_CACHE,u={stream:!0,messages:e,...t.prediction?{prediction:{type:"content",content:t.prediction}}:{response_format:a},...n,user:r.userHash,...r.baseUrl&&c?{cache:{"no-cache":!0,"no-store":!0}}:{},...!1===r.shareUsageData?{"no-log":!0}:{}},l=r.abortSignal;let d;try{const e={signal:l};d=await observeOpenAI(i,t.traceInfo).chat.completions.create(u,e)}catch(e){
1993
- throw new AggregateError([e],getUserFacingMessageFromError(e))}return chatStreamBuilder(_optionalChain$U([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),async e=>withSpan("openAiClient.streamAsString",async t=>(t.setAttributes(o),streamAsString(d,l,e))))})}}async function streamAsString(e,t,r){let n="";try{for await(const i of e){if(1!==i.choices.length)throw new Error(`expected exactly one choice, got: ${JSON.stringify(i)}`);const e=i.choices[0],s=_optionalChain$U([e,"access",e=>e.delta,"optionalAccess",e=>e.refusal]);if(s)throw new Error(`refusal: ${s}`);const o=_optionalChain$U([e,"access",e=>e.delta,"optionalAccess",e=>e.content]);o&&(_optionalChain$U([t,"optionalAccess",e=>e.throwIfAborted,"call",e=>e()]),await _optionalChain$U([r,"optionalAccess",e=>e.chunk,"call",e=>e(o,_optionalChain$U([i,"access",e=>e.usage,"optionalAccess",e=>e.completion_tokens]))]),n+=o)}}catch(e){const t=new AggregateError([e],"error consuming chat stream")
1994
- ;throw isObscureOpenAIStreamError(e)&&allowRetries(t,{withDelay:!0}),t}return n}function isObscureOpenAIStreamError(e){return e&&"object"==typeof e&&e instanceof Error&&"type"in e&&"APIError"===e.type&&e.message.includes("You can retry")}function _nullishCoalesce$P(e,t){return null!=e?e:t()}function _optionalChain$T(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function cerebrasNoStreamImpl(e,t){const r={key:_optionalChain$T([e,"access",e=>e.keys,"optionalAccess",e=>e.cerebras]),abortSignal:e.abortSignal,userHash:e.userHash,baseUrl:_optionalChain$T([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.cerebras])},n=handleConfigBase(t);if(!r.key)throw new Error("cerebras key is required");const i=new OpenAI({apiKey:r.key,baseURL:r.baseUrl||"https://api.cerebras.ai/v1"});return{
1995
- cacheKey:[n.model,String(n.temperature)],streamFromMessages:async(e,t={})=>withSpan("cerebrasClient.streamFromMessages",async s=>{const o=_optionalChain$T([t,"access",e=>e.traceInfo,"optionalAccess",e=>e.parent])?{"langfuse.traceId":t.traceInfo.parent.traceId,"langfuse.traceUrl":t.traceInfo.parent.getTraceUrl()}:{};let a;s.setAttributes(o),s.setAttribute("streaming",!1),t.respondObject&&(a=zodResponseFormat(t.respondObject.schema,t.respondObject.name));const c={stream:!1,messages:e,...t.prediction?{prediction:{type:"content",content:t.prediction}}:{response_format:a},...n,user:r.userHash},u=r.abortSignal;let l;try{l=await observeOpenAI(i,t.traceInfo).chat.completions.create(c,{signal:u})}catch(e){throw new AggregateError([e],"cerebras request error")}
1996
- return chatStreamBuilder(_optionalChain$T([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_nullishCoalesce$P(_optionalChain$T([l,"access",e=>e.choices,"access",e=>e[0],"optionalAccess",e=>e.message,"optionalAccess",e=>e.content]),()=>"")))})}}function _nullishCoalesce$O(e,t){return null!=e?e:t()}function _optionalChain$S(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function handleConfig$1(e){return{temperature:_nullishCoalesce$O(e.modelTemperature,()=>.6),max_tokens:20480,reasoning_effort:e.modelReasoningEffort,model:e.modelName,...e.modelParams}}function deepseekImpl(e,t){const r=handleConfig$1(t),n={key:_optionalChain$S([e,"access",e=>e.keys,"optionalAccess",e=>e.fireworks]),
1997
- apiEndpoint:_optionalChain$S([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.fireworks])||"https://api.fireworks.ai/inference/v1",forTesting:e.forTesting,abortSignal:e.abortSignal};if(!n.key)throw new Error("deepseek key is required");const i=new OpenAI({apiKey:n.key,fetch:_optionalChain$S([n,"access",e=>e.forTesting,"optionalAccess",e=>e.openAiFetch]),baseURL:n.apiEndpoint});return{cacheKey:[r.model,String(r.temperature)],async streamFromMessages(e,t={}){const s=translateMessagesToArray(structuredClone(e)),o=_optionalChain$S([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);o&&appendSchema(s,o);const a={messages:s,response_format:undefined,...r,stream:!1},c=n.abortSignal;let u;try{u=await observeOpenAI(i,t.traceInfo).chat.completions.create(a,{signal:c})}catch(e){throw new AggregateError([e],"deepseek stream setup error")}
1998
- const l=removeThinking(_nullishCoalesce$O(_optionalChain$S([u,"access",e=>e.choices,"access",e=>e[0],"optionalAccess",e=>e.message,"optionalAccess",e=>e.content]),()=>""));return chatStreamBuilder(_optionalChain$S([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_nullishCoalesce$O(l,()=>"")))}}}var safeBuffer={exports:{}},hasRequiredSafeBuffer,paramBytesForAlg_1,hasRequiredParamBytesForAlg,ecdsaSigFormatter,hasRequiredEcdsaSigFormatter;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,function(e,t){var r=require$$0$j,n=r.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s),s.prototype=Object.create(n.prototype),i(n,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},s.alloc=function(e,t,r){
1990
+ }:i:"duplicate-ref"===r.nameStrategy?{...i,...o||r.seenRefs.size?{[r.definitionPath]:{...o,...r.seenRefs.size?{[n]:i}:void 0}}:void 0}:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return"jsonSchema7"===r.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"===r.target&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function zodToJsonSchema(e,t){return zodToJsonSchema$1(e,{openaiStrictMode:!0,name:t.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function zodResponseFormat(e,t,r){return makeParseableResponseFormat({type:"json_schema",json_schema:{...r,name:t,strict:!0,schema:zodToJsonSchema(e,{name:t})}},t=>e.parse(JSON.parse(t)))}function _nullishCoalesce$Q(e,t){return null!=e?e:t()}function _optionalChain$T(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
1991
+ ("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function handleConfigBase(e){return{temperature:_nullishCoalesce$Q(e.modelTemperature,()=>1),reasoning_effort:e.modelReasoningEffort,model:e.modelName,...e.modelParams}}function modelSuspectOfMinificationBug(e){return e.startsWith("o3")||e.startsWith("o4")}function openAiImpl(e,t){const r={key:_optionalChain$T([e,"access",e=>e.keys,"optionalAccess",e=>e.openAi]),forTesting:e.forTesting,abortSignal:e.abortSignal,userHash:e.userHash,baseUrl:_optionalChain$T([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.openAi]),shareUsageData:e.shareUsageData},n=handleConfigBase(t);if(!r.key)throw new Error("LLM key is missing: try running `tessl login`");const i=new OpenAI({apiKey:r.key,fetch:_optionalChain$T([r,"access",e=>e.forTesting,"optionalAccess",e=>e.openAiFetch]),baseURL:r.baseUrl});return{
1992
+ cacheKey:[n.model,String(n.temperature)],streamFromMessages:async(e,t={})=>withSpan("openAiClient.streamFromMessages",async s=>{const o=_optionalChain$T([t,"access",e=>e.traceInfo,"optionalAccess",e=>e.parent])?{"langfuse.traceId":t.traceInfo.parent.traceId,"langfuse.traceUrl":t.traceInfo.parent.getTraceUrl()}:{};let a;s.setAttributes(o),s.setAttribute("streaming",!0),t.respondObject&&(a=zodResponseFormat(t.respondObject.schema,t.respondObject.name)),a&&modelSuspectOfMinificationBug(n.model)&&(e=injectMinificationToMessages(structuredClone(e)));const c="true"===process.env.TESSL_DISABLE_LLM_CACHE,u={stream:!0,messages:e,...t.prediction?{prediction:{type:"content",content:t.prediction}}:{response_format:a},...n,user:r.userHash,...r.baseUrl&&c?{cache:{"no-cache":!0,"no-store":!0}}:{},...!1===r.shareUsageData?{"no-log":!0}:{}},l=r.abortSignal;let d;try{const e={signal:l};d=await observeOpenAI(i,t.traceInfo).chat.completions.create(u,e)}catch(e){
1993
+ throw new AggregateError([e],getUserFacingMessageFromError(e))}return chatStreamBuilder(_optionalChain$T([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),async e=>withSpan("openAiClient.streamAsString",async t=>(t.setAttributes(o),streamAsString(d,l,e))))})}}async function streamAsString(e,t,r){let n="";try{for await(const i of e){if(1!==i.choices.length)throw new Error(`expected exactly one choice, got: ${JSON.stringify(i)}`);const e=i.choices[0],s=_optionalChain$T([e,"access",e=>e.delta,"optionalAccess",e=>e.refusal]);if(s)throw new Error(`refusal: ${s}`);const o=_optionalChain$T([e,"access",e=>e.delta,"optionalAccess",e=>e.content]);o&&(_optionalChain$T([t,"optionalAccess",e=>e.throwIfAborted,"call",e=>e()]),await _optionalChain$T([r,"optionalAccess",e=>e.chunk,"call",e=>e(o,_optionalChain$T([i,"access",e=>e.usage,"optionalAccess",e=>e.completion_tokens]))]),n+=o)}}catch(e){const t=new AggregateError([e],"error consuming chat stream")
1994
+ ;throw isObscureOpenAIStreamError(e)&&allowRetries(t,{withDelay:!0}),t}return n}function isObscureOpenAIStreamError(e){return e&&"object"==typeof e&&e instanceof Error&&"type"in e&&"APIError"===e.type&&e.message.includes("You can retry")}function _nullishCoalesce$P(e,t){return null!=e?e:t()}function _optionalChain$S(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function cerebrasNoStreamImpl(e,t){const r={key:_optionalChain$S([e,"access",e=>e.keys,"optionalAccess",e=>e.cerebras]),abortSignal:e.abortSignal,userHash:e.userHash,baseUrl:_optionalChain$S([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.cerebras])},n=handleConfigBase(t);if(!r.key)throw new Error("cerebras key is required");const i=new OpenAI({apiKey:r.key,baseURL:r.baseUrl||"https://api.cerebras.ai/v1"});return{
1995
+ cacheKey:[n.model,String(n.temperature)],streamFromMessages:async(e,t={})=>withSpan("cerebrasClient.streamFromMessages",async s=>{const o=_optionalChain$S([t,"access",e=>e.traceInfo,"optionalAccess",e=>e.parent])?{"langfuse.traceId":t.traceInfo.parent.traceId,"langfuse.traceUrl":t.traceInfo.parent.getTraceUrl()}:{};let a;s.setAttributes(o),s.setAttribute("streaming",!1),t.respondObject&&(a=zodResponseFormat(t.respondObject.schema,t.respondObject.name));const c={stream:!1,messages:e,...t.prediction?{prediction:{type:"content",content:t.prediction}}:{response_format:a},...n,user:r.userHash},u=r.abortSignal;let l;try{l=await observeOpenAI(i,t.traceInfo).chat.completions.create(c,{signal:u})}catch(e){throw new AggregateError([e],"cerebras request error")}
1996
+ return chatStreamBuilder(_optionalChain$S([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_nullishCoalesce$P(_optionalChain$S([l,"access",e=>e.choices,"access",e=>e[0],"optionalAccess",e=>e.message,"optionalAccess",e=>e.content]),()=>"")))})}}function _nullishCoalesce$O(e,t){return null!=e?e:t()}function _optionalChain$R(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function handleConfig$1(e){return{temperature:_nullishCoalesce$O(e.modelTemperature,()=>.6),max_tokens:20480,reasoning_effort:e.modelReasoningEffort,model:e.modelName,...e.modelParams}}function deepseekImpl(e,t){const r=handleConfig$1(t),n={key:_optionalChain$R([e,"access",e=>e.keys,"optionalAccess",e=>e.fireworks]),
1997
+ apiEndpoint:_optionalChain$R([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.fireworks])||"https://api.fireworks.ai/inference/v1",forTesting:e.forTesting,abortSignal:e.abortSignal};if(!n.key)throw new Error("deepseek key is required");const i=new OpenAI({apiKey:n.key,fetch:_optionalChain$R([n,"access",e=>e.forTesting,"optionalAccess",e=>e.openAiFetch]),baseURL:n.apiEndpoint});return{cacheKey:[r.model,String(r.temperature)],async streamFromMessages(e,t={}){const s=translateMessagesToArray(structuredClone(e)),o=_optionalChain$R([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);o&&appendSchema(s,o);const a={messages:s,response_format:undefined,...r,stream:!1},c=n.abortSignal;let u;try{u=await observeOpenAI(i,t.traceInfo).chat.completions.create(a,{signal:c})}catch(e){throw new AggregateError([e],"deepseek stream setup error")}
1998
+ const l=removeThinking(_nullishCoalesce$O(_optionalChain$R([u,"access",e=>e.choices,"access",e=>e[0],"optionalAccess",e=>e.message,"optionalAccess",e=>e.content]),()=>""));return chatStreamBuilder(_optionalChain$R([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_nullishCoalesce$O(l,()=>"")))}}}var safeBuffer={exports:{}},hasRequiredSafeBuffer,paramBytesForAlg_1,hasRequiredParamBytesForAlg,ecdsaSigFormatter,hasRequiredEcdsaSigFormatter;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,function(e,t){var r=require$$0$j,n=r.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s),s.prototype=Object.create(n.prototype),i(n,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},s.alloc=function(e,t,r){
1999
1999
  if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=n(e);return void 0!==t?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}}(safeBuffer,safeBuffer.exports)),safeBuffer.exports}function requireParamBytesForAlg(){if(hasRequiredParamBytesForAlg)return paramBytesForAlg_1;function e(e){return(e/8|0)+(e%8==0?0:1)}hasRequiredParamBytesForAlg=1;var t={ES256:e(256),ES384:e(384),ES512:e(521)};return paramBytesForAlg_1=function(e){var r=t[e];if(r)return r;throw new Error('Unknown algorithm "'+e+'"')}}function requireEcdsaSigFormatter(){if(hasRequiredEcdsaSigFormatter)return ecdsaSigFormatter;hasRequiredEcdsaSigFormatter=1;var e=requireSafeBuffer().Buffer,t=requireParamBytesForAlg(),r=128;function n(t){if(e.isBuffer(t))return t
2000
2000
  ;if("string"==typeof t)return e.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function i(e,t,n){for(var i=0;t+i<n&&0===e[t+i];)++i;return e[t+i]>=r&&--i,i}return ecdsaSigFormatter={derToJose:function(r,i){r=n(r);var s=t(i),o=s+1,a=r.length,c=0;if(48!==r[c++])throw new Error('Could not find expected "seq"');var u=r[c++];if(129===u&&(u=r[c++]),a-c<u)throw new Error('"seq" specified length of "'+u+'", only "'+(a-c)+'" remaining');if(2!==r[c++])throw new Error('Could not find expected "int" for "r"');var l=r[c++];if(a-c-2<l)throw new Error('"r" specified length of "'+l+'", only "'+(a-c-2)+'" available');if(o<l)throw new Error('"r" specified length of "'+l+'", max of "'+o+'" is acceptable');var d=c;if(c+=l,2!==r[c++])throw new Error('Could not find expected "int" for "s"');var p=r[c++];if(a-c!==p)throw new Error('"s" specified length of "'+p+'", expected "'+(a-c)+'"')
2001
2001
  ;if(o<p)throw new Error('"s" specified length of "'+p+'", max of "'+o+'" is acceptable');var h=c;if((c+=p)!==a)throw new Error('Expected to consume entire buffer, but "'+(a-c)+'" bytes remain');var A=s-l,f=s-p,g=e.allocUnsafe(A+l+f+p);for(c=0;c<A;++c)g[c]=0;r.copy(g,c,d+Math.max(-A,0),d+l);for(var m=c=s;c<m+f;++c)g[c]=0;return r.copy(g,c,h+Math.max(-f,0),h+p),g=function(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(g=g.toString("base64")),g},joseToDer:function(s,o){s=n(s);var a=t(o),c=s.length;if(c!==2*a)throw new TypeError('"'+o+'" signatures must be "'+2*a+'" bytes, saw "'+c+'"');var u=i(s,0,a),l=i(s,a,s.length),d=a-u,p=a-l,h=2+d+1+1+p,A=h<r,f=e.allocUnsafe((A?2:3)+h),g=0;return f[g++]=48,A?f[g++]=h:(f[g++]=129,f[g++]=255&h),f[g++]=2,f[g++]=d,u<0?(f[g++]=0,g+=s.copy(f,g,0,a)):g+=s.copy(f,g,u,a),f[g++]=2,f[g++]=p,l<0?(f[g++]=0,s.copy(f,g,a)):s.copy(f,g,a+l),f}},ecdsaSigFormatter}var dist$1={},util$8={},hasRequiredUtil$8;function requireUtil$8(){
@@ -2074,22 +2074,22 @@ e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodInter
2074
2074
  ;types$2.ostring=()=>Ie().optional();types$2.onumber=()=>ve().optional();return types$2.oboolean=()=>_e().optional(),types$2.coerce={string:e=>F.create({...e,coerce:!0}),number:e=>k.create({...e,coerce:!0}),boolean:e=>N.create({...e,coerce:!0}),bigint:e=>$.create({...e,coerce:!0}),date:e=>P.create({...e,coerce:!0})},types$2.NEVER=n.INVALID,types$2}function requireExternal(){return hasRequiredExternal||(hasRequiredExternal=1,e=external,t=external&&external.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=external&&external.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)},Object.defineProperty(e,"__esModule",{value:!0}),r(requireErrors$3(),e),r(requireParseUtil(),e),
2075
2075
  r(requireTypeAliases(),e),r(requireUtil$7(),e),r(requireTypes$2(),e),r(requireZodError(),e)),external;var e,t,r}function requireZod(){return hasRequiredZod||(hasRequiredZod=1,function(e){var t=zod&&zod.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=zod&&zod.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=zod&&zod.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&t(n,e,i);return r(n,e),n},i=zod&&zod.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),
2076
2076
  e.z=void 0;const s=n(requireExternal());e.z=s,i(requireExternal(),e),e.default=s}(zod)),zod}function requireDist$1(){if(hasRequiredDist$1)return dist$1;hasRequiredDist$1=1,Object.defineProperty(dist$1,"__esModule",{value:!0}),dist$1.toGeminiSchema=function r(n){switch((0,e.getZodType)(n)){case"ZodArray":return t({type:e.SchemaType.ARRAY,items:r(n.element)},n);case"ZodObject":const i={},s=[];return Object.entries(n.shape).forEach(([t,n])=>{i[t]=r(n),"ZodOptional"!==(0,e.getZodType)(n)&&s.push(t)}),t({type:e.SchemaType.OBJECT,properties:i,required:s.length>0?s:void 0},n);case"ZodString":return t({type:e.SchemaType.STRING},n);case"ZodNumber":return t({type:e.SchemaType.NUMBER},n);case"ZodBoolean":return t({type:e.SchemaType.BOOLEAN},n);case"ZodEnum":return t({type:e.SchemaType.STRING,enum:n._def.values},n);case"ZodDefault":case"ZodNullable":case"ZodOptional":return t({...r(n._def.innerType),nullable:!0},n);case"ZodLiteral":return t({type:e.SchemaType.STRING,enum:[n._def.value]},n)
2077
- ;default:return t({type:e.SchemaType.OBJECT,nullable:!0},n)}},dist$1.toZodSchema=function t(n){const i=requireZod();switch(n.type){case e.SchemaType.ARRAY:return r(i.array(t(n.items)),n);case e.SchemaType.OBJECT:const s={};return Object.entries(n.properties).forEach(([e,r])=>{let i=t(r);n.required&&n.required.includes(e)||(i=i.optional()),s[e]=i}),r(i.object(s),n);case e.SchemaType.STRING:return r(i.string(),n);case e.SchemaType.NUMBER:case e.SchemaType.INTEGER:return r(i.number(),n);case e.SchemaType.BOOLEAN:return r(i.boolean(),n);default:return r(i.any(),n)}};const e=requireUtil$8();function t(e,t){return void 0===e.nullable&&(e.nullable=t.isOptional()),t.description&&(e.description=t.description),e}function r(e,t){return t.nullable&&(e=e.nullable()),t.description&&(e=e.describe(t.description)),e}return dist$1}function _nullishCoalesce$N(e,t){return null!=e?e:t()}function _optionalChain$R(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
2078
- ("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function handleConfig(e){return{temperature:_nullishCoalesce$N(e.modelTemperature,()=>.6),max_tokens:16384,reasoning_effort:e.modelReasoningEffort,model:e.modelName,...e.modelParams}}function llama3_1__405bImpl(e,t){const r=handleConfig(t),n={key:_optionalChain$R([e,"access",e=>e.keys,"optionalAccess",e=>e.fireworks]),apiEndpoint:_optionalChain$R([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.fireworks])||"https://api.fireworks.ai/inference/v1",forTesting:e.forTesting,abortSignal:e.abortSignal};if(!n.key)throw new Error("llama key is required");const i=new OpenAI({apiKey:n.key,fetch:_optionalChain$R([n,"access",e=>e.forTesting,"optionalAccess",e=>e.openAiFetch]),baseURL:n.apiEndpoint});return{cacheKey:[r.model,String(r.temperature)],async streamFromMessages(e,t={}){
2079
- const s=translateMessagesToArray(structuredClone(e)),o=_optionalChain$R([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);o&&appendSchema(s,o);const a={stream:!1,messages:s,response_format:undefined,...r},c=n.abortSignal;let u;try{u=await observeOpenAI(i,t.traceInfo).chat.completions.create(a,{signal:c})}catch(e){throw new AggregateError([e],"llama stream setup error")}return chatStreamBuilder(_optionalChain$R([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_nullishCoalesce$N(_optionalChain$R([u,"access",e=>e.choices,"access",e=>e[0],"optionalAccess",e=>e.message,"optionalAccess",e=>e.content]),()=>"")))}}}function _nullishCoalesce$M(e,t){return null!=e?e:t()}function _optionalChain$Q(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}
2080
- return r}function openAiNoStreamImpl(e,t){const r={key:_optionalChain$Q([e,"access",e=>e.keys,"optionalAccess",e=>e.openAi]),forTesting:e.forTesting,abortSignal:e.abortSignal,userHash:e.userHash,baseUrl:_optionalChain$Q([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.openAi]),shareUsageData:e.shareUsageData},n=handleConfigBase(t);if(!r.key)throw new Error("LLM key is missing: try running `tessl login`");const i=new OpenAI({apiKey:r.key,fetch:_optionalChain$Q([r,"access",e=>e.forTesting,"optionalAccess",e=>e.openAiFetch]),baseURL:r.baseUrl});return{cacheKey:[n.model,String(n.temperature)],streamFromMessages:async(e,t={})=>withSpan("openAiClient.streamFromMessages",async s=>{const o=_optionalChain$Q([t,"access",e=>e.traceInfo,"optionalAccess",e=>e.parent])?{"langfuse.traceId":t.traceInfo.parent.traceId,"langfuse.traceUrl":t.traceInfo.parent.getTraceUrl()}:{};let a;s.setAttributes(o),s.setAttribute("streaming",!1),
2081
- t.respondObject&&(a=zodResponseFormat(t.respondObject.schema,t.respondObject.name));const c={stream:!1,messages:e,...t.prediction?{prediction:{type:"content",content:t.prediction}}:{response_format:a},...n,user:r.userHash,...!1===r.shareUsageData?{"no-log":!0}:{}},u=r.abortSignal;let l;try{l=await observeOpenAI(i,t.traceInfo).chat.completions.create(c,{signal:u})}catch(e){throw new AggregateError([e],"openai request error")}return chatStreamBuilder(_optionalChain$Q([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_nullishCoalesce$M(_optionalChain$Q([l,"access",e=>e.choices,"access",e=>e[0],"optionalAccess",e=>e.message,"optionalAccess",e=>e.content]),()=>"")))})}}function _optionalChain$P(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
2082
- requireDist$1();const CLIENTS=["anthropic","bedrock","cerebras","deepseek","google-no-stream","llama","openai","openai-no-stream"],clientMap={anthropic:anthropicImpl,bedrock:throwUnavailableInThisVersion,cerebras:cerebrasNoStreamImpl,deepseek:deepseekImpl,"google-no-stream":throwUnavailableInThisVersion,llama:llama3_1__405bImpl,openai:openAiImpl,"openai-no-stream":openAiNoStreamImpl};function createLlmClient(e,t){const{abortSignal:r}=e;if(!t.modelClient&&t.modelName&&isEasyModelAlias(t.modelName)){const e=easyModelAliases[t.modelName];t.modelClient="openai-maybe-stream"===e?t.skipStreaming?"openai-no-stream":"openai":e,t.modelParams??={},t.modelParams.model=t.modelName}if(!t.modelClient&&t.modelName&&isComplicatedModelAlias(t.modelName)){_optionalChain$P([complicatedModelAliases[t.modelName],"optionalCall",e=>e(t)])}t.modelClient||(t.modelClient=t.skipStreaming?"openai-no-stream":"openai",t.modelParams??={},t.modelParams.model=t.modelName);let n=(0,clientMap[t.modelClient])(e,t)
2083
- ;n=withTextValidation(n);const i=_optionalChain$P([e,"access",e=>e.cacheWith,"optionalAccess",e=>e.fs]);i&&(n=cacheWrapper(n,r,async(e,t)=>fsCache(i,e,t)));const s=_optionalChain$P([e,"access",e=>e.cacheWith,"optionalAccess",e=>e.redis]);return s&&(n=cacheWrapper(n,r,async(e,t)=>redisCache(s,e,t))),n}function withTextValidation(e){return{async streamFromMessages(t,r){for(const e of t)try{assertSafeText(e.content)}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Refusing to send data with unsafe characters to LLM: ${t}`)}return e.streamFromMessages(t,r)},cacheKey:e.cacheKey}}function withDefaultTraceInfo(e,t){return{streamFromMessages:async(r,n)=>e.streamFromMessages(r,{...n,traceInfo:{parent:t,..._optionalChain$P([n,"optionalAccess",e=>e.traceInfo])}}),cacheKey:e.cacheKey}}function zodLiteralUnion(e){const t=e.map(e=>literalType(e));return unionType(t,{errorMap:(e,t)=>"invalid_union"===e.code?{message:`Invalid value provided for ${e.path.join(".")}`}:{message:""
2084
- }})}function _nullishCoalesce$L(e,t){return null!=e?e:t()}function _optionalChain$O(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const defaultDefaults={modelName:getDefaultModel(),modelTemperature:1,skipStreaming:!1},ModelParamSchema=Type.Object({modelName:Type.Optional(Type.String()),modelClient:Type.Optional(Type.Union([Type.Literal("anthropic"),Type.Literal("bedrock"),Type.Literal("cerebras"),Type.Literal("deepseek"),Type.Literal("google-no-stream"),Type.Literal("llama"),Type.Literal("openai"),Type.Literal("openai-no-stream")])),modelParams:Type.Optional(Type.Record(Type.String(),Type.Unknown())),modelTemperature:Type.Optional(Type.Number()),modelReasoningEffort:Type.Optional(Type.String()),skipStreaming:Type.Optional(Type.Boolean())}),cmdParamSchema=objectType({
2077
+ ;default:return t({type:e.SchemaType.OBJECT,nullable:!0},n)}},dist$1.toZodSchema=function t(n){const i=requireZod();switch(n.type){case e.SchemaType.ARRAY:return r(i.array(t(n.items)),n);case e.SchemaType.OBJECT:const s={};return Object.entries(n.properties).forEach(([e,r])=>{let i=t(r);n.required&&n.required.includes(e)||(i=i.optional()),s[e]=i}),r(i.object(s),n);case e.SchemaType.STRING:return r(i.string(),n);case e.SchemaType.NUMBER:case e.SchemaType.INTEGER:return r(i.number(),n);case e.SchemaType.BOOLEAN:return r(i.boolean(),n);default:return r(i.any(),n)}};const e=requireUtil$8();function t(e,t){return void 0===e.nullable&&(e.nullable=t.isOptional()),t.description&&(e.description=t.description),e}function r(e,t){return t.nullable&&(e=e.nullable()),t.description&&(e=e.describe(t.description)),e}return dist$1}function _nullishCoalesce$N(e,t){return null!=e?e:t()}function _optionalChain$Q(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
2078
+ ("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function handleConfig(e){return{temperature:_nullishCoalesce$N(e.modelTemperature,()=>.6),max_tokens:16384,reasoning_effort:e.modelReasoningEffort,model:e.modelName,...e.modelParams}}function llama3_1__405bImpl(e,t){const r=handleConfig(t),n={key:_optionalChain$Q([e,"access",e=>e.keys,"optionalAccess",e=>e.fireworks]),apiEndpoint:_optionalChain$Q([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.fireworks])||"https://api.fireworks.ai/inference/v1",forTesting:e.forTesting,abortSignal:e.abortSignal};if(!n.key)throw new Error("llama key is required");const i=new OpenAI({apiKey:n.key,fetch:_optionalChain$Q([n,"access",e=>e.forTesting,"optionalAccess",e=>e.openAiFetch]),baseURL:n.apiEndpoint});return{cacheKey:[r.model,String(r.temperature)],async streamFromMessages(e,t={}){
2079
+ const s=translateMessagesToArray(structuredClone(e)),o=_optionalChain$Q([t,"optionalAccess",e=>e.respondObject,"optionalAccess",e=>e.schema]);o&&appendSchema(s,o);const a={stream:!1,messages:s,response_format:undefined,...r},c=n.abortSignal;let u;try{u=await observeOpenAI(i,t.traceInfo).chat.completions.create(a,{signal:c})}catch(e){throw new AggregateError([e],"llama stream setup error")}return chatStreamBuilder(_optionalChain$Q([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_nullishCoalesce$N(_optionalChain$Q([u,"access",e=>e.choices,"access",e=>e[0],"optionalAccess",e=>e.message,"optionalAccess",e=>e.content]),()=>"")))}}}function _nullishCoalesce$M(e,t){return null!=e?e:t()}function _optionalChain$P(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}
2080
+ return r}function openAiNoStreamImpl(e,t){const r={key:_optionalChain$P([e,"access",e=>e.keys,"optionalAccess",e=>e.openAi]),forTesting:e.forTesting,abortSignal:e.abortSignal,userHash:e.userHash,baseUrl:_optionalChain$P([e,"access",e=>e.apiEndpoint,"optionalAccess",e=>e.openAi]),shareUsageData:e.shareUsageData},n=handleConfigBase(t);if(!r.key)throw new Error("LLM key is missing: try running `tessl login`");const i=new OpenAI({apiKey:r.key,fetch:_optionalChain$P([r,"access",e=>e.forTesting,"optionalAccess",e=>e.openAiFetch]),baseURL:r.baseUrl});return{cacheKey:[n.model,String(n.temperature)],streamFromMessages:async(e,t={})=>withSpan("openAiClient.streamFromMessages",async s=>{const o=_optionalChain$P([t,"access",e=>e.traceInfo,"optionalAccess",e=>e.parent])?{"langfuse.traceId":t.traceInfo.parent.traceId,"langfuse.traceUrl":t.traceInfo.parent.getTraceUrl()}:{};let a;s.setAttributes(o),s.setAttribute("streaming",!1),
2081
+ t.respondObject&&(a=zodResponseFormat(t.respondObject.schema,t.respondObject.name));const c={stream:!1,messages:e,...t.prediction?{prediction:{type:"content",content:t.prediction}}:{response_format:a},...n,user:r.userHash,...!1===r.shareUsageData?{"no-log":!0}:{}},u=r.abortSignal;let l;try{l=await observeOpenAI(i,t.traceInfo).chat.completions.create(c,{signal:u})}catch(e){throw new AggregateError([e],"openai request error")}return chatStreamBuilder(_optionalChain$P([t,"access",e=>e.respondObject,"optionalAccess",e=>e.schema]),nonStreamedAsString(_nullishCoalesce$M(_optionalChain$P([l,"access",e=>e.choices,"access",e=>e[0],"optionalAccess",e=>e.message,"optionalAccess",e=>e.content]),()=>"")))})}}function _optionalChain$O(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
2082
+ requireDist$1();const CLIENTS=["anthropic","bedrock","cerebras","deepseek","google-no-stream","llama","openai","openai-no-stream"],clientMap={anthropic:anthropicImpl,bedrock:throwUnavailableInThisVersion,cerebras:cerebrasNoStreamImpl,deepseek:deepseekImpl,"google-no-stream":throwUnavailableInThisVersion,llama:llama3_1__405bImpl,openai:openAiImpl,"openai-no-stream":openAiNoStreamImpl};function createLlmClient(e,t){const{abortSignal:r}=e;if(!t.modelClient&&t.modelName&&isEasyModelAlias(t.modelName)){const e=easyModelAliases[t.modelName];t.modelClient="openai-maybe-stream"===e?t.skipStreaming?"openai-no-stream":"openai":e,t.modelParams??={},t.modelParams.model=t.modelName}if(!t.modelClient&&t.modelName&&isComplicatedModelAlias(t.modelName)){_optionalChain$O([complicatedModelAliases[t.modelName],"optionalCall",e=>e(t)])}t.modelClient||(t.modelClient=t.skipStreaming?"openai-no-stream":"openai",t.modelParams??={},t.modelParams.model=t.modelName);let n=(0,clientMap[t.modelClient])(e,t)
2083
+ ;n=withTextValidation(n);const i=_optionalChain$O([e,"access",e=>e.cacheWith,"optionalAccess",e=>e.fs]);i&&(n=cacheWrapper(n,r,async(e,t)=>fsCache(i,e,t)));const s=_optionalChain$O([e,"access",e=>e.cacheWith,"optionalAccess",e=>e.redis]);return s&&(n=cacheWrapper(n,r,async(e,t)=>redisCache(s,e,t))),n}function withTextValidation(e){return{async streamFromMessages(t,r){for(const e of t)try{assertSafeText(e.content)}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Refusing to send data with unsafe characters to LLM: ${t}`)}return e.streamFromMessages(t,r)},cacheKey:e.cacheKey}}function withDefaultTraceInfo(e,t){return{streamFromMessages:async(r,n)=>e.streamFromMessages(r,{...n,traceInfo:{parent:t,..._optionalChain$O([n,"optionalAccess",e=>e.traceInfo])}}),cacheKey:e.cacheKey}}function zodLiteralUnion(e){const t=e.map(e=>literalType(e));return unionType(t,{errorMap:(e,t)=>"invalid_union"===e.code?{message:`Invalid value provided for ${e.path.join(".")}`}:{message:""
2084
+ }})}function _nullishCoalesce$L(e,t){return null!=e?e:t()}function _optionalChain$N(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const defaultDefaults={modelName:getDefaultModel(),modelTemperature:1,skipStreaming:!1},ModelParamSchema=Type.Object({modelName:Type.Optional(Type.String()),modelClient:Type.Optional(Type.Union([Type.Literal("anthropic"),Type.Literal("bedrock"),Type.Literal("cerebras"),Type.Literal("deepseek"),Type.Literal("google-no-stream"),Type.Literal("llama"),Type.Literal("openai"),Type.Literal("openai-no-stream")])),modelParams:Type.Optional(Type.Record(Type.String(),Type.Unknown())),modelTemperature:Type.Optional(Type.Number()),modelReasoningEffort:Type.Optional(Type.String()),skipStreaming:Type.Optional(Type.Boolean())}),cmdParamSchema=objectType({
2085
2085
  cloud:booleanType().optional().default(!1).describe("Enables cloud execution of tool; defaults to false")}),getModelNameSchema=()=>{const e=getModelAliases(),t=getDefaultModel(),r=getModelPrefix();return zodLiteralUnion(e).default(t).describe(`The model to use (one of: ${r}auto, ${r}anthropic-reasoning, ${r}openai-reasoning)`)},modelParamSchema=objectType({modelName:getModelNameSchema(),modelClient:zodLiteralUnion(CLIENTS).optional().describe("The name of the LLM provider - use for access models not available via modelName"),modelParams:recordType(stringType(),unknownType()).optional().describe("The parameters that should be passed to the model"),modelTemperature:numberType().optional().default(1).describe("Controls randomness in output; higher means more creative"),modelReasoningEffort:zodLiteralUnion(["low","medium","high"]).optional().describe("Determines how much computation the model devotes to analyzing the prompt before responding"),
2086
2086
  skipStreaming:booleanType().optional().default(!1).describe("If enabled, disables streaming and returns full output at once")}),getCliModelParamSchema=()=>objectType({modelName:getModelNameSchema()}).strict(),Defaults=ModelParamSchema,reqSchema=objectType({defaults:modelParamSchema.optional().default({}),steps:arrayType(objectType({name:stringType(),params:recordType(stringType(),unknownType()).optional()}))}),Req=Type.Object({defaults:Type.Optional(Defaults),steps:Type.Array(Type.Object({name:Type.String(),params:Type.Optional(Type.Record(Type.String(),Type.Unknown()))}))});function loadReq(e){const t=distExports.parse(e);strictCheck(Req,t),t.defaults=_nullishCoalesce$L(t.defaults,()=>structuredClone(defaultDefaults));const r=t;for(const[e,t]of entriesOf(defaultDefaults))e in r.defaults||(r.defaults[e]=structuredClone(t));return r}async function bindTools(e,t){const r=[];for(const{name:n,params:i}of t.steps){const s=await e(n);if(!s)throw new UnknownToolError(n)
2087
- ;const o=setupToolParams(s,i,t.defaults);r.push({tool:s,params:o})}return r}function setupToolParams(e,t,r){const n=validateToolParams$1(e,t);return{...structuredClone(r),...n}}function checkToolCanRun(e,t=isCliBuild()){if(t){if(_optionalChain$O([e,"optionalAccess",e=>e.denyRunIn,"optionalAccess",e=>e.includes,"call",e=>e("cli")]))throw new Error("Tool not available in CLI mode")}else if(_optionalChain$O([e,"optionalAccess",e=>e.denyRunIn,"optionalAccess",e=>e.includes,"call",e=>e("cloud")]))throw new Error("Tool not available in cloud mode")}function filterFalsyParams(e){if(!e)return e;const t={};for(const[r,n]of Object.entries(e))if(!1===n||0===n)t[r]=n;else{if(Array.isArray(n)&&0===n.length)continue;if("string"==typeof n&&""===n)continue;null!=n&&(t[r]=n)}return t}function validateToolParams$1(e,t){const r=filterFalsyParams(t),n=modelParamSchema.merge(e.paramsSchema).safeParse(r);if(!n.success){
2087
+ ;const o=setupToolParams(s,i,t.defaults);r.push({tool:s,params:o})}return r}function setupToolParams(e,t,r){const n=validateToolParams$1(e,t);return{...structuredClone(r),...n}}function checkToolCanRun(e,t=isCliBuild()){if(t){if(_optionalChain$N([e,"optionalAccess",e=>e.denyRunIn,"optionalAccess",e=>e.includes,"call",e=>e("cli")]))throw new Error("Tool not available in CLI mode")}else if(_optionalChain$N([e,"optionalAccess",e=>e.denyRunIn,"optionalAccess",e=>e.includes,"call",e=>e("cloud")]))throw new Error("Tool not available in cloud mode")}function filterFalsyParams(e){if(!e)return e;const t={};for(const[r,n]of Object.entries(e))if(!1===n||0===n)t[r]=n;else{if(Array.isArray(n)&&0===n.length)continue;if("string"==typeof n&&""===n)continue;null!=n&&(t[r]=n)}return t}function validateToolParams$1(e,t){const r=filterFalsyParams(t),n=modelParamSchema.merge(e.paramsSchema).safeParse(r);if(!n.success){
2088
2088
  const t=n.error.errors[0],r=t.path.map(e=>"number"==typeof e?`[${e}]`:e.toString()).join(".");throw new Error(`Error in ${e.name} param ${r}: ${t.message}`)}return n.data||void 0}Set$1("uuid",e=>"string"==typeof e&&!!e.match(UUID_REGEX));var REGEX=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function validate$1(e){return"string"==typeof e&&REGEX.test(e)}const byteToHex=[];for(let e=0;e<256;++e)byteToHex.push((e+256).toString(16).slice(1));function unsafeStringify(e,t=0){return(byteToHex[e[t+0]]+byteToHex[e[t+1]]+byteToHex[e[t+2]]+byteToHex[e[t+3]]+"-"+byteToHex[e[t+4]]+byteToHex[e[t+5]]+"-"+byteToHex[e[t+6]]+byteToHex[e[t+7]]+"-"+byteToHex[e[t+8]]+byteToHex[e[t+9]]+"-"+byteToHex[e[t+10]]+byteToHex[e[t+11]]+byteToHex[e[t+12]]+byteToHex[e[t+13]]+byteToHex[e[t+14]]+byteToHex[e[t+15]]).toLowerCase()}const rnds8Pool=new Uint8Array(256);let poolPtr=rnds8Pool.length;function rng(){
2089
2089
  return poolPtr>rnds8Pool.length-16&&(randomFillSync(rnds8Pool),poolPtr=0),rnds8Pool.slice(poolPtr,poolPtr+=16)}var native={randomUUID};function v4(e,t,r){if(native.randomUUID&&!e)return native.randomUUID();const n=(e=e||{}).random??e.rng?.()??rng();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=15&n[6]|64,n[8]=63&n[8]|128,unsafeStringify(n)}const _state={};function v7(e,t,r){let n;{const e=Date.now(),i=rng();updateV7State(_state,e,i),n=v7Bytes(i,_state.msecs,_state.seq,t,r)}return unsafeStringify(n)}function updateV7State(e,t,r){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++),e}function v7Bytes(e,t,r,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(n){if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`)}else n=new Uint8Array(16),i=0;return t??=Date.now(),r??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],
2090
- n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=255&t,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|3&e[10],n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}function _nullishCoalesce$K(e,t){return null!=e?e:t()}function _optionalChain$N(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function fetchFromLocal(e,t){const r={};for(const n of _nullishCoalesce$K(t,()=>[])){const t=resolve$2(e,n);if(!t.startsWith(e))throw new Error(`bad path outside wd ${t} (${n} not in ${e})`);try{r[n]=await fsp.readFile(t,"utf8")}catch(e){}}return r}function safeEnv(){return _pick(process.env,["PATH","HOME","TMPDIR","USER"])}async function exec$1(e,t){
2091
- const{cmd:r,argv:n,cwd:i,timeoutSecs:s=10,fetchFiles:o=[],mergeStdStreams:a=!1,env:c=safeEnv(),signal:u}=e;if(!r&&!n)throw new Error("Must provide either cmd or argv");if(r&&n)throw new Error("Cannot provide both cmd and argv");const l=resolve$2(i);try{await fsp.access(l)}catch(e){throw new Error(`Working directory does not exist: ${l}`)}const d={cwd:l,stdio:["pipe","pipe","pipe"],env:c,detached:!0};let p,h,A="",f="";function g(){try{h.pid&&process.kill(-h.pid,"SIGTERM")}catch(e){if(!isErrnoException(e))throw e;if("ESRCH"!==e.code&&"EPERM"!==e.code)throw e}}_optionalChain$N([u,"optionalAccess",e=>e.throwIfAborted,"call",e=>e()]),p=r?["/bin/sh","-c",r]:n;const m=setTimeout(()=>{try{g()}catch(e){_optionalChain$N([t,"optionalAccess",e=>e.warn,"call",t=>t({err:e},"unexpected error attempting to clear process group")])}},1e3*s);let y;m.unref();try{y=await new Promise(e=>{h=cp.spawn(p[0],p.slice(1),d),_optionalChain$N([h,"access",e=>e.stdin,"optionalAccess",e=>e.end,"call",e=>e()]),
2092
- h.on("error",t=>e({error:t})),h.on("exit",(t,r)=>e({code:t,signal:r})),_optionalChain$N([h,"access",e=>e.stdout,"optionalAccess",e=>e.setEncoding,"call",e=>e("utf8")]),_optionalChain$N([h,"access",e=>e.stdout,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{A+=e})]),_optionalChain$N([h,"access",e=>e.stderr,"optionalAccess",e=>e.setEncoding,"call",e=>e("utf8")]),_optionalChain$N([h,"access",e=>e.stderr,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{f+=e})]),a&&_optionalChain$N([h,"access",e=>e.stderr,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{A+=e})])})}finally{g(),clearTimeout(m)}const E=await fetchFromLocal(l,o);return{stdout:A,stderr:a?"":f,code:_nullishCoalesce$K(y.code,()=>{}),signal:_nullishCoalesce$K(y.signal,()=>{}),fetchedFiles:E,error:y.error}}var create$1,hasRequiredCreate,src$2,hasRequiredSrc$2;function requireCreate(){if(hasRequiredCreate)return create$1;hasRequiredCreate=1;class e{constructor(e){this.data=e}}class t{enqueue(t){if(this.head){let r=this.head
2090
+ n[i++]=t/1099511627776&255,n[i++]=t/4294967296&255,n[i++]=t/16777216&255,n[i++]=t/65536&255,n[i++]=t/256&255,n[i++]=255&t,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|3&e[10],n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}function _nullishCoalesce$K(e,t){return null!=e?e:t()}function _optionalChain$M(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function fetchFromLocal(e,t){const r={};for(const n of _nullishCoalesce$K(t,()=>[])){const t=resolve$2(e,n);if(!t.startsWith(e))throw new Error(`bad path outside wd ${t} (${n} not in ${e})`);try{r[n]=await fsp.readFile(t,"utf8")}catch(e){}}return r}function safeEnv(){return _pick(process.env,["PATH","HOME","TMPDIR","USER"])}async function exec$1(e,t){
2091
+ const{cmd:r,argv:n,cwd:i,timeoutSecs:s=10,fetchFiles:o=[],mergeStdStreams:a=!1,env:c=safeEnv(),signal:u}=e;if(!r&&!n)throw new Error("Must provide either cmd or argv");if(r&&n)throw new Error("Cannot provide both cmd and argv");const l=resolve$2(i);try{await fsp.access(l)}catch(e){throw new Error(`Working directory does not exist: ${l}`)}const d={cwd:l,stdio:["pipe","pipe","pipe"],env:c,detached:!0};let p,h,A="",f="";function g(){try{h.pid&&process.kill(-h.pid,"SIGTERM")}catch(e){if(!isErrnoException(e))throw e;if("ESRCH"!==e.code&&"EPERM"!==e.code)throw e}}_optionalChain$M([u,"optionalAccess",e=>e.throwIfAborted,"call",e=>e()]),p=r?["/bin/sh","-c",r]:n;const m=setTimeout(()=>{try{g()}catch(e){_optionalChain$M([t,"optionalAccess",e=>e.warn,"call",t=>t({err:e},"unexpected error attempting to clear process group")])}},1e3*s);let y;m.unref();try{y=await new Promise(e=>{h=cp.spawn(p[0],p.slice(1),d),_optionalChain$M([h,"access",e=>e.stdin,"optionalAccess",e=>e.end,"call",e=>e()]),
2092
+ h.on("error",t=>e({error:t})),h.on("exit",(t,r)=>e({code:t,signal:r})),_optionalChain$M([h,"access",e=>e.stdout,"optionalAccess",e=>e.setEncoding,"call",e=>e("utf8")]),_optionalChain$M([h,"access",e=>e.stdout,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{A+=e})]),_optionalChain$M([h,"access",e=>e.stderr,"optionalAccess",e=>e.setEncoding,"call",e=>e("utf8")]),_optionalChain$M([h,"access",e=>e.stderr,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{f+=e})]),a&&_optionalChain$M([h,"access",e=>e.stderr,"optionalAccess",e=>e.on,"call",e=>e("data",e=>{A+=e})])})}finally{g(),clearTimeout(m)}const E=await fetchFromLocal(l,o);return{stdout:A,stderr:a?"":f,code:_nullishCoalesce$K(y.code,()=>{}),signal:_nullishCoalesce$K(y.signal,()=>{}),fetchedFiles:E,error:y.error}}var create$1,hasRequiredCreate,src$2,hasRequiredSrc$2;function requireCreate(){if(hasRequiredCreate)return create$1;hasRequiredCreate=1;class e{constructor(e){this.data=e}}class t{enqueue(t){if(this.head){let r=this.head
2093
2093
  ;for(;r.next;)r=r.next;r.next=new e(t)}else this.head=new e(t)}dequeue(){if(!this.head)return;const e=this.head.data;return this.head=this.head.next,e}size(){let e=0,t=this.head;for(;t;)e++,t=t.next;return e}}return create$1=(e=1)=>{const r=new t,n=()=>{++e;const t=r.dequeue();void 0!==t&&t()},i=t=>{--e,t(n)},s=()=>new Promise(e=>s.isLocked()?r.enqueue(()=>i(e)):i(e));return s.isLocked=()=>0===e,s.awaiting=()=>r.size(),s},create$1}function requireSrc$2(){if(hasRequiredSrc$2)return src$2;hasRequiredSrc$2=1;const e=requireCreate();return src$2={withLock:t=>{const r=e(t),n=async e=>{const t=await r();try{return await e()}finally{t()}};return n.isLocked=r.isLocked,n.awaiting=r.awaiting,n},createLock:e},src$2}var srcExports$2=requireSrc$2(),Utf8Stream_1,hasRequiredUtf8Stream,Parser_1,hasRequiredParser;function stripMarkdown(e){if(0===e.trim().length)return"";if(!/^```/gm.test(e))return e.trimEnd()+"\n";const t=[...e.matchAll(/```\w*\n(.*?)\n```/gs)]
2094
2094
  ;if(0===t.length)throw Error("no code block found",{cause:{text:e}});if(t.length>1)throw Error("multiple code blocks found",{cause:{text:e}});let r=t[0][1];return r.endsWith("\n")||(r+="\n"),r}function requireUtf8Stream(){if(hasRequiredUtf8Stream)return Utf8Stream_1;hasRequiredUtf8Stream=1;const{Transform:e}=Stream$2,{StringDecoder:t}=require$$1$b;return Utf8Stream_1=class extends e{constructor(e){super(Object.assign({},e,{writableObjectMode:!1})),this._buffer=""}_transform(e,r,n){"string"==typeof e?this._transform=this._transformString:(this._stringDecoder=new t,this._transform=this._transformBuffer),this._transform(e,r,n)}_transformBuffer(e,t,r){this._buffer+=this._stringDecoder.write(e),this._processBuffer(r)}_transformString(e,t,r){this._buffer+=e.toString(),this._processBuffer(r)}_processBuffer(e){this._buffer&&(this.push(this._buffer,"utf8"),this._buffer=""),e(null)}_flushInput(){this._stringDecoder&&(this._buffer+=this._stringDecoder.end())}_flush(e){this._flushInput(),
2095
2095
  this._processBuffer(e)}}}function requireParser(){if(hasRequiredParser)return Parser_1;hasRequiredParser=1;const e=requireUtf8Stream(),t={value1:/^(?:[\"\{\[\]\-\d]|true\b|false\b|null\b|\s{1,256})/,string:/^(?:[^\x00-\x1f\"\\]{1,256}|\\[bfnrt\"\\\/]|\\u[\da-fA-F]{4}|\")/,key1:/^(?:[\"\}]|\s{1,256})/,colon:/^(?:\:|\s{1,256})/,comma:/^(?:[\,\]\}]|\s{1,256})/,ws:/^\s{1,256}/,numberStart:/^\d/,numberDigit:/^\d{0,256}/,numberFraction:/^[\.eE]/,numberExponent:/^[eE]/,numberExpSign:/^[-+]/};let r=!0;try{new RegExp(".","y"),r=!1}catch(e){}!r&&Object.keys(t).forEach(e=>{let r=t[e].source.slice(1);"(?:"===r.slice(0,3)&&")"===r.slice(-1)&&(r=r.slice(3,-1)),t[e]=new RegExp(r,"y")}),t.numberFracStart=t.numberExpStart=t.numberStart,t.numberFracDigit=t.numberExpDigit=t.numberDigit;const n={true:!0,false:!1,null:null},i={object:"objectStop",array:"arrayStop","":"done"},s=e=>String.fromCharCode(parseInt(e.slice(2),16)),o={b:"\b",f:"\f",n:"\n",r:"\r",t:"\t",'"':'"',"\\":"\\","/":"/"};class a extends e{
@@ -2105,15 +2105,15 @@ this._packNumbers&&(this._accumulator+=c),this._expect="numberFracDigit",r?this.
2105
2105
  a=t.numberExpSign.exec(this._buffer),!a){if(u<this._buffer.length){this._expect="numberExpStart";break}if(this._done)return e(new Error("Parser has expected an exponent value of a number"));break e}c=a[0],this._streamNumbers&&this.push({name:"numberChunk",value:c}),this._packNumbers&&(this._accumulator+=c),this._expect="numberExpStart",r?this._buffer=this._buffer.slice(c.length):u+=c.length;break;case"numberExpStart":if(t.numberExpStart.lastIndex=u,a=t.numberExpStart.exec(this._buffer),!a){if(u<this._buffer.length||this._done)return e(new Error("Parser cannot parse input: expected an exponent part of a number"));break e}c=a[0],this._streamNumbers&&this.push({name:"numberChunk",value:c}),this._packNumbers&&(this._accumulator+=c),this._expect="numberExpDigit",r?this._buffer=this._buffer.slice(c.length):u+=c.length;break;case"numberExpDigit":if(t.numberExpDigit.lastIndex=u,a=t.numberExpDigit.exec(this._buffer),c=a[0],!c){if(u<this._buffer.length||this._done){this._expect=i[this._parent]
2106
2106
  ;break}break e}this._streamNumbers&&this.push({name:"numberChunk",value:c}),this._packNumbers&&(this._accumulator+=c),r?this._buffer=this._buffer.slice(c.length):u+=c.length;break;case"done":if(t.ws.lastIndex=u,a=t.ws.exec(this._buffer),!a){if(u<this._buffer.length){if(this._jsonStreaming){this._expect="value";break}return e(new Error("Parser cannot parse input: unexpected characters"))}break e}c=a[0],this._open_number&&(this._streamNumbers&&this.push({name:"endNumber"}),this._open_number=!1,this._packNumbers&&(this.push({name:"numberValue",value:this._accumulator}),this._accumulator="")),r?this._buffer=this._buffer.slice(c.length):u+=c.length}!r&&(this._buffer=this._buffer.slice(u)),e(null)}}return a.parser=a.make,a.make.Constructor=a,Parser_1=a}var ParserExports=requireParser(),Parser=getDefaultExportFromCjs(ParserExports);function emptyTyperWithName(e){return{generationName:e,async start(){},async chunk(){},async countTokens(){},async done(){}}}
2107
2107
  function createDefaultTokenCounter({emitMgmt:e,uuid:t},r){return e&&t?{async start(){await e({id:"typingStart",uuid:t})},async countTokens(r){await e({id:"typingCountTokens",uuid:t,totalTokens:r})},async done(){await e({id:"typingDone",uuid:t})},generationName:r}:emptyTyperWithName(r)}function createDefaultTyper(e,t){const{emitMgmt:r,uuid:n}=e;return r&&n?{...createDefaultTokenCounter(e,t),async chunk(e,t){await r({id:"typingChunk",uuid:n,chunk:e,totalTokens:t})}}:emptyTyperWithName(t)}function adaptParserToTyper(e){const t=t=>t&&"not-streamed"!==e[t]?e[t]:emptyTyperWithName(void 0);let r;return async n=>{if(n instanceof AggregateError)throw new AggregateError([n],"parser encountered error");switch(n.name){case"keyValue":r=n.value in e?n.value:void 0,await t(r).start();break;case"stringChunk":await t(r).chunk(n.value);break;case"endString":await t(r).done(),r=void 0}}}function streamingJsonParser(e,t){const r=new Parser,n=[];r.on("data",e=>n.push(e)),
2108
- r.on("error",e=>n.push(new AggregateError([e],"parser error")));const i=async()=>{const t=[...n];n.length=0;for(const r of t)await e(r)},s={async start(){},async chunk(e){await new Promise((t,n)=>r.write(e,e=>e?n(e):t())),await i()},async countTokens(e){},async done(){},generationName:t};return{capture:s,finish:async()=>{await new Promise(e=>r.end(e)),await i()}}}function _nullishCoalesce$J(e,t){return null!=e?e:t()}function _optionalChain$M(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function createHighLevelClient(e,t,r){const{llmFactory:n,logger:i,lfTrace:s,abortSignal:o}=e;let a=createLlmClient({...n,abortSignal:o},r);a=withDefaultTraceInfo(a,s);const c=createDefaultTyper(e,"default");return new ScriptImpl(t,a,o,s,c,i)}class ScriptImpl{__init(){this.messages=[]}
2109
- static __initStatic(){this.concurrencyControl=srcExports$2.withLock(Number(process.env.MAX_LLM_CONCURRENCY)||100)}constructor(e,t,r,n,i,s){ScriptImpl.prototype.__init.call(this),this.messages.push({role:"system",content:e}),this.client=t,this.abortSignal=r,this.lfTrace=n,this.logger=s,this.defaultTyper=i}async callLlmWithPolicies(e){return withSpan("script.withRetry",async t=>{for(let r=1;r<=3;r++)try{return await ScriptImpl.concurrencyControl(async()=>await e())}catch(e){const n=retryableError(e);if(r<3&&n){_optionalChain$M([this,"access",e=>e.logger,"optionalAccess",e=>e.warn,"call",t=>t({attempt:r,retries:3,err:e,withDelay:n.withDelay},"retrying recognised error from llm call")]),n.withDelay&&await sleepInterruptable(100+5e3*Math.random(),this.abortSignal);continue}throw t.addEvent("withRetry.error",{[`attempt.${r}.err`]:cerealiseError(e)}),e}throw new Error("unreachable: threw or returned")})}async text(e=!1,t){
2110
- const r=_nullishCoalesce$J(t,()=>this.defaultTyper),n=_nullishCoalesce$J(this.expectParams,()=>({validator:()=>!0,promptOnFailure:"",attempts:1,strategy:"feedback",validationErrorBuilder:(e,t)=>new Error(e)}));return withSpan(`script.text: ${_nullishCoalesce$J(_optionalChain$M([r,"optionalAccess",e=>e.generationName]),()=>"???")}`,async t=>{let i="";for(let s=1;s<=n.attempts;s++){if(i=await this.callLlmWithPolicies(async()=>{await _optionalChain$M([r,"optionalAccess",e=>e.start,"call",e=>e()]);return(await this.client.streamFromMessages(this.messages,{traceInfo:{generationName:_optionalChain$M([r,"optionalAccess",e=>e.generationName])},retryIdx:s})).asString(r)}),this.assistant(i),t.setAttribute("response",i),e&&(i=stripMarkdown(i)),n.validator(i)){this.fireLfExpectationMetEvent({attempt:s,generationName:_optionalChain$M([r,"optionalAccess",e=>e.generationName]),expectParams:n,response:i}),_optionalChain$M([this,"access",e=>e.logger,"optionalAccess",e=>e.debug,"call",e=>e({attempt:s,
2111
- totalAttempts:n.attempts,validator:n.validator.name},"expectation validation succeeded")]),this.messages[this.messages.length-1].content=i;break}if(_optionalChain$M([this,"access",e=>e.logger,"optionalAccess",e=>e.info,"call",e=>e({attempt:s,totalAttempts:n.attempts,validator:n.validator.name},"expectation validation failed")]),s===n.attempts)throw n.validationErrorBuilder(`failed to meet expectation: ${n.validator.name}`,s);"feedback"===n.strategy?this.user(n.promptOnFailure):this.messages.pop()}return await _optionalChain$M([r,"optionalAccess",e=>e.done,"call",e=>e()]),i})}fireLfExpectationMetEvent({attempt:e,expectParams:t,generationName:r,response:n}){this.lfTrace.event({name:"expectationMet",input:n,output:!0,metadata:{attempt:e,generationName:r,strategy:t.strategy,attempts:t.attempts,validator:t.validator.name}})}async object(e,t){const r=_nullishCoalesce$J(t,()=>this.defaultTyper)
2112
- ;return withSpan(`script.object: ${_nullishCoalesce$J(_optionalChain$M([r,"optionalAccess",e=>e.generationName]),()=>"???")}`,async t=>{const[n,i]=await this.callLlmWithPolicies(async()=>{await _optionalChain$M([r,"optionalAccess",e=>e.start,"call",e=>e()]);return(await this.client.streamFromMessages(this.messages,{traceInfo:{generationName:_optionalChain$M([r,"optionalAccess",e=>e.generationName])},respondObject:e,prediction:this.predictionData})).asObject(r)});return this.assistant(i),t.setAttribute("response",i),await _optionalChain$M([r,"optionalAccess",e=>e.done,"call",e=>e()]),n})}async multiGen(e){const t=fromEntries(e.map(e=>[e,"not-streamed"]));return this.multiGenTyper(t)}async multiGenTyper(e){const t=keysOf(e);return withSpan(`multiGen: ${t.join(",")}`,async()=>this.callLlmWithPolicies(async()=>{const r=objectType(fromEntries(t.map(e=>[e,stringType().nullish()]))),n=await this.client.streamFromMessages(this.messages,{respondObject:{schema:r,name:"outputFiles"}
2113
- }),{capture:i,finish:s}=streamingJsonParser(adaptParserToTyper(e),"multiGen"),[o,a]=await n.asObject(i);return this.assistant(a),await s(),o}))}say(e,t){if(null==e)throw new Error("empty message");return this.messages.push({role:t,content:e}),this}assistant(e){return this.say(e,"assistant"),this}user(e){return e&&e.trim()?this.say(e,"user"):_optionalChain$M([this,"access",e=>e.logger,"optionalAccess",e=>e.warn,"call",t=>t({content:e,contentType:typeof e},"LLM Script received empty or whitespace-only user content - this may cause API errors")]),this}prediction(e){if(null==e)throw new Error("empty prediction");return this.predictionData=e,this}expect(e){return this.expectParams=e,this}overwriteLastReplyTo(e){const t=this.messages[this.messages.length-1];if("assistant"!==_optionalChain$M([t,"optionalAccess",e=>e.role]))throw new Error("can only overwrite assistant messages");return t.content=e,this}}function _nullishCoalesce$I(e,t){return null!=e?e:t()}function _optionalChain$L(e){
2114
- let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function createToolUtils(e,t){return{abortSignal:e.abortSignal,script:(r,n)=>createHighLevelClient(e,r,{...t,...n}),exec:async t=>exec$1(t,e.logger),langfuseEvent:t=>{_optionalChain$L([e,"access",e=>e.lfTrace,"optionalAccess",e=>e.event,"call",e=>e(t)])},userHasFlag:t=>e.userFeatureFlags===FeatureFlagsAlwaysReturnTrue||e.userFeatureFlags[t],ngClient:e.ngClient,experimental:{lookupTool:await makeLookupTool(),runTool,runToolOrCrash,specDom:{fromMarkdown:specFromMarkdown,toMarkdown:htmlDomToMarkdown,getApi,findTests,findTest,findImplementations:findImplementationPaths}}}}ScriptImpl.__initStatic();const tracer=trace$1.getTracer("request-context");async function requestSpan(e,t,r){const{params:n,tool:i}=t,s=i.name
2115
- ;return tracer.startActiveSpan(`step: ${s}`,async t=>{t.setAttribute("gen_ai.request.model",_nullishCoalesce$I(n.modelName,()=>"unknown")),t.setAttribute("gen_ai.request.temperature",_nullishCoalesce$I(n.modelTemperature,()=>"unknown")),t.setAttribute("llm.user",_nullishCoalesce$I(_optionalChain$L([e,"access",e=>e.llmFactory,"optionalAccess",e=>e.userHash]),()=>"unknown"));try{const t=v7(),i=e.reporter.withContext({toolRunId:t,toolName:s});return await r({...e,uuid:t,parent:e.uuid,logger:e.logger.child({stepUuid:t}),lfTrace:e.lfTrace.span({name:s,input:n}),reporter:i})}catch(e){throw annotateSpanWithError(t,e),e}finally{t.end()}})}function _optionalChain$K(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function sendHeartbeat(e){await e.emitMgmt({id:"heartbeat"})}
2116
- async function withHeartbeat(e,t,r){await sendHeartbeat(e);const n={},i=setInterval(()=>{t.signal.aborted?clearInterval(i):(async()=>{try{await sendHeartbeat(e)}catch(e){n.error=new AggregateError([e],"heartbeat crashed, aborting"),clearInterval(i),t.abort(n.error)}})()},5e3);try{return await r(()=>{if(n.error)throw n.error;if(t.signal.aborted)throw new ExpectedError("Operation cancelled")})}finally{clearInterval(i)}}async function executeToolList(e,t,r){let n=SUCCESS;for(const i of e){const e=await runTool(i,t);if(n=e,e>SUCCESS)break;_optionalChain$K([r,"optionalCall",e=>e()])}return n}const runToolOrCrash=async(...e)=>{if(1===await runTool(...e))throw new Error("tool failed")};async function runTool(e,t){const{tool:r,params:n}=e,i=setupToolParams(r,n),{rc:s,fsd:o}=t;return requestSpan(s,e,async e=>{await e.emitMgmt({id:"startTool",name:r.name,stepType:r.type,uuid:e.uuid,parent:e.parent,params:i});const t=await createToolUtils(e,i);let n;try{if("fsd"===r.type){
2108
+ r.on("error",e=>n.push(new AggregateError([e],"parser error")));const i=async()=>{const t=[...n];n.length=0;for(const r of t)await e(r)},s={async start(){},async chunk(e){await new Promise((t,n)=>r.write(e,e=>e?n(e):t())),await i()},async countTokens(e){},async done(){},generationName:t};return{capture:s,finish:async()=>{await new Promise(e=>r.end(e)),await i()}}}function _nullishCoalesce$J(e,t){return null!=e?e:t()}function _optionalChain$L(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function createHighLevelClient(e,t,r){const{llmFactory:n,logger:i,lfTrace:s,abortSignal:o}=e;let a=createLlmClient({...n,abortSignal:o},r);a=withDefaultTraceInfo(a,s);const c=createDefaultTyper(e,"default");return new ScriptImpl(t,a,o,s,c,i)}class ScriptImpl{__init(){this.messages=[]}
2109
+ static __initStatic(){this.concurrencyControl=srcExports$2.withLock(Number(process.env.MAX_LLM_CONCURRENCY)||100)}constructor(e,t,r,n,i,s){ScriptImpl.prototype.__init.call(this),this.messages.push({role:"system",content:e}),this.client=t,this.abortSignal=r,this.lfTrace=n,this.logger=s,this.defaultTyper=i}async callLlmWithPolicies(e){return withSpan("script.withRetry",async t=>{for(let r=1;r<=3;r++)try{return await ScriptImpl.concurrencyControl(async()=>await e())}catch(e){const n=retryableError(e);if(r<3&&n){_optionalChain$L([this,"access",e=>e.logger,"optionalAccess",e=>e.warn,"call",t=>t({attempt:r,retries:3,err:e,withDelay:n.withDelay},"retrying recognised error from llm call")]),n.withDelay&&await sleepInterruptable(100+5e3*Math.random(),this.abortSignal);continue}throw t.addEvent("withRetry.error",{[`attempt.${r}.err`]:cerealiseError(e)}),e}throw new Error("unreachable: threw or returned")})}async text(e=!1,t){
2110
+ const r=_nullishCoalesce$J(t,()=>this.defaultTyper),n=_nullishCoalesce$J(this.expectParams,()=>({validator:()=>!0,promptOnFailure:"",attempts:1,strategy:"feedback",validationErrorBuilder:(e,t)=>new Error(e)}));return withSpan(`script.text: ${_nullishCoalesce$J(_optionalChain$L([r,"optionalAccess",e=>e.generationName]),()=>"???")}`,async t=>{let i="";for(let s=1;s<=n.attempts;s++){if(i=await this.callLlmWithPolicies(async()=>{await _optionalChain$L([r,"optionalAccess",e=>e.start,"call",e=>e()]);return(await this.client.streamFromMessages(this.messages,{traceInfo:{generationName:_optionalChain$L([r,"optionalAccess",e=>e.generationName])},retryIdx:s})).asString(r)}),this.assistant(i),t.setAttribute("response",i),e&&(i=stripMarkdown(i)),n.validator(i)){this.fireLfExpectationMetEvent({attempt:s,generationName:_optionalChain$L([r,"optionalAccess",e=>e.generationName]),expectParams:n,response:i}),_optionalChain$L([this,"access",e=>e.logger,"optionalAccess",e=>e.debug,"call",e=>e({attempt:s,
2111
+ totalAttempts:n.attempts,validator:n.validator.name},"expectation validation succeeded")]),this.messages[this.messages.length-1].content=i;break}if(_optionalChain$L([this,"access",e=>e.logger,"optionalAccess",e=>e.info,"call",e=>e({attempt:s,totalAttempts:n.attempts,validator:n.validator.name},"expectation validation failed")]),s===n.attempts)throw n.validationErrorBuilder(`failed to meet expectation: ${n.validator.name}`,s);"feedback"===n.strategy?this.user(n.promptOnFailure):this.messages.pop()}return await _optionalChain$L([r,"optionalAccess",e=>e.done,"call",e=>e()]),i})}fireLfExpectationMetEvent({attempt:e,expectParams:t,generationName:r,response:n}){this.lfTrace.event({name:"expectationMet",input:n,output:!0,metadata:{attempt:e,generationName:r,strategy:t.strategy,attempts:t.attempts,validator:t.validator.name}})}async object(e,t){const r=_nullishCoalesce$J(t,()=>this.defaultTyper)
2112
+ ;return withSpan(`script.object: ${_nullishCoalesce$J(_optionalChain$L([r,"optionalAccess",e=>e.generationName]),()=>"???")}`,async t=>{const[n,i]=await this.callLlmWithPolicies(async()=>{await _optionalChain$L([r,"optionalAccess",e=>e.start,"call",e=>e()]);return(await this.client.streamFromMessages(this.messages,{traceInfo:{generationName:_optionalChain$L([r,"optionalAccess",e=>e.generationName])},respondObject:e,prediction:this.predictionData})).asObject(r)});return this.assistant(i),t.setAttribute("response",i),await _optionalChain$L([r,"optionalAccess",e=>e.done,"call",e=>e()]),n})}async multiGen(e){const t=fromEntries(e.map(e=>[e,"not-streamed"]));return this.multiGenTyper(t)}async multiGenTyper(e){const t=keysOf(e);return withSpan(`multiGen: ${t.join(",")}`,async()=>this.callLlmWithPolicies(async()=>{const r=objectType(fromEntries(t.map(e=>[e,stringType().nullish()]))),n=await this.client.streamFromMessages(this.messages,{respondObject:{schema:r,name:"outputFiles"}
2113
+ }),{capture:i,finish:s}=streamingJsonParser(adaptParserToTyper(e),"multiGen"),[o,a]=await n.asObject(i);return this.assistant(a),await s(),o}))}say(e,t){if(null==e)throw new Error("empty message");return this.messages.push({role:t,content:e}),this}assistant(e){return this.say(e,"assistant"),this}user(e){return e&&e.trim()?this.say(e,"user"):_optionalChain$L([this,"access",e=>e.logger,"optionalAccess",e=>e.warn,"call",t=>t({content:e,contentType:typeof e},"LLM Script received empty or whitespace-only user content - this may cause API errors")]),this}prediction(e){if(null==e)throw new Error("empty prediction");return this.predictionData=e,this}expect(e){return this.expectParams=e,this}overwriteLastReplyTo(e){const t=this.messages[this.messages.length-1];if("assistant"!==_optionalChain$L([t,"optionalAccess",e=>e.role]))throw new Error("can only overwrite assistant messages");return t.content=e,this}}function _nullishCoalesce$I(e,t){return null!=e?e:t()}function _optionalChain$K(e){
2114
+ let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function createToolUtils(e,t){return{abortSignal:e.abortSignal,script:(r,n)=>createHighLevelClient(e,r,{...t,...n}),exec:async t=>exec$1(t,e.logger),langfuseEvent:t=>{_optionalChain$K([e,"access",e=>e.lfTrace,"optionalAccess",e=>e.event,"call",e=>e(t)])},userHasFlag:t=>e.userFeatureFlags===FeatureFlagsAlwaysReturnTrue||e.userFeatureFlags[t],ngClient:e.ngClient,experimental:{lookupTool:await makeLookupTool(),runTool,runToolOrCrash,specDom:{fromMarkdown:specFromMarkdown,toMarkdown:htmlDomToMarkdown,getApi,findTests,findTest,findImplementations:findImplementationPaths}}}}ScriptImpl.__initStatic();const tracer=trace$1.getTracer("request-context");async function requestSpan(e,t,r){const{params:n,tool:i}=t,s=i.name
2115
+ ;return tracer.startActiveSpan(`step: ${s}`,async t=>{t.setAttribute("gen_ai.request.model",_nullishCoalesce$I(n.modelName,()=>"unknown")),t.setAttribute("gen_ai.request.temperature",_nullishCoalesce$I(n.modelTemperature,()=>"unknown")),t.setAttribute("llm.user",_nullishCoalesce$I(_optionalChain$K([e,"access",e=>e.llmFactory,"optionalAccess",e=>e.userHash]),()=>"unknown"));try{const t=v7(),i=e.reporter.withContext({toolRunId:t,toolName:s});return await r({...e,uuid:t,parent:e.uuid,logger:e.logger.child({stepUuid:t}),lfTrace:e.lfTrace.span({name:s,input:n}),reporter:i})}catch(e){throw annotateSpanWithError(t,e),e}finally{t.end()}})}function _optionalChain$J(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function sendHeartbeat(e){await e.emitMgmt({id:"heartbeat"})}
2116
+ async function withHeartbeat(e,t,r){await sendHeartbeat(e);const n={},i=setInterval(()=>{t.signal.aborted?clearInterval(i):(async()=>{try{await sendHeartbeat(e)}catch(e){n.error=new AggregateError([e],"heartbeat crashed, aborting"),clearInterval(i),t.abort(n.error)}})()},5e3);try{return await r(()=>{if(n.error)throw n.error;if(t.signal.aborted)throw new ExpectedError("Operation cancelled")})}finally{clearInterval(i)}}async function executeToolList(e,t,r){let n=SUCCESS;for(const i of e){const e=await runTool(i,t);if(n=e,e>SUCCESS)break;_optionalChain$J([r,"optionalCall",e=>e()])}return n}const runToolOrCrash=async(...e)=>{if(1===await runTool(...e))throw new Error("tool failed")};async function runTool(e,t){const{tool:r,params:n}=e,i=setupToolParams(r,n),{rc:s,fsd:o}=t;return requestSpan(s,e,async e=>{await e.emitMgmt({id:"startTool",name:r.name,stepType:r.type,uuid:e.uuid,parent:e.parent,params:i});const t=await createToolUtils(e,i);let n;try{if("fsd"===r.type){
2117
2117
  if(!o)throw new Error("fsd is required for fsd tools");n=await r.impl({rc:e,params:i,utils:t,fsd:o})}else assertUnreachable(r.type);return await e.emitMgmt({id:"endTool",name:r.name,exitCode:n,stepType:r.type,uuid:e.uuid,parent:e.parent}),n}catch(t){if(t instanceof ResponseValidationError)return 1;if(t&&"object"==typeof t){const r=t;r.uuid||(r.uuid=e.uuid),r.parent||(r.parent=e.parent)}throw t}})}async function _asyncNullishCoalesce$5(e,t){return null!=e?e:await t()}const isFsDiff=e=>null!==e&&"diff"in e;function fsdiff(e){const t=new Map,r=async r=>{if(!t.has(r))return await _asyncNullishCoalesce$5(await e.readText(r),async()=>"");return t.get(r)[0]},n=(e,r)=>{const n=t.get(e);n?n[1]=r[1]:t.set(e,r)};return{...e,writeText:async(t,i)=>{const s=await r(t);await e.writeText(t,i),n(t,[s,i])},destroy:async t=>{const i=await r(t);await e.destroy(t),n(t,[i,""])},diff:()=>new Map(Array.from(t.entries()).filter(([e,[t,r]])=>t!==r).map(([e,[t,r]])=>[e,[t,r,change(t,r)]]))}}function change(e,t){
2118
2118
  return""===e?"added":""===t?"deleted":"modified"}function calculateLineStats(e){let t=0,r=0;for(const[,[n,i]]of e){const e=n?n.split("\n").length:0,s=i?i.split("\n").length:0;s>e?t+=s-e:e>s&&(r+=e-s)}return{added:t,removed:r}}function calculateFileStats(e){let t=0,r=0,n=0;for(const[,[,,i]]of e)switch(i){case"added":t++;break;case"modified":r++;break;case"deleted":n++}return{created:t,modified:r,removed:n}}async function generateNewCode(e,t,r,n,i,s,o,a){const c=formatFileContextMessage(o),u=formatUserMessage$2(e,t,n,i,r);return addOrReplaceGeneratedCodeComment(await a.script(s).user(c).user(u).text(!0),relative(dirname(e),n),i,e)}function formatUserMessage$2(e,t,r,n,i){const s=["Update the content for the following code file so that it matches the provided spec and the user's goal (if provided)."];return s.push(`SPEC:\n${wrapWithFileTag(r,n)}`),t?s.push(`CODE:\n${wrapWithFileTag(e,t)}`):s.push(`CODE:\n${createFileTag(e)}`),i&&s.push(`GOAL: ${i}`),s.push(stripIndent`REQUIREMENTS:
2119
2119
  - Return the entire updated code file, including sections that weren't changed.
@@ -2127,9 +2127,9 @@ const{specContent:p,fileContext:h,exitCode:A}=await getStandardSpecFileContext({
2127
2127
  Generate the test file at ${t}, so that it satisfies the test definition contained in the spec at ${r}. Relevant code should be imported from ${l.join(", ")}.
2128
2128
 
2129
2129
  Return a test file that will work with the expected test framework, without any additional commentary or markup so its ready to be executed.
2130
- `;d+=await constructGeneralUserPrompt(o,r,s,i?void 0:t,u);const p=a(c).user(d);return addOrReplaceGeneratedCodeComment(await p.text(!0),relative(dirname(t),r),_nullishCoalesce$H(await o.readText(r),()=>{}),t)}const constructGeneralUserPrompt=async function(e,t,r,n,i){let s="";r&&r.trim().length>0&&(s+=`\n The user's instruction is:\n ${r}\n `);const o=n?await e.readText(n):void 0;return o&&o.trim().length>0&&n&&(s+=`\n The current version of the file is:\n ${wrapWithFileTag(n,o)}\n `),i[t]=await _asyncNullishCoalesce$4(await e.readText(t),async()=>""),s+=`\n ${formatFileContextMessage(i)}`,s};function _nullishCoalesce$G(e,t){return null!=e?e:t()}function _optionalChain$J(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
2130
+ `;d+=await constructGeneralUserPrompt(o,r,s,i?void 0:t,u);const p=a(c).user(d);return addOrReplaceGeneratedCodeComment(await p.text(!0),relative(dirname(t),r),_nullishCoalesce$H(await o.readText(r),()=>{}),t)}const constructGeneralUserPrompt=async function(e,t,r,n,i){let s="";r&&r.trim().length>0&&(s+=`\n The user's instruction is:\n ${r}\n `);const o=n?await e.readText(n):void 0;return o&&o.trim().length>0&&n&&(s+=`\n The current version of the file is:\n ${wrapWithFileTag(n,o)}\n `),i[t]=await _asyncNullishCoalesce$4(await e.readText(t),async()=>""),s+=`\n ${formatFileContextMessage(i)}`,s};function _nullishCoalesce$G(e,t){return null!=e?e:t()}function _optionalChain$I(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
2131
2131
  const generateTestsParamsSchema=objectType({spec:stringType().describe("Path to the spec to generate tests from, relative to the project root").transform(stripSurroundingQuotes),prompt:stringType().describe("Additional context to steer the LLM when generating tests").optional(),context:arrayType(stringType()).describe("Paths of any additional files that should be considered as context during generation").optional(),reference:enumType(["none","current"]).describe('Whether to reference existing content: "none" to regenerate from scratch, "current" to edit existing content').default("current"),testPaths:arrayType(stringType()).describe("Paths of the test files to filter on for generation (if omitted, will generate all test paths found in spec)").optional(),generateDraftTests:common$2.generate(),generateLockedTests:common$2.generate(),generateImplTests:common$2.generate()}),generateTestsTool={name:"generate-tests",type:"fsd",impl:generateTests,paramsSchema:generateTestsParamsSchema,
2132
- description:"Generate tests for a spec",help:"Generates tests for any [@test] links in the spec.",visibility:"private",positionalParam:"spec"};async function generateTests({utils:e,fsd:t,params:r,rc:n}){const{spec:i,prompt:s,context:o,reference:a="current",testPaths:c}=r,{reporter:u}=n;if(!i)return u.failure("No spec path provided. Please provide a spec path in the params",{specPath:i});const l=await getSystemPrompt(n.projectDir),d=[i],p=await Promise.all(d.map(async d=>{const{specContent:p,fileContext:h,exitCode:A}=await getStandardSpecFileContext({specPath:d,extraFiles:_nullishCoalesce$G(o,()=>[]),fsd:t,rc:n,allowEmptySpec:!1,includeLinkedContent:!0});if(A!==SUCCESS)return A;if(!p)return u.alert("error",`No spec content found for ${d}`),FAILURE;let f=specLinkedPathsFromContents(p,d,[findTestsConsidering(r)],n.projectDir);if(0===f.length)return u.alert("error",`No tests found for ${d}`),FAILURE;if(_optionalChain$J([c,"optionalAccess",e=>e.length])&&(f=f.filter(e=>c.includes(e.path)),
2132
+ description:"Generate tests for a spec",help:"Generates tests for any [@test] links in the spec.",visibility:"private",positionalParam:"spec"};async function generateTests({utils:e,fsd:t,params:r,rc:n}){const{spec:i,prompt:s,context:o,reference:a="current",testPaths:c}=r,{reporter:u}=n;if(!i)return u.failure("No spec path provided. Please provide a spec path in the params",{specPath:i});const l=await getSystemPrompt(n.projectDir),d=[i],p=await Promise.all(d.map(async d=>{const{specContent:p,fileContext:h,exitCode:A}=await getStandardSpecFileContext({specPath:d,extraFiles:_nullishCoalesce$G(o,()=>[]),fsd:t,rc:n,allowEmptySpec:!1,includeLinkedContent:!0});if(A!==SUCCESS)return A;if(!p)return u.alert("error",`No spec content found for ${d}`),FAILURE;let f=specLinkedPathsFromContents(p,d,[findTestsConsidering(r)],n.projectDir);if(0===f.length)return u.alert("error",`No tests found for ${d}`),FAILURE;if(_optionalChain$I([c,"optionalAccess",e=>e.length])&&(f=f.filter(e=>c.includes(e.path)),
2133
2133
  0===f.length))return u.alert("info",`No matching tests to generate for ${d}`),FAILURE;const g=specLinkedPathsFromContents(p,d,[findGeneratePaths,findDescribePaths],n.projectDir);if(0===g.length)return u.alert("error",`No code path found for ${d}: did you include a @generate or @describe link?`),FAILURE;const m=calculateSpecHash(p),y=[];for(const e of f){let n;switch(e.kind){case"draft":n=r.generateDraftTests;break;case"locked":n=r.generateLockedTests;break;case"impl":n=r.generateImplTests}await checkShouldUpdate({fsd:t,specPath:d,specHash:m,generate:n,generatedFilePath:e.path})&&y.push(e)}return 0===y.length?(u.alert("info",`No test files to generate for ${d}. ${f.length} skipped`),SUCCESS):(y.push("test-runner"),await u.cMap(y,async(r,o)=>{if("test-runner"===r)return o(`${d} (test-runner)`),void await generateTestRunner({spec:i,fsd:t,script:e.script,systemMessage:l,projectDir:n.projectDir});const c=r.path;o(c);const u=await generateTestContent({testFilePath:c,specPath:d,codePaths:g,
2134
2134
  ignoreCurrent:"none"===a,prompt:_nullishCoalesce$G(s,()=>""),fsd:t,script:e.script,systemMessage:l,fileContext:h});await t.writeText(c,u)},{message:`Generated {progress}/{total} test files for ${d}`,publishResults:!1}),SUCCESS)}));return p.filter(e=>e===SUCCESS).length===p.length?SUCCESS:FAILURE}async function generateNewSpec(e,t,r,n,i,s){const o=formatFileContextMessage(i),a=formatUserMessage$1(e,t,r);return await s.script(n).user(o).user(a).text()}function formatUserMessage$1(e,t,r){const n=["Update the content for the following spec file so that it matches the user's goal. If adding links, note the file path that has been provided, and make sure that links are relative to its actual location."];return t?n.push(wrapWithFileTag(e,t)):n.push(createFileTag(e)),n.push(`GOAL: ${r}`),n.push(stripIndent`REQUIREMENTS:
2135
2135
  - Return only the updated spec file content, no other text, wrapper tags, or comments.
@@ -2142,24 +2142,24 @@ ignoreCurrent:"none"===a,prompt:_nullishCoalesce$G(s,()=>""),fsd:t,script:e.scri
2142
2142
  name:"dependency-verification",schema:objectType({violations:arrayType(missingDependencySchema).describe("List of files with their missing dependencies")})};async function verifyDependenciesWithLLM(e,t,r){
2143
2143
  const n=e.length>0?e.map(e=>`- ${e}`).join("\n"):"No dependencies declared in the specification.",i=`\nYour task is to check the consistency between dependencies provided in the spec and what actual dependencies are used in the generated code.\nFocus on dependencies declared in the code and not in the spec.\n\nDependencies listed in the spec will be given to you under <spec-dependencies> tag. Each dependency listed in the spec is described with the name and small description.\nEach code file content along with the code file path will be given to you under <code-path> and <code-content> tags.\n\nYour goal is to check if the code-content uses any dependencies that are NOT explicitly declared in the spec-dependencies.\nYou must output the list of dependencies that are used in the code-content but not declared in the spec-dependencies for each code-path.\n\nIMPORTANT RULES:\n1. Flag dependencies that can be installed from npm, pypi, etc.\n2. Do NOT flag built-in language features, standard library modules\n3. For each file, list the specific dependency names that are missing from the spec\n\nLet's start:\n<spec-dependencies>\n${n}\n</spec-dependencies>\n\n${t.map(e=>`<code-path>${e.path}</code-path>\n<code-content>${e.content}</code-content>`).join("\n\n")}\n\nReturn your analysis as a structured response listing any violations found.\n`
2144
2144
  ;return await r.script("You are an expert code reviewer performing external dependency verification.").user(i).object(dependencyVerificationSchema)}const verifyDepsParamsSchema=objectType({spec:stringType().describe("Path to the spec file to be verified").transform(stripSurroundingQuotes).refine(e=>e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec file must have ${SPEC_FILE_EXTENSION} extension`}),codePaths:arrayType(stringType()).optional().describe("Optional array of file paths to restrict dependency verification to"),specifyMissingDependencies:booleanType().optional().default(!1).describe("If true, automatically add missing dependencies to the spec using edit-spec tool")}),verifyDepsTool={name:"verify-deps",type:"fsd",impl:verifyDeps,paramsSchema:verifyDepsParamsSchema,description:"Verify that code implementation only uses dependencies that are explicitly declared in the specification. Optionally restrict verification to specific file paths.",visibility:"private"}
2145
- ;async function verifyDeps({fsd:e,params:t,rc:r,utils:n}){const{spec:i,codePaths:s}=t,{reporter:o}=r;o.alert("info",`Starting dependency verification for ${i}`);const{specContent:a,exitCode:c}=await getStandardSpecFileContext({specPath:i,fsd:e,rc:r,allowEmptySpec:!1,includeLinkedContent:!0});if(0!==c)return c;const u=getUsePaths(specFromMarkdown(a));let l=specLinkedPathsFromContents(a,i,[findGeneratePaths],r.projectDir);if(s){const e=s.map(e=>({path:e,isInSpec:l.includes(e)})),t=e.filter(({isInSpec:e})=>!e).map(({path:e})=>e);if(t.length>0)return o.failure(`Spec ${i} does not link to: ${t.join(", ")}`);l=e.map(({path:e})=>e)}if(0===l.length)return o.alert("error","No code paths found to verify, verify-deps tool requires code to be verified against"),FAILURE;const d=[];for(const t of l){const r=await e.readText(t);if(!r)return o.alert("error",`Warning: Could not read code file ${t}`),FAILURE;d.push({path:t,content:r})}const p=await verifyDependenciesWithLLM(u,d,n);let h=!1
2146
- ;const A=new Set;for(const e of p.violations)e.missingDependencies.length>0&&(e.missingDependencies.forEach(e=>A.add(e)),o.alert("error",`File: ${e.fileName} uses following dependencies not mentioned in the spec: ${e.missingDependencies.join(", ")}`),h=!0);if(h){if(t.specifyMissingDependencies){o.alert("info","Attempting to automatically add missing dependencies to spec...");const t=Array.from(A).join(", ");return await runTool({tool:primitiveEditSpecTool,params:{spec:i,goal:`Add the following missing dependencies to the spec: ${t}. These dependencies are used in the generated code but not declared in the dependencies section.`,reference:"current"}},{rc:r,fsd:e})===SUCCESS?o.alert("success",`Successfully added missing dependencies to spec: ${t}. Please install these dependencies in your project.`):o.alert("error","Failed to automatically add missing dependencies to spec"),FAILURE}return FAILURE}return o.alert("success","Dependency verification passed"),SUCCESS}let Action$2=class{
2147
- constructor(e,t,r,n,i){this.name=e,this.tools=t,this.description=r||"No description available.",this.actionParams=n||(e=>e),this.memoryLoader=i}async run(e,t,r){let n=SUCCESS;const i=this.actionParams(e.params,r);for(const t of this.tools){const r=await e.rc.lookupTool(t.name);if(!r)throw new Error(`Tool '${t.name}' not found via lookup`);if(n=await runTool({tool:r,params:i},{rc:e.rc,fsd:e.fsd}),n!==SUCCESS)return e.rc.logger.error({},`Tool "${t.name}" in action "${this.name}" failed with exit code ${n}. Halting execution of this action.`),n}if(this.memoryLoader)try{(await this.memoryLoader(e.fsd,i)).forEach(e=>{if(!e.content)throw new Error(`Action ${this.name} failed to retrieve generated code – consider halting the fix loop.`);t.add(e.content,`Result of running action ${this.name} on ${e.path}`)})}catch(t){return e.rc.logger.error({},`Memory loading failed for action "${this.name}": ${t instanceof Error?t.message:String(t)}`),n}return n}};async function getCodeContents(e,t){
2148
- const r=await e.readText(t);if(!r)return[];const n=findGeneratePaths(specFromMarkdown(r));return 0===n.length?[]:await Promise.all(n.map(async r=>{const n=resolveRelativeToRoot(t,r);return{path:n,content:await e.readText(n)}}))}const codeContentsMemoryLoader=async(e,t)=>getCodeContents(e,t.spec),actionStepsConfig=[new Action$2("generate-code",[{name:generateCodeTool.name}],"Generate code from the spec based on the existing implementation",(e,t)=>({...e,generateCode:t.generateCode,codePaths:t.targetCodeFiles}),codeContentsMemoryLoader),new Action$2("generate-code-from-scratch",[{name:generateCodeTool.name}],"Generate code from the spec from scratch. Ignore the existing implementation. May be useful if you cant fix the issue after several attempts.",(e,t)=>({...e,generateCode:t.generateCode,codePaths:t.targetCodeFiles,reference:"none"}),codeContentsMemoryLoader),new Action$2("generate-tests",[{name:generateTestsTool.name}],"Generate tests from the spec",(e,t)=>({...e,
2149
- generateDraftTests:t.generateDraftTests,generateLockedTests:t.generateLockedTests,generateImplTests:t.generateImplTests,testPaths:e.tests instanceof Array&&e.tests.every(e=>"string"==typeof e)?[...e.tests,...t.targetTestFiles]:t.targetTestFiles})),new Action$2("edit-spec",[{name:primitiveEditSpecTool.name},{name:generateTestsTool.name}],"Edit the spec file, then triggers tests re-generation for consistency")];actionStepsConfig.map(e=>e.name);class ActionExecutor{constructor(e=[],t,r){if(this.memory=t,this.availableActions=actionStepsConfig.filter(t=>t.tools.every(t=>e.includes(t.name))),0===this.availableActions.length)throw new Error("No available actions found based on allowed tools");this.planContext=r}getAvailableActions(){return this.availableActions.map(e=>e.name)}getAvailableActionsWithDescriptions(){return this.availableActions.map((e,t)=>`${t+1}. ${e.name}: ${e.description}`)}async run(e,t){const r=this.availableActions.find(t=>t.name===e)
2150
- ;if(!r)throw new Error(`Action ${e} is not available but has to be`);const n=await r.run(t,this.memory,this.planContext);return n!==SUCCESS&&t.rc.logger.error({},`Action "${e}" failed with exit code ${n}. Halting execution of this action.`),n}}class Memory{__init(){this.history=[]}constructor(e=7){Memory.prototype.__init.call(this),this.maxSize=e}add(e,t){this.history.push({message:e,description:t}),this.history.length>this.maxSize&&this.history.shift()}formatToString(e=!0){const t=e?this.history:this.history.slice(0,-1);return 0===t.length?"No history available.":t.map((e,t)=>{let r=`\n --- Message ${t+1} ---\n`;return e.description&&(r+=`\nDescription: ${e.description}`),r+=`\n${e.message}`,r}).join("\n\n")}getHistory(){return[...this.history]}}var ObservationStatus;!function(e){e.OK="OK";e.FAILED="FAILED"}(ObservationStatus||(ObservationStatus={}));class Observer{constructor(e,t){this.name=e,this.description=t||"No description available."}async run(e,t,r){
2151
- const n=await e.rc.lookupTool(this.name);if(!n)throw new Error(`Tool '${this.name}' not found via lookup`);await runTool({tool:n,params:{...e.params,testCommand:r.testCommand}},{rc:e.rc,fsd:e.fsd});return await this.parseResult(e,t)}}class RunTestsObserver extends Observer{async parseResult(e,t){const{spec:r}=e.params;let n;try{n=await readTestResults(r,e.fsd)}catch(t){throw e.rc.logger.error({error:t},"Fix loop run tests observer failed to read valid test results"),new Error(`Fix loop run tests observer failed to read valid test results: ${t instanceof Error?t.message:String(t)}`)}const i=0===n.numFailingTests&&0===n.numErrorTests?ObservationStatus.OK:ObservationStatus.FAILED,s={regularFailingTests:n.numFailingTests-(n.numFailingImplTests||0),regularErrorTests:n.numErrorTests-(n.numErrorImplTests||0),implFailingTests:n.numFailingImplTests||0,implErrorTests:n.numErrorImplTests||0
2152
- },o=i===ObservationStatus.FAILED&&0===s.regularFailingTests&&0===s.regularErrorTests&&(s.implFailingTests>0||s.implErrorTests>0);return t.add(JSON.stringify(n),`Result of running observer named ${this.name}`),{name:this.name,status:i,observation:n,onlyImplTestsFailing:o,testFailureCounts:s}}}const observationStepsConfig=[new RunTestsObserver("test","Run tests for the spec")];observationStepsConfig.map(e=>e.name);class ObservationsExecutor{constructor(e=[],t,r){this.memory=t,this.availableObservations=observationStepsConfig.filter(t=>!e.includes(t.name)),this.planContext=r}getAvailableObservations(){return this.availableObservations.map(e=>e.name)}async runObservation(e,t){const r=this.availableObservations.find(t=>t.name===e);if(!r)throw new Error(`Observation ${e} is not available but has to be`);return r.run(t,this.memory,this.planContext)}}async function _asyncNullishCoalesce$3(e,t){return null!=e?e:await t()}const planStepSchema=objectType({
2153
- action:stringType().describe("The name of the action to execute."),reasoning:stringType().describe("The reasoning for choosing this action and its parameters"),instruction:stringType().describe("The instruction for the action to execute")}),planSchema={name:"plan",schema:objectType({plan:arrayType(planStepSchema).describe("The sequence of actions to execute to fix the issue")})};class PlanGenerator{constructor(e,t,r,n,i=1,s=""){this.rc=e,this.fsd=t,this.memory=r,this.utils=n,this.planLength=i,this.goal=s}async generatePlan(e,t,r,n){if(!this.rc.projectConfig)throw new Error("No config found. Run `tessl init` to create one.");const i=await this.fsd.readText(e);if(!i)throw new Error(`Spec file not found: ${e}`);const s=r.observationPath?await _asyncNullishCoalesce$3(await this.fsd.readText(r.observationPath),async()=>""):JSON.stringify(r.observation,null,2),o=this.createSystemMessage(),a=this.createUserMessage(i,t,s,n,this.goal,r),c=await this.utils.script(o).user(a).object(planSchema)
2154
- ;this.rc.logger.info({},"Generated plan:");const u=JSON.stringify(c,null,2);return this.rc.logger.info({},u),this.memory.add(u,"Generated plan"),c}createUserMessage(e,t,r,n,i,s){const o=n.join("\n"),a=this.memory.formatToString(!1);let c="";if(s.testFailureCounts&&void 0!==s.onlyImplTestsFailing){const e=s.testFailureCounts;c=`\n\nImplementation Test Status:\n- Regular spec tests: ${e.regularFailingTests+e.regularErrorTests>0?"FAILING":"PASSING"}\n- Implementation tests: ${e.implFailingTests+e.implErrorTests>0?"FAILING":"PASSING"}\n${s.onlyImplTestsFailing?"- Only implementation tests are failing":""}`}
2145
+ ;async function verifyDeps({fsd:e,params:t,rc:r,utils:n}){const{spec:i,codePaths:s}=t,{reporter:o}=r;o.alert("info",`Starting dependency verification for ${i}`);const{specContent:a,exitCode:c}=await getStandardSpecFileContext({specPath:i,fsd:e,rc:r,allowEmptySpec:!1,includeLinkedContent:!0});if(0!==c)return c;const u=getUsePaths(specFromMarkdown(a)),l=(await Promise.all(u.map(async t=>{if(t.endsWith(SPEC_FILE_EXTENSION)){const n=resolveRelativeToRoot(i,t);return await specLinkedPaths(e,n,[findGeneratePaths,findDescribePaths],r.projectDir)}return[t]}))).flat();let d=specLinkedPathsFromContents(a,i,[findGeneratePaths],r.projectDir);if(s){const e=s.map(e=>({path:e,isInSpec:d.includes(e)})),t=e.filter(({isInSpec:e})=>!e).map(({path:e})=>e);if(t.length>0)return o.failure(`Spec ${i} does not link to: ${t.join(", ")}`);d=e.map(({path:e})=>e)}if(0===d.length)return o.alert("error","No code paths found to verify, verify-deps tool requires code to be verified against"),FAILURE;const p=[]
2146
+ ;for(const t of d){const r=await e.readText(t);if(!r)return o.alert("error",`Warning: Could not read code file ${t}`),FAILURE;p.push({path:t,content:r})}const h=await verifyDependenciesWithLLM(l,p,n);let A=!1;const f=new Set;for(const e of h.violations)e.missingDependencies.length>0&&(e.missingDependencies.forEach(e=>f.add(e)),o.alert("error",`File: ${e.fileName} uses following dependencies not mentioned in the spec: ${e.missingDependencies.join(", ")}`),A=!0);if(A){if(t.specifyMissingDependencies){o.alert("info","Attempting to automatically add missing dependencies to spec...");const t=Array.from(f).join(", ");return await runTool({tool:primitiveEditSpecTool,params:{spec:i,goal:`Add the following missing dependencies to the spec: ${t}. These dependencies are used in the generated code but not declared in the dependencies section.`,reference:"current"}},{rc:r,fsd:e
2147
+ })===SUCCESS?o.alert("success",`Successfully added missing dependencies to spec: ${t}. Please install these dependencies in your project.`):o.alert("error","Failed to automatically add missing dependencies to spec"),FAILURE}return FAILURE}return o.alert("success","Dependency verification passed"),SUCCESS}let Action$2=class{constructor(e,t,r,n,i){this.name=e,this.tools=t,this.description=r||"No description available.",this.actionParams=n||(e=>e),this.memoryLoader=i}async run(e,t,r){let n=SUCCESS;const i=this.actionParams(e.params,r);for(const t of this.tools){const r=await e.rc.lookupTool(t.name);if(!r)throw new Error(`Tool '${t.name}' not found via lookup`);if(n=await runTool({tool:r,params:i},{rc:e.rc,fsd:e.fsd}),n!==SUCCESS)return e.rc.logger.error({},`Tool "${t.name}" in action "${this.name}" failed with exit code ${n}. Halting execution of this action.`),n}if(this.memoryLoader)try{(await this.memoryLoader(e.fsd,i)).forEach(e=>{
2148
+ if(!e.content)throw new Error(`Action ${this.name} failed to retrieve generated code – consider halting the fix loop.`);t.add(e.content,`Result of running action ${this.name} on ${e.path}`)})}catch(t){return e.rc.logger.error({},`Memory loading failed for action "${this.name}": ${t instanceof Error?t.message:String(t)}`),n}return n}};async function getCodeContents(e,t){const r=await e.readText(t);if(!r)return[];const n=findGeneratePaths(specFromMarkdown(r));return 0===n.length?[]:await Promise.all(n.map(async r=>{const n=resolveRelativeToRoot(t,r);return{path:n,content:await e.readText(n)}}))}const codeContentsMemoryLoader=async(e,t)=>getCodeContents(e,t.spec),actionStepsConfig=[new Action$2("generate-code",[{name:generateCodeTool.name}],"Generate code from the spec based on the existing implementation",(e,t)=>({...e,generateCode:t.generateCode,codePaths:t.targetCodeFiles}),codeContentsMemoryLoader),new Action$2("generate-code-from-scratch",[{name:generateCodeTool.name
2149
+ }],"Generate code from the spec from scratch. Ignore the existing implementation. May be useful if you cant fix the issue after several attempts.",(e,t)=>({...e,generateCode:t.generateCode,codePaths:t.targetCodeFiles,reference:"none"}),codeContentsMemoryLoader),new Action$2("generate-tests",[{name:generateTestsTool.name}],"Generate tests from the spec",(e,t)=>({...e,generateDraftTests:t.generateDraftTests,generateLockedTests:t.generateLockedTests,generateImplTests:t.generateImplTests,testPaths:e.tests instanceof Array&&e.tests.every(e=>"string"==typeof e)?[...e.tests,...t.targetTestFiles]:t.targetTestFiles})),new Action$2("edit-spec",[{name:primitiveEditSpecTool.name},{name:generateTestsTool.name}],"Edit the spec file, then triggers tests re-generation for consistency")];actionStepsConfig.map(e=>e.name);class ActionExecutor{constructor(e=[],t,r){if(this.memory=t,this.availableActions=actionStepsConfig.filter(t=>t.tools.every(t=>e.includes(t.name))),
2150
+ 0===this.availableActions.length)throw new Error("No available actions found based on allowed tools");this.planContext=r}getAvailableActions(){return this.availableActions.map(e=>e.name)}getAvailableActionsWithDescriptions(){return this.availableActions.map((e,t)=>`${t+1}. ${e.name}: ${e.description}`)}async run(e,t){const r=this.availableActions.find(t=>t.name===e);if(!r)throw new Error(`Action ${e} is not available but has to be`);const n=await r.run(t,this.memory,this.planContext);return n!==SUCCESS&&t.rc.logger.error({},`Action "${e}" failed with exit code ${n}. Halting execution of this action.`),n}}class Memory{__init(){this.history=[]}constructor(e=7){Memory.prototype.__init.call(this),this.maxSize=e}add(e,t){this.history.push({message:e,description:t}),this.history.length>this.maxSize&&this.history.shift()}formatToString(e=!0){const t=e?this.history:this.history.slice(0,-1);return 0===t.length?"No history available.":t.map((e,t)=>{let r=`\n --- Message ${t+1} ---\n`
2151
+ ;return e.description&&(r+=`\nDescription: ${e.description}`),r+=`\n${e.message}`,r}).join("\n\n")}getHistory(){return[...this.history]}}var ObservationStatus;!function(e){e.OK="OK";e.FAILED="FAILED"}(ObservationStatus||(ObservationStatus={}));class Observer{constructor(e,t){this.name=e,this.description=t||"No description available."}async run(e,t,r){const n=await e.rc.lookupTool(this.name);if(!n)throw new Error(`Tool '${this.name}' not found via lookup`);await runTool({tool:n,params:{...e.params,testCommand:r.testCommand}},{rc:e.rc,fsd:e.fsd});return await this.parseResult(e,t)}}class RunTestsObserver extends Observer{async parseResult(e,t){const{spec:r}=e.params;let n;try{n=await readTestResults(r,e.fsd)}catch(t){throw e.rc.logger.error({error:t},"Fix loop run tests observer failed to read valid test results"),new Error(`Fix loop run tests observer failed to read valid test results: ${t instanceof Error?t.message:String(t)}`)}
2152
+ const i=0===n.numFailingTests&&0===n.numErrorTests?ObservationStatus.OK:ObservationStatus.FAILED,s={regularFailingTests:n.numFailingTests-(n.numFailingImplTests||0),regularErrorTests:n.numErrorTests-(n.numErrorImplTests||0),implFailingTests:n.numFailingImplTests||0,implErrorTests:n.numErrorImplTests||0},o=i===ObservationStatus.FAILED&&0===s.regularFailingTests&&0===s.regularErrorTests&&(s.implFailingTests>0||s.implErrorTests>0);return t.add(JSON.stringify(n),`Result of running observer named ${this.name}`),{name:this.name,status:i,observation:n,onlyImplTestsFailing:o,testFailureCounts:s}}}const observationStepsConfig=[new RunTestsObserver("test","Run tests for the spec")];observationStepsConfig.map(e=>e.name);class ObservationsExecutor{constructor(e=[],t,r){this.memory=t,this.availableObservations=observationStepsConfig.filter(t=>!e.includes(t.name)),this.planContext=r}getAvailableObservations(){return this.availableObservations.map(e=>e.name)}async runObservation(e,t){
2153
+ const r=this.availableObservations.find(t=>t.name===e);if(!r)throw new Error(`Observation ${e} is not available but has to be`);return r.run(t,this.memory,this.planContext)}}async function _asyncNullishCoalesce$3(e,t){return null!=e?e:await t()}const planStepSchema=objectType({action:stringType().describe("The name of the action to execute."),reasoning:stringType().describe("The reasoning for choosing this action and its parameters"),instruction:stringType().describe("The instruction for the action to execute")}),planSchema={name:"plan",schema:objectType({plan:arrayType(planStepSchema).describe("The sequence of actions to execute to fix the issue")})};class PlanGenerator{constructor(e,t,r,n,i=1,s=""){this.rc=e,this.fsd=t,this.memory=r,this.utils=n,this.planLength=i,this.goal=s}async generatePlan(e,t,r,n){if(!this.rc.projectConfig)throw new Error("No config found. Run `tessl init` to create one.");const i=await this.fsd.readText(e);if(!i)throw new Error(`Spec file not found: ${e}`)
2154
+ ;const s=r.observationPath?await _asyncNullishCoalesce$3(await this.fsd.readText(r.observationPath),async()=>""):JSON.stringify(r.observation,null,2),o=this.createSystemMessage(),a=this.createUserMessage(i,t,s,n,this.goal,r),c=await this.utils.script(o).user(a).object(planSchema);this.rc.logger.info({},"Generated plan:");const u=JSON.stringify(c,null,2);return this.rc.logger.info({},u),this.memory.add(u,"Generated plan"),c}createUserMessage(e,t,r,n,i,s){const o=n.join("\n"),a=this.memory.formatToString(!1);let c="";if(s.testFailureCounts&&void 0!==s.onlyImplTestsFailing){const e=s.testFailureCounts;c=`\n\nImplementation Test Status:\n- Regular spec tests: ${e.regularFailingTests+e.regularErrorTests>0?"FAILING":"PASSING"}\n- Implementation tests: ${e.implFailingTests+e.implErrorTests>0?"FAILING":"PASSING"}\n${s.onlyImplTestsFailing?"- Only implementation tests are failing":""}`}
2155
2155
  return`\n<spec>\n${e}\n</spec>\n\n\n\n<memory>\n${a}\n</memory>\n\n\n\n<observer-response>\n${r}${c}\n</observer-response>\n\n\n\n<tools>\n${o}\n\n\n\nYou also have access to an additional tool named **"terminate"**.\nUse this when either:\n0. You observe that errors are related to missing dependencies—for example, when a package is not installed or when imports come from the path you can't make imports from. \n - If that's the case, output in your reasoning only what dependencies are missing, do not suggest how to install them.\n1. You believe the issue cannot be resolved using the provided tools\n2. Only implementation tests are failing - suggest updating implementation details or removing outdated impl tests\n3. The failures originate from a fundamental contradiction between spec requirements and implementation details\n\nIf you choose **"terminate"**, you **must not** include any other actions in the plan.\nBe sure to provide a clear and concise reasoning for selecting it.\n</tools>\n\n\n\n<test-files>\n${t.map(e=>`- ${e}`).join("\n")}\n</test-files>\n\n\n\n<goal>\n${i}\n</goal>\n\n\n\nPlease generate a plan to address the issue using the format specified in the system prompt.\n`
2156
2156
  }createSystemMessage(){
2157
2157
  return`\nYou are a software fix planner.\n\nYou will receive:\n- A content of the spec file wrapped in <spec></spec> tags. Spec defines the API of the component, explains nature of tests and provides context for the component. Spec is the source of truth.\n- A memory of the conversation, wrapped in <memory></memory> tags so that you could see what happened. Memory can include generated code from previous fix iterations so you can see and understand context of the current fix iteration.\n- An <observer-response></observer-response> section, which contains the actual issue or failure observed in the current solution. This is the latest feedback from the system\n- A list of available tools, wrapped in <tools></tools> tags.\n- An optional list of test files <test-files></test-files>, listing the subset of test files that we are going to be regenerating if we are going to limit them.\n- An optional user goal <goal></goal>, describing the intended outcome or the problem.\n\nYour task is to analyze the spec, analyze the observer response, analyze the available tools, and propose a step-by-step **plan to fix the issue** using the provided tools.\n\nFor each step in the plan:\n- Select a relevant tool.\n- Provide a **short, clear reasoning** for choosing this tool.\n- Write a concise **instruction** that tells the executor exactly what to do when running this tool.\n\nEach plan step must follow this format:\n{\n"tool": "<tool name>",\n"reasoning": "<why this tool is needed>",\n"instruction": "<clear, relevant instruction>"\n}\n**Instruction Examples:**\n- For "generate-code", if unit tests are failing, the instruction could be: "Update the code to pass the tests."\n\n**Output Requirements:**\n- Return the plan as a **JSON array** of tools in the format above.\n- You may include up to ${this.planLength} tools in the plan.\n\n**Important:**\n- Your plan must satisfy the spec first.\n- Code or tests can easily contradict spec (due to a bug in code/tests) that's why you can use the toolings to decide how to fix the issue.\n if you observe feedback from failed tests it can be not due to a bug in the code but rather a problem with tests not following spec properly. **Your plan must satisfy the spec first.**\n- If you already tried to generate code multiple times (based on your memory), it might be a good idea to change the strategy and re-generate tests or edit the spec. Don't be afraid to change the strategy.\n- if toolset allows to edit spec, then you can edit spec in case there are clear contradictions inside the spec that prevent from generating a valid solution.\n- Use memory to see what actions were taken in the past and result they produced in order to outline your plan\n\n**Implementation Test Handling:**\n- Implementation tests have "_impl" suffix in their file names and test implementation details marked with { .impl } tags in the spec\n- If ONLY implementation tests are failing (regular spec tests pass), this indicates:\n 1. The core functionality works correctly per the spec\n 2. Implementation details have changed or are inconsistent with current behavior\n- In this scenario, prefer the "terminate" action with reasoning that suggests:\n - Using \`tessl document --include-impl-details {spec-path}\` to update implementation details\n - Or deleting the failing implementation tests if they're no longer relevant\n - Implementation details should follow the actual working code, not drive it\n`
2158
- }}function _optionalChain$I(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const primitiveToolNames=[primitiveEditSpecTool.name,generateCodeTool.name,generateTestsTool.name],defaultTools=["generate-code"],fixLoopParamsSchema=objectType({spec:stringType().describe("Path to the spec, relative to the project root").transform(stripSurroundingQuotes),goal:stringType().describe("A string describing the goal that user wants to achieve through the fix loop").optional(),tests:arrayType(stringType()).describe("List of test files that should be worked on during the fix loop. Others are ignored").optional(),code:arrayType(stringType()).describe("List of code files that should be worked on during the fix loop. Others are ignored").optional(),
2158
+ }}function _optionalChain$H(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const primitiveToolNames=[primitiveEditSpecTool.name,generateCodeTool.name,generateTestsTool.name],defaultTools=["generate-code"],fixLoopParamsSchema=objectType({spec:stringType().describe("Path to the spec, relative to the project root").transform(stripSurroundingQuotes),goal:stringType().describe("A string describing the goal that user wants to achieve through the fix loop").optional(),tests:arrayType(stringType()).describe("List of test files that should be worked on during the fix loop. Others are ignored").optional(),code:arrayType(stringType()).describe("List of code files that should be worked on during the fix loop. Others are ignored").optional(),
2159
2159
  tools:arrayType(stringType().refine(e=>primitiveToolNames.includes(e),e=>({message:`Invalid tool: ${e}. Must be one of: ${primitiveToolNames.join(", ")}`}))).describe("A list of primitive tools available for the fix loop").default(defaultTools),maxPlanLength:numberType().describe("The maximum number of tools in a plan").optional(),iterations:numberType().describe("The number of iterations to run the fix loop").default(3),testCommand:stringType().optional().describe(testCommandDescription),context:arrayType(stringType()).describe("Paths of any additional files that should be considered as context during generation").optional(),generateDraftTests:common$2.generate(),generateLockedTests:common$2.generate(),generateImplTests:common$2.generate(),generateCode:common$2.generate()}),fixTool={name:"fix",type:"fsd",impl:fixLoop,paramsSchema:fixLoopParamsSchema,description:"Fix failing tests for a single spec by updating the code",visibility:"private"}
2160
2160
  ;async function fixLoop({fsd:e,rc:t,utils:r,params:n}){const{spec:i,goal:s,iterations:o,maxPlanLength:a,tools:c,testCommand:u}=n;let l,d;try{l=await resolveTargetedFiles(t,e,i,[findTestsConsidering(n)],n.tests)}catch(e){return t.reporter.failure(`${e instanceof Error?e.message:`Unknown error resolving ${i} tests`}`,{specPath:i,tests:n.tests})}try{d=await resolveTargetedFiles(t,e,i,[findGeneratePaths],n.code)}catch(e){return t.reporter.failure(e instanceof Error?e.message:`Unknown error resolving ${i} generated files`,{specPath:i,code:n.code})}t.reporter.message(`Defined ${o} agentic loop iterations`);const p=new Memory(7);(await getCodeContents(e,i)).forEach(e=>{e.content&&p.add(e.content,`Current source code in ${e.path}`)});const h=new ActionExecutor(c,p,{generateDraftTests:n.generateDraftTests,generateLockedTests:n.generateLockedTests,generateImplTests:n.generateImplTests,generateCode:n.generateCode,targetTestFiles:l,targetCodeFiles:d,testCommand:u})
2161
2161
  ;t.reporter.message(`Available actions: ${h.getAvailableActions().join(", ")}`);const A=new ObservationsExecutor([],p,{testCommand:u}),f=new PlanGenerator(t,e,p,r,a,s);for(let s=0;s<o+1;s++){t.reporter.message(`Running iteration ${s+1} of the fix loop`),t.reporter.message("First, run tests and inspect the results.");const a=await A.runObservation("test",{fsd:e,rc:t,utils:r,params:n});if(a.status===ObservationStatus.OK)return t.reporter.success(["All tests are passing"]);if(s===o)return t.reporter.failure(`Reached maximum iterations (${o}) without fixing the issue`);t.reporter.message("test tool observation failed indicating some issues likely with failed tests. Trying to generate a plan to address the problem.");const c=await f.generatePlan(i,l,a,h.getAvailableActionsWithDescriptions());if(0===c.plan.length)throw new Error("Something went wrong: No plan was generated, process should have terminated.");t.reporter.message(`Executing plan with ${c.plan.length} actions`);let u=0
2162
- ;for(const s of c.plan){if(u++,"terminate"===_optionalChain$I([s,"optionalAccess",e=>e.action]))return a.onlyImplTestsFailing?t.reporter.failure(["Fix loop terminated: Only implementation tests are failing.",`Reasoning: ${s.reasoning}`,"","Suggested actions:",`- Use 'tessl document --include-impl-details -s ${i}' to update implementation details in the spec`,"- Or delete the failing implementation tests if they're no longer relevant"].join("\n")):t.reporter.failure(`Something went wrong. Reasoning: ${s.reasoning}`);const o=getFullTestResultsPath(i);if(await t.reporter.wait(`Executing action ${u}/${c.plan.length}: ${s.action}`,async()=>h.run(s.action,{fsd:e,rc:t,utils:r,params:{...n,goal:s.instruction,context:[...n.context||[],o]}}))!==SUCCESS)return t.reporter.failure("Fix loop interrupted: executed action returned unexpected failure")}}return t.reporter.success(["Fix loop completed successfully"])}async function resolveTargetedFiles(e,t,r,n,i){
2162
+ ;for(const s of c.plan){if(u++,"terminate"===_optionalChain$H([s,"optionalAccess",e=>e.action]))return a.onlyImplTestsFailing?t.reporter.failure(["Fix loop terminated: Only implementation tests are failing.",`Reasoning: ${s.reasoning}`,"","Suggested actions:",`- Use 'tessl document --include-impl-details -s ${i}' to update implementation details in the spec`,"- Or delete the failing implementation tests if they're no longer relevant"].join("\n")):t.reporter.failure(`Something went wrong. Reasoning: ${s.reasoning}`);const o=getFullTestResultsPath(i);if(await t.reporter.wait(`Executing action ${u}/${c.plan.length}: ${s.action}`,async()=>h.run(s.action,{fsd:e,rc:t,utils:r,params:{...n,goal:s.instruction,context:[...n.context||[],o]}}))!==SUCCESS)return t.reporter.failure("Fix loop interrupted: executed action returned unexpected failure")}}return t.reporter.success(["Fix loop completed successfully"])}async function resolveTargetedFiles(e,t,r,n,i){
2163
2163
  const{projectDir:s}=e,o=getPaths(await specLinkedPaths(t,r,n,s));if(void 0===i)return o;const a=[];for(const e of i)o.some(t=>t===e)||a.push(e);if(a.length>0)throw new Error(`spec ${r} does not contain links for the following files: ${a.join(" ")}`);return i}const TESTS_TO_CONSIDER=["added","modified"];async function buildSpec(e,{fsd:t,params:r,rc:n},{prompt:i,codePaths:s,testPaths:o}={}){const a=r.testCommand||enableTestRunners(),c=0!==r.maxIterations;if(c&&!a)return n.reporter.alert("error","No test command provided. Please provide a test command to use the fix loop."),FAILURE;const u=[],l=await t.readText(e);if(!l)throw new Error("Spec file not found");const d=specFromMarkdown(l),p=fsdiff(t),h=fsdiff(t);r.generateCode.includes(GenerateOption.never)||s&&0===s.length||0===findGeneratePaths(d).length||u.push(runTool({tool:generateCodeTool,params:{context:r.context,spec:e,reference:"current",generateCode:r.generateCode,codePaths:s,goal:i}},{rc:n,fsd:p}))
2164
2164
  ;if(0===specLinkedPathsFromContents(l,e,[findTestsConsidering(r)],n.projectDir).length||o&&0===o.length||u.push(runTool({tool:generateTestsTool,params:{context:r.context,spec:e,reference:"current",generateDraftTests:r.generateDraftTests,generateLockedTests:r.generateLockedTests,generateImplTests:r.generateImplTests,testPaths:o,prompt:i}},{rc:n,fsd:h})),0===u.length)return SUCCESS;if((await Promise.all(u)).find(e=>e!==SUCCESS))return FAILURE;const A=p.diff().keys().toArray();if(A.length>0){const i=await runTool({tool:verifyDepsTool,params:{spec:e,codePaths:A,specifyMissingDependencies:r.specifyMissingDependencies}},{rc:n,fsd:t});if(i!==SUCCESS)return n.reporter.alert("error","Code uses dependencies not declared in the spec. Please edit the spec to add missing dependencies and install them in the project."),i}if(!a)return SUCCESS;if(!c){return await runTool({tool:testTool,params:{spec:e,testCommand:r.testCommand}},{rc:n,fsd:t})}return await runFixLoop({specPath:e,fsd:t,params:r,rc:n,
2165
2165
  testDiff:h,codeDiff:p,code:A})}async function runFixLoop({specPath:e,fsd:t,params:r,rc:n,testDiff:i,codeDiff:s,code:o}){try{const a=Array.from(i.diff().entries()).filter(([e,[,,t]])=>TESTS_TO_CONSIDER.includes(t)&&!e.includes(TEST_RUNNER_DIR)).map(([e])=>e),c=[];if(o.length&&c.push("generate-code"),a.length&&c.push("generate-tests"),0===c.length)return n.logger.info({specPath:e,code:o,tests:a,codeDiff:s.diff(),testsDiff:i.diff()},"Skipping fix loop. No files to try to fix"),SUCCESS;if(await runTool({tool:fixTool,params:{context:r.context,spec:e,tools:c,iterations:r.maxIterations,testCommand:r.testCommand,tests:a,code:o,generateDraftTests:[GenerateOption.always],generateLockedTests:[GenerateOption.always],generateImplTests:[GenerateOption.always],generateCode:[GenerateOption.always]}},{rc:n,fsd:t})!==SUCCESS)return n.reporter.failure(`Fix loop failed for ${e}`)}catch(t){n.logger.error({specPath:e,codeDiff:s.diff(),testsDiff:i.diff(),params:r,err:t},"Error thrown during the fix loop")
@@ -2206,9 +2206,9 @@ language:stringType().describe("The language that this spec should target.").opt
2206
2206
  <goal>
2207
2207
  ${i}
2208
2208
  </goal>
2209
- `;a&&(c+=`\nIt will be used to generate tests and code written in ${a}.`);const u=await runTool({tool:primitiveEditSpecTool,params:{...t,spec:n,goal:c,reference:"none",context:o,init:!0}},{rc:r,fsd:e});return u===SUCCESS?r.reporter.success([`Spec created at ${n}`,"Next: Review the spec and make sure it accurately reflects your goal","Then: Run `tessl generate-tests` to create test files"]):u}function _nullishCoalesce$E(e,t){return null!=e?e:t()}function _optionalChain$H(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const PLAN_FILE_EXTENSION=".plan.md";function planFromMarkdown(e){return parseHtml(markdownToHtml(e))}function markdownFromPlanDom(e){return htmlDomToMarkdown(e)}function resetPlan(e){const t=planFromMarkdown(e)
2210
- ;t.querySelectorAll("blockquote").forEach(e=>e.remove());return t.querySelectorAll('input[type="checkbox"]').forEach(e=>e.removeAttribute("checked")),markdownFromPlanDom(t)}function getAllTasks(e){const t=e.querySelectorAll("input[type='checkbox']"),r=[];for(const n of t){const t=checkboxElementToTaskCheckbox(n,e);t&&r.push(t)}return r}function getFirstOpenTask(e){const t=e.querySelector("input[type='checkbox']:not([checked])");return t?checkboxElementToTaskCheckbox(t,e):null}function checkboxElementToTaskCheckbox(e,t){const r=t.querySelector(`label[for="${_optionalChain$H([e,"optionalAccess",e=>e.id])}"]`);if(!r)return null;const[n,...i]=_nullishCoalesce$E(_optionalChain$H([r,"optionalAccess",e=>e.textContent,"optionalAccess",e=>e.split,"call",e=>e("\n")]),()=>[]),s=_nullishCoalesce$E(i,()=>[]).filter(e=>!!e).join("\n");if(!n)return null;const o=n.replace(/^\s+/,"").match(/([^{}]*)(?:{(.*)})?/);if(!o||o.length<3)return null;const[a,c,u]=o;if(!c)return null;let l;if(u){
2211
- u.split(",").map(e=>e.trim()).forEach(e=>{const t=e.match(/@([^, ]+)/);2===_optionalChain$H([t,"optionalAccess",e=>e.length])&&([,l]=t)})}const d=e.hasAttribute("checked");return{task:c.trim(),tool:_optionalChain$H([l,"optionalAccess",e=>e.trim,"call",e=>e()]),context:s,completed:d}}const editParamsSchema=objectType({file:stringType().describe("Path to the file to edit").transform(stripSurroundingQuotes),context:arrayType(stringType().transform(stripSurroundingQuotes)).describe("Paths of any additional files that should be considered as context during the edit").optional(),prompt:stringType().describe("Description of the desired change"),documentUnknownFiles:enumType(["always","never"]).describe("Whether to automatically run `tessl document` for code files we don't have specs for").optional().default("always"),maxIterations:numberType().describe("Max improvement passes to attempt to fix tests after generating code and/or tests").default(0),
2209
+ `;a&&(c+=`\nIt will be used to generate tests and code written in ${a}.`);const u=await runTool({tool:primitiveEditSpecTool,params:{...t,spec:n,goal:c,reference:"none",context:o,init:!0}},{rc:r,fsd:e});return u===SUCCESS?r.reporter.success([`Spec created at ${n}`,"Next: Review the spec and make sure it accurately reflects your goal","Then: Run `tessl generate-tests` to create test files"]):u}function _nullishCoalesce$E(e,t){return null!=e?e:t()}function _optionalChain$G(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const PLAN_FILE_EXTENSION=".plan.md";function planFromMarkdown(e){return parseHtml(markdownToHtml(e))}function markdownFromPlanDom(e){return htmlDomToMarkdown(e)}function resetPlan(e){const t=planFromMarkdown(e)
2210
+ ;t.querySelectorAll("blockquote").forEach(e=>e.remove());return t.querySelectorAll('input[type="checkbox"]').forEach(e=>e.removeAttribute("checked")),markdownFromPlanDom(t)}function getAllTasks(e){const t=e.querySelectorAll("input[type='checkbox']"),r=[];for(const n of t){const t=checkboxElementToTaskCheckbox(n,e);t&&r.push(t)}return r}function getFirstOpenTask(e){const t=e.querySelector("input[type='checkbox']:not([checked])");return t?checkboxElementToTaskCheckbox(t,e):null}function checkboxElementToTaskCheckbox(e,t){const r=t.querySelector(`label[for="${_optionalChain$G([e,"optionalAccess",e=>e.id])}"]`);if(!r)return null;const[n,...i]=_nullishCoalesce$E(_optionalChain$G([r,"optionalAccess",e=>e.textContent,"optionalAccess",e=>e.split,"call",e=>e("\n")]),()=>[]),s=_nullishCoalesce$E(i,()=>[]).filter(e=>!!e).join("\n");if(!n)return null;const o=n.replace(/^\s+/,"").match(/([^{}]*)(?:{(.*)})?/);if(!o||o.length<3)return null;const[a,c,u]=o;if(!c)return null;let l;if(u){
2211
+ u.split(",").map(e=>e.trim()).forEach(e=>{const t=e.match(/@([^, ]+)/);2===_optionalChain$G([t,"optionalAccess",e=>e.length])&&([,l]=t)})}const d=e.hasAttribute("checked");return{task:c.trim(),tool:_optionalChain$G([l,"optionalAccess",e=>e.trim,"call",e=>e()]),context:s,completed:d}}const editParamsSchema=objectType({file:stringType().describe("Path to the file to edit").transform(stripSurroundingQuotes),context:arrayType(stringType().transform(stripSurroundingQuotes)).describe("Paths of any additional files that should be considered as context during the edit").optional(),prompt:stringType().describe("Description of the desired change"),documentUnknownFiles:enumType(["always","never"]).describe("Whether to automatically run `tessl document` for code files we don't have specs for").optional().default("always"),maxIterations:numberType().describe("Max improvement passes to attempt to fix tests after generating code and/or tests").default(0),
2212
2212
  testCommand:stringType().describe(testCommandDescription).optional(),specifyMissingDependencies:booleanType().optional().default(!1).describe("If true, automatically add missing dependencies to the spec if they are used in generated code file")}),editTool={name:"edit",type:"fsd",impl:edit,paramsSchema:editParamsSchema,description:"Edit a spec, code file, or test implementation based on a natural language prompt. If editing code or tests, the referencing spec will be updated with new context.",visibility:"public",positionalParam:"file"};async function edit({fsd:e,params:t,rc:r}){const{file:n}=t,i=n.endsWith(SPEC_FILE_EXTENSION),s=n.endsWith(PLAN_FILE_EXTENSION);if(r.reporter.heading(`Reading ${n}`),i)r.reporter.alert("info","Detected spec");else{if(s)return r.reporter.failure("Editing plan files is not currently supported");r.reporter.alert("info","Detected file")}return i?await editSpecFile(n,{fsd:e,params:t,rc:r}):await editRegularFile(n,{fsd:e,params:t,rc:r})}
2213
2213
  async function editSpecFile(e,{fsd:t,params:r,rc:n}){return await runTool({tool:primitiveEditSpecTool,params:{spec:e,goal:r.prompt,context:r.context}},{rc:n,fsd:t})}async function editRegularFile(e,{fsd:t,params:r,rc:n}){const i=await findOrCreateSpec(e,{fsd:t,params:r,rc:n});if(!i.spec)return FAILURE;if(i.existed){const s=await editSpecForFile(e,i.spec,{fsd:t,params:r,rc:n});if(s!==SUCCESS)return s}return await buildFileFromSpec(e,i.spec,{fsd:t,params:r,rc:n})}async function findOrCreateSpec(e,{fsd:t,params:r,rc:n}){const{documentUnknownFiles:i}=r;let s=await findSpecLinkingFile(n,t,[findGeneratePaths,findDescribePaths,findTestPaths],e);if(s)return{spec:s,existed:!0};if("always"===i&&(s=await createSpec({rc:n,fsd:t,file:e,params:r}),s))return{spec:s,existed:!1};const o=`Run \`tessl document --code ${e}\` or call \`tessl edit\` with \`--document-unknown-files=always\``;return n.reporter.failure(`Cannot find a spec linked to ${e}. ${o}`),{spec:null,existed:!1}}
2214
2214
  async function editSpecForFile(e,t,{fsd:r,params:n,rc:i}){return await runTool({tool:primitiveEditSpecTool,params:{spec:t,goal:specEditGoalForFile({file:e,specPath:t,prompt:n.prompt}),context:[e,...n.context||[]]}},{rc:i,fsd:r})}async function buildFileFromSpec(e,t,{fsd:r,params:n,rc:i}){i.reporter.alert("info",`Building the spec linked to ${e}: ${t}`);const s=await r.readText(t);if(!s)return i.reporter.failure(`Spec file ${t} is empty or does not exist`);const o=(e,...r)=>specLinkedPathsFromContents(s,t,r,i.projectDir).some(t=>t===e);return o(e,findGeneratePaths,findDescribePaths)?await buildCodeFile(e,t,{fsd:r,params:n,rc:i}):o(e,findTestPaths)?await buildTestFile(e,t,{fsd:r,params:n,rc:i}):i.reporter.failure(`Cannot find @generate, @describe or @test links to ${e} in ${t}`)}async function buildCodeFile(e,t,{fsd:r,params:n,rc:i}){return await buildSpec(t,{fsd:r,rc:i,params:{specifyMissingDependencies:n.specifyMissingDependencies,spec:[t],maxIterations:n.maxIterations,
@@ -2872,7 +2872,7 @@ Question: "What is the name of the new file to create?"
2872
2872
  Task: "Request user input to clarify how to handle errors"
2873
2873
  Question: "How should we handle errors?"
2874
2874
  `,requestReviewParamsSchema=objectType({changedFiles:arrayType(stringType()).describe("Array of changed files to review")}),requestReviewTool={name:"request-review",type:"fsd",impl:requestReview,paramsSchema:requestReviewParamsSchema,description:"Pauses execution for file review from user, then passes any provided feedback into the plan",visibility:"private",denyRunIn:["cloud"]};async function requestReview({params:e,rc:t}){const{changedFiles:r}=e;if(t.logger.info({changedFiles:r},"requesting review"),!t.waitForInput)return t.reporter.failure("waiting for user input is not configured but is required for this task, ending here");const n=`User review: ${await t.waitForInput({question:"Please review the changes made and select one of the following options:",showContinueOptions:!0,filePaths:r})||"User approves feedback; continue with the current plan"}`;return t.reporter.message(n),t.reporter.success([n])}const DEFAULT_MCP_CONFIG={tessl:{type:"stdio",command:"tessl",args:["mcp"]}
2875
- },INTERACTIVE_TOOLS={[requestInputTool.name]:requestInputTool,[requestReviewTool.name]:requestReviewTool},INTERACTIVE_TOOL_NAMES=Object.keys(INTERACTIVE_TOOLS),DEFAULT_ALLOWED_TOOLS=["mcp__tessl","WebFetch","WebSearch",`mcp__${MCP_NAME}__read_text_file`,`mcp__${MCP_NAME}__glob_files`,`mcp__${MCP_NAME}__list_files`,`mcp__${MCP_NAME}__write_text_file`,`mcp__${MCP_NAME}__destroy_file`,`mcp__${MCP_NAME}__shell_command`,`mcp__${MCP_NAME}__grep_files`],DEFAULT_DISALLOWED_TOOLS=["Task","exit_plan_mode","NotebookRead","NotebookEdit","TodoWrite","Read","Edit","MultiEdit","Write","Glob","LS","Bash","Grep","mcp__tessl__exec",...INTERACTIVE_TOOL_NAMES.map(e=>`mcp__tessl__${e}`)],DEFAULT_MAX_ATTEMPTS=3;function _optionalChain$G(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
2875
+ },INTERACTIVE_TOOLS={[requestInputTool.name]:requestInputTool,[requestReviewTool.name]:requestReviewTool},INTERACTIVE_TOOL_NAMES=Object.keys(INTERACTIVE_TOOLS),DEFAULT_ALLOWED_TOOLS=["mcp__tessl","WebFetch","WebSearch",`mcp__${MCP_NAME}__read_text_file`,`mcp__${MCP_NAME}__glob_files`,`mcp__${MCP_NAME}__list_files`,`mcp__${MCP_NAME}__write_text_file`,`mcp__${MCP_NAME}__destroy_file`,`mcp__${MCP_NAME}__shell_command`,`mcp__${MCP_NAME}__grep_files`],DEFAULT_DISALLOWED_TOOLS=["Task","exit_plan_mode","NotebookRead","NotebookEdit","TodoWrite","Read","Edit","MultiEdit","Write","Glob","LS","Bash","Grep","mcp__tessl__exec",...INTERACTIVE_TOOL_NAMES.map(e=>`mcp__tessl__${e}`)],DEFAULT_MAX_ATTEMPTS=3;function _optionalChain$F(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
2876
2876
  async function runClaude({prompt:e,rc:t,session:r,mcpServers:n,turns:i,systemPrompt:s,typer:o}){const a=[s,stripIndents`
2877
2877
  For file operations, you MUST use the MCP ${MCP_NAME} tools instead of native Claude tools or any other MCP:
2878
2878
  - Use mcp__${MCP_NAME}__read_text_file instead of Read
@@ -2887,7 +2887,7 @@ async function runClaude({prompt:e,rc:t,session:r,mcpServers:n,turns:i,systemPro
2887
2887
 
2888
2888
  The native Read, Write, Edit, MultiEdit, Bash, and Grep tools are disabled. Always use the MCP ${MCP_NAME} tools for all these operations.
2889
2889
  `].filter(e=>void 0!==e).join("\n\n"),c=conditionalLogger(t.logger,"CLAUDE_CODE"),{controller:u,cleanup:l}=childAbortController(t.abortSignal),d=[],p={prompt:e,options:{maxTurns:i,allowedTools:DEFAULT_ALLOWED_TOOLS,disallowedTools:DEFAULT_DISALLOWED_TOOLS,mcpServers:n,resume:r,appendSystemPrompt:a,stderr:e=>d.push(e),abortController:u}},h=[];try{await t.reporter.wait("Chatting with Claude...",async e=>{for await(const e of query(p))h.push(e),c.info({claudeMessage:e},"Claude message received"),await handleClaudeMessage(e,t.reporter.message.bind(t.reporter),o)})}catch(e){return t.reporter.failure(e instanceof Error?e.message:"Claude code failed with an unknown error",d.length?{stderr:d}:{})}finally{l()}return h}async function handleClaudeMessage(e,t,r){if(isResultMessage(e)&&"error_during_execution"===e.subtype)throw new Error("Claude code encountered an error during execution");isAssistantMessage(e)&&(handleAssistantMessage(e,t),
2890
- await _optionalChain$G([r,"optionalAccess",e=>e.countTokens,"call",t=>t(e.message.usage.output_tokens)]))}function handleAssistantMessage(e,t){for(const r of e.message.content)processAssistantContent(r,t)}function processAssistantContent(e,t){isTextBlock(e)&&t(`Claude says: ${e.text}`),isThinkingBlock(e)&&t(`Claude is thinking: ${e.thinking}`),isToolUseBlock(e)&&t(`Claude is using: ${e.name}`)}function isResultMessage(e){return"result"===e.type}function isAssistantMessage(e){return"assistant"===e.type}function isTextBlock(e){return"text"===e.type}function isThinkingBlock(e){return"thinking"===e.type}function isToolUseBlock(e){return"tool_use"===e.type}function childAbortController(e){const t=new AbortController,r=()=>{e.removeEventListener("abort",n)},n=()=>{t.abort(),r()};return e.addEventListener("abort",n),e.aborted&&(t.abort(),r()),{controller:t,cleanup:r}}function _optionalChain$F(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
2890
+ await _optionalChain$F([r,"optionalAccess",e=>e.countTokens,"call",t=>t(e.message.usage.output_tokens)]))}function handleAssistantMessage(e,t){for(const r of e.message.content)processAssistantContent(r,t)}function processAssistantContent(e,t){isTextBlock(e)&&t(`Claude says: ${e.text}`),isThinkingBlock(e)&&t(`Claude is thinking: ${e.thinking}`),isToolUseBlock(e)&&t(`Claude is using: ${e.name}`)}function isResultMessage(e){return"result"===e.type}function isAssistantMessage(e){return"assistant"===e.type}function isTextBlock(e){return"text"===e.type}function isThinkingBlock(e){return"thinking"===e.type}function isToolUseBlock(e){return"tool_use"===e.type}function childAbortController(e){const t=new AbortController,r=()=>{e.removeEventListener("abort",n)},n=()=>{t.abort(),r()};return e.addEventListener("abort",n),e.aborted&&(t.abort(),r()),{controller:t,cleanup:r}}function _optionalChain$E(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
2891
2891
  ("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function getEditPlanUserTemplate({goal:e,planContent:t,planPath:r,isInteractive:n,templateContent:i,config:s}){const o=t?wrapWithFileTag(r,t):createFileTag(r),a=i?stripIndent`TEMPLATE (use this plan as a model for the approach to this task):
2892
2892
  <TEMPLATE>
2893
2893
  ${i}
@@ -2926,7 +2926,7 @@ ${n?"":"- Do not add any tasks that require user input, e.g. review of changes o
2926
2926
 
2927
2927
  EXAMPLES:
2928
2928
  ${getPlanExamples()}
2929
- `}function getToolList(e,t){const r=builtInTools().filter(e=>"public"===e.visibility&&"fsd"===e.type&&"status"!==e.name&&("run-ci"!==e.name||_optionalChain$F([t,"optionalAccess",e=>e.ciCommand])&&t.ciCommand.length>0));e&&r.push(...Object.values(INTERACTIVE_TOOLS));return r.map(e=>`- ${e.name}: ${e.description}`).join("\n")}function getPlanExamples(){return stripIndent`---
2929
+ `}function getToolList(e,t){const r=builtInTools().filter(e=>"public"===e.visibility&&"fsd"===e.type&&"status"!==e.name&&("run-ci"!==e.name||_optionalChain$E([t,"optionalAccess",e=>e.ciCommand])&&t.ciCommand.length>0));e&&r.push(...Object.values(INTERACTIVE_TOOLS));return r.map(e=>`- ${e.name}: ${e.description}`).join("\n")}function getPlanExamples(){return stripIndent`---
2930
2930
  GOAL:
2931
2931
  Write a haiku about the weather
2932
2932
 
@@ -3101,14 +3101,14 @@ ${getPlanExamples()}
3101
3101
  - [ ] Build the primitive-steps tile { @build }
3102
3102
  - [ ] Run tests for the primitive-steps tile
3103
3103
  `}function stripFileWrapperTags(e){return e.replace(/^\s*<FILE[^>]*>/,"").replace(/<\/FILE\s*>\s*$/,"")}async function generateNewPlan({planPath:e,planContent:t,goal:r,systemPrompt:n,fileContext:i,utils:s,interactive:o,templateContent:a,config:c}){const u=formatFileContextMessage(i),l=getEditPlanUserTemplate({planPath:e,planContent:t,goal:r,templateContent:a,isInteractive:o,config:c});return stripFileWrapperTags(await s.script(n).user(u).user(l).text())}async function generateNewPlanWithAgent({planPath:e,planContent:t,goal:r,systemPrompt:n,fileContext:i,fsd:s,rc:o,interactive:a,templateContent:c,config:u}){const l=[formatFileContextMessage(i),getEditPlanUserTemplate({planPath:e,planContent:t,goal:r,isInteractive:a,templateContent:c,config:u})].join("\n\n"),d=await createFilesystemMCPServer(o,s),p=createDefaultTokenCounter(o,"edit-plan");try{await o.reporter.wait("Waiting for MCP server to be ready...",async e=>{await waitForMcpServer(d.healthUrl,e)}),await p.start()
3104
- ;const e=await runClaude({prompt:l,rc:o,mcpServers:d.config,turns:3,systemPrompt:n,typer:p});if("number"==typeof e)return e;const t=e[e.length-1];return t&&isResultMessage(t)&&"success"===t.subtype?stripFileWrapperTags(t.result):o.reporter.failure("Failed to generate plan with agent",{claudeMessages:e})}finally{await d.stop(),await p.done()}}function _optionalChain$E(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const DEFAULT_PLAN_DIR="plans",getTimestampedPlanPath=()=>(new Date).toISOString().slice(0,16).replace(/:/g,"").replace("T","-"),editPlanParamsSchema=objectType({plan:stringType().describe("Path to the plan file, relative to the project root").transform(stripSurroundingQuotes).refine(e=>e.endsWith(PLAN_FILE_EXTENSION),{
3104
+ ;const e=await runClaude({prompt:l,rc:o,mcpServers:d.config,turns:3,systemPrompt:n,typer:p});if("number"==typeof e)return e;const t=e[e.length-1];return t&&isResultMessage(t)&&"success"===t.subtype?stripFileWrapperTags(t.result):o.reporter.failure("Failed to generate plan with agent",{claudeMessages:e})}finally{await d.stop(),await p.done()}}function _optionalChain$D(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const DEFAULT_PLAN_DIR="plans",getTimestampedPlanPath=()=>(new Date).toISOString().slice(0,16).replace(/:/g,"").replace("T","-"),editPlanParamsSchema=objectType({plan:stringType().describe("Path to the plan file, relative to the project root").transform(stripSurroundingQuotes).refine(e=>e.endsWith(PLAN_FILE_EXTENSION),{
3105
3105
  message:`Plan file must end with ${PLAN_FILE_EXTENSION}`}).optional(),goal:stringType().describe("For existing plans: description of changes to make to the plan. For new plans (use --init): a description of the plan to be created"),context:arrayType(stringType()).describe("Optional array of context files").optional(),template:stringType().describe("Path to the plan to use as template for the new/updated plan").transform(stripSurroundingQuotes).refine(e=>e.endsWith(PLAN_FILE_EXTENSION),{message:`Template file must end with ${PLAN_FILE_EXTENSION}`}).optional(),reference:enumType(["none","current"]).describe('Whether to reference existing content: "none" to regenerate from scratch, "current" to edit existing content').default("current"),init:booleanType().describe("Boolean to initialize a new plan").optional(),withAgent:booleanType().describe("Use an agent to edit/create the plan. The agent can read code or use tools to pull extra context if needed").default(!1).optional()
3106
3106
  }),primitiveEditPlanTool={name:"edit-plan",type:"fsd",impl:editPlan,paramsSchema:editPlanParamsSchema,description:"Edit or create a plan file to organize and track tasks with markdown checkboxes.",visibility:"private"};async function generatePlanPath(e,t){const r=(await t.script("Generate a short, lowercase, hyphen-separated filename (no extension) for a project plan based on the following goal. Do not include a path, just the filename. Do not include the file extension.").user(`Goal: ${e}`).text(!0)).toLowerCase().replace(/[^a-z0-9-]/g,"").replace(/--+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${DEFAULT_PLAN_DIR}/${getTimestampedPlanPath()}-${r}${PLAN_FILE_EXTENSION}`}async function editPlan({utils:e,fsd:t,params:r,rc:n}){const{reporter:i}=n,s=fsdiff(t);let{plan:o,init:a}=r;const{context:c,goal:u,reference:l="current",withAgent:d,template:p}=r;o?i.heading("Updating plan"):(o=await i.wait("Determining file path",generatePlanPath(u,e)),a=!0,i.alert("info",`Using path ${o}`),
3107
3107
  i.heading("Generating a new plan"));const{logger:h}=n,A=await getSystemPrompt(n.projectDir),{planContent:f,fileContext:g,exitCode:m}=await getStandardPlanFileContext({planPath:o,extraFiles:c,fsd:s,rc:n,allowEmptyPlan:a,includeLinkedContent:!0});if(0!==m)return m;let y;if(p)try{if(y=await s.readText(p),!y)return n.reporter.failure(`Template file not found: ${p}`);h.debug({template:p},"Loaded template content")}catch(e){return n.reporter.failure(`Failed to load template: ${p}. Error: ${e instanceof Error?e.message:String(e)}`)}h.debug({goal:u,withAgent:d,template:p},"Generating new plan content");const E=n.projectConfig;let b;const C={rc:n,planPath:o,planContent:"none"===l?void 0:f,goal:u,systemPrompt:A,fileContext:g,fsd:s,utils:e,interactive:isInteractive$1(),templateContent:y,config:E};if(d){const e=await i.wait("Writing a plan with Claude Code",generateNewPlanWithAgent(C));if("number"==typeof e)return e;b=e}else b=await i.wait("Writing the plan",generateNewPlan(C))
3108
- ;await s.writeText(o,b);const I=planFromMarkdown(b),v=getAllTasks(I),w=_optionalChain$E([I,"access",e=>e.querySelector,"call",e=>e("h1"),"optionalAccess",e=>e.innerText]);return i.alert("success",`Updated plan. ${v.length} tasks.`),i.plan(w,o,v),n.reporter.success([`Updated ${o}`])}function isSummaryMessage(e){return"summary"===e.type}function serializeReportMessage(e){switch(e.type){case"message":return e.content;case"list":{const t=e.content.title?`${e.content.title}:\n`:"",r=e.content.bullet||"•";return t+e.content.items.map(e=>` ${r} ${e}`).join("\n")}case"alert":return`[${e.content.severity.toUpperCase()}] ${e.content.message}`;case"plan":return`${e.content.title?`Plan: ${e.content.title}`:"Plan"} (${e.content.tasks.length} tasks) - ${e.content.filePath}`;case"heading":return`=== ${e.content} ===`;case"action":return`${"success"===e.content.result?"SUCCESS:":"failure"===e.content.result?"FAILURE:":"..."} ${e.content.message}`;case"progressBar":{
3109
- const t=void 0!==e.content.progress&&void 0!==e.content.total?` (${e.content.progress}/${e.content.total})`:"";return`${e.content.message}${t}`}default:return e}}function createMessageCollector(e){const t=[],r=[];return{summaries:t,messages:r,handleManagementEvent:async n=>{if("report"===n.id&&"message"===n.data.type){const i=n.data.message;if(void 0!==e&&i.toolName!==e)return Promise.resolve();isSummaryMessage(i)?t.push(...i.content):r.push(serializeReportMessage(i))}else if("crash"===n.id&&n.err){const e=getMessageFromMaybeError(n.err);r.push(`[CRASH] ${e}`)}return Promise.resolve()}}}function _optionalChain$D(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const agentWrapperParamsSchema=objectType({task:stringType().describe("The task to complete"),
3108
+ ;await s.writeText(o,b);const I=planFromMarkdown(b),v=getAllTasks(I),w=_optionalChain$D([I,"access",e=>e.querySelector,"call",e=>e("h1"),"optionalAccess",e=>e.innerText]);return i.alert("success",`Updated plan. ${v.length} tasks.`),i.plan(w,o,v),n.reporter.success([`Updated ${o}`])}function isSummaryMessage(e){return"summary"===e.type}function serializeReportMessage(e){switch(e.type){case"message":return e.content;case"list":{const t=e.content.title?`${e.content.title}:\n`:"",r=e.content.bullet||"•";return t+e.content.items.map(e=>` ${r} ${e}`).join("\n")}case"alert":return`[${e.content.severity.toUpperCase()}] ${e.content.message}`;case"plan":return`${e.content.title?`Plan: ${e.content.title}`:"Plan"} (${e.content.tasks.length} tasks) - ${e.content.filePath}`;case"heading":return`=== ${e.content} ===`;case"action":return`${"success"===e.content.result?"SUCCESS:":"failure"===e.content.result?"FAILURE:":"..."} ${e.content.message}`;case"progressBar":{
3109
+ const t=void 0!==e.content.progress&&void 0!==e.content.total?` (${e.content.progress}/${e.content.total})`:"";return`${e.content.message}${t}`}default:return e}}function createMessageCollector(e){const t=[],r=[];return{summaries:t,messages:r,handleManagementEvent:async n=>{if("report"===n.id&&"message"===n.data.type){const i=n.data.message;if(void 0!==e&&i.toolName!==e)return Promise.resolve();isSummaryMessage(i)?t.push(...i.content):r.push(serializeReportMessage(i))}else if("crash"===n.id&&n.err){const e=getMessageFromMaybeError(n.err);r.push(`[CRASH] ${e}`)}return Promise.resolve()}}}function _optionalChain$C(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const agentWrapperParamsSchema=objectType({task:stringType().describe("The task to complete"),
3110
3110
  plan:stringType().describe("Path to the plan file").optional(),turns:numberType().describe("The number of turns to run").default(3)}),agentWrapperTool={name:"agent-wrapper",type:"fsd",impl:agentWrapper,paramsSchema:agentWrapperParamsSchema,description:"Performs a single, open-ended (agentic) task from a plan. Current agent is Claude Code.",visibility:"private",denyRunIn:["cloud"]};async function agentWrapper({fsd:e,params:t,rc:r}){const{task:n,plan:i,turns:s}=t,{reporter:o}=r;let a,c,u=!1;const l=createDefaultTokenCounter(r,"agent-wrapper"),d=await createFilesystemMCPServer(r,e),p={...DEFAULT_MCP_CONFIG,...d.config};try{await r.reporter.wait("Waiting for MCP server to be ready...",async e=>{await waitForMcpServer(d.healthUrl,e)});const t=i?await e.readText(i):null;void 0===t&&r.reporter.alert("warning",`Missing plan file: ${i}`);const h=PROMPT_TEMPLATE(t?`<PLAN: ${i}>\n${t}\n</PLAN>`:"No plan provided",n);await l.start();for(let e=0;!u&&e<DEFAULT_MAX_ATTEMPTS;e++){
3111
- const t=DEFAULT_MAX_ATTEMPTS-e,o=await runClaude({prompt:h,rc:r,session:a,mcpServers:p,turns:s,typer:l});if("number"==typeof o)return o;const d=o[o.length-1];d?isResultMessage(d)?(c=d,"success"===d.subtype?u=!0:a=d.session_id):r.logger.warn({attempts_remaining:t,task:n,planPath:i,message:d},`Expected a result message, but got ${d.type} instead, continuing if there are remaining retries`):r.logger.warn({attempts_remaining:t,task:n,planPath:i},"0 messages returned from runClaude, continuing if there are remaining retries")}return"success"===_optionalChain$D([c,"optionalAccess",e=>e.subtype])?o.success([]):o.failure(`Task failed after ${DEFAULT_MAX_ATTEMPTS} attempts`,{session:a})}finally{await d.stop(),await l.done()}}const PROMPT_TEMPLATE=(e,t)=>stripIndent`
3111
+ const t=DEFAULT_MAX_ATTEMPTS-e,o=await runClaude({prompt:h,rc:r,session:a,mcpServers:p,turns:s,typer:l});if("number"==typeof o)return o;const d=o[o.length-1];d?isResultMessage(d)?(c=d,"success"===d.subtype?u=!0:a=d.session_id):r.logger.warn({attempts_remaining:t,task:n,planPath:i,message:d},`Expected a result message, but got ${d.type} instead, continuing if there are remaining retries`):r.logger.warn({attempts_remaining:t,task:n,planPath:i},"0 messages returned from runClaude, continuing if there are remaining retries")}return"success"===_optionalChain$C([c,"optionalAccess",e=>e.subtype])?o.success([]):o.failure(`Task failed after ${DEFAULT_MAX_ATTEMPTS} attempts`,{session:a})}finally{await d.stop(),await l.done()}}const PROMPT_TEMPLATE=(e,t)=>stripIndent`
3112
3112
  You are a task executor. You will be given a task to complete as part of a larger plan. Your goal is to complete only the provided task, with the rest of the plan as context.
3113
3113
 
3114
3114
  You may perform some initial research in order to understand and complete the task. But completing the task should only be a single action. If the task requires multiple actions, or applies the same action to multiple entities, you should use the mcp__tessl__plan tool to break the task down, then exit. The plan tool requires a path to the plan file and a goal describing how you want to update the plan.
@@ -3119,17 +3119,17 @@ ${e}
3119
3119
 
3120
3120
  Here is the task:
3121
3121
  ${t}
3122
- `,PARAM_ALIASES={spec:"s",goal:"g",prompt:"p",file:"F",plan:"P",template:"T",recursive:"r",reference:"R",code:"c",context:"C",interactive:"i",iterations:"n",force:"f"};function validateAliasConflicts(e){const t=new Map;for(const r of e){const e=PARAM_ALIASES[r];e&&(t.has(e)||t.set(e,[]),t.get(e).push(r))}const r=Array.from(t.entries()).filter(([,e])=>e.length>1);if(r.length>0){const e=r.map(([e,t])=>`-${e}: ${t.join(", ")}`).join("; ");throw new Error(`Parameter alias conflicts detected: ${e}`)}}function _nullishCoalesce$B(e,t){return null!=e?e:t()}function _optionalChain$C(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function schemaToFlags(e,t){const r=zodToJsonSchema$2(e),{properties:n={},required:i=[]}=r;return Object.entries(n).filter(([e])=>e!==t).map(([e,t])=>{
3123
- const r=Array.isArray(t.type)?t.type.join("|"):_nullishCoalesce$B(t.type,()=>"unknown"),n=void 0!==t.default?t.default:void 0,s=_optionalChain$C([t,"access",e=>e.enum,"optionalAccess",e=>e.length])?t.enum:void 0,o=_optionalChain$C([s,"optionalAccess",e=>e.map,"call",e=>e(e=>{const t=JSON.stringify(e);return t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t})]);return{long:camelCaseToKebabCase(e),short:PARAM_ALIASES[e],required:i.includes(e),type:r,description:t.description,defaultValue:n,availableValues:o}})}function extractParamsFromArgs({args:e,tool:{paramsSchema:t,positionalParam:r},logger:n}){const{_:i,...s}=e,o=schemaToFlags(t);if(validateAliasConflicts(o.map(e=>e.long)),require$$0$i(i&&i.length>0,"run command must have unparsedArgs by definition"),i.shift(),void 0===r&&i[0]&&!i[0].startsWith("-"))throw new ExpectedError(`Unexpected positional argument: ${i[0]}`);if(r){if("array"===o.find(e=>kebabCaseToCamelCase(e.long)===r).type){const e=[]
3122
+ `,PARAM_ALIASES={spec:"s",goal:"g",prompt:"p",file:"F",plan:"P",template:"T",recursive:"r",reference:"R",code:"c",context:"C",interactive:"i",iterations:"n",force:"f"};function validateAliasConflicts(e){const t=new Map;for(const r of e){const e=PARAM_ALIASES[r];e&&(t.has(e)||t.set(e,[]),t.get(e).push(r))}const r=Array.from(t.entries()).filter(([,e])=>e.length>1);if(r.length>0){const e=r.map(([e,t])=>`-${e}: ${t.join(", ")}`).join("; ");throw new Error(`Parameter alias conflicts detected: ${e}`)}}function _nullishCoalesce$B(e,t){return null!=e?e:t()}function _optionalChain$B(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function schemaToFlags(e,t){const r=zodToJsonSchema$2(e),{properties:n={},required:i=[]}=r;return Object.entries(n).filter(([e])=>e!==t).map(([e,t])=>{
3123
+ const r=Array.isArray(t.type)?t.type.join("|"):_nullishCoalesce$B(t.type,()=>"unknown"),n=void 0!==t.default?t.default:void 0,s=_optionalChain$B([t,"access",e=>e.enum,"optionalAccess",e=>e.length])?t.enum:void 0,o=_optionalChain$B([s,"optionalAccess",e=>e.map,"call",e=>e(e=>{const t=JSON.stringify(e);return t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t})]);return{long:camelCaseToKebabCase(e),short:PARAM_ALIASES[e],required:i.includes(e),type:r,description:t.description,defaultValue:n,availableValues:o}})}function extractParamsFromArgs({args:e,tool:{paramsSchema:t,positionalParam:r},logger:n}){const{_:i,...s}=e,o=schemaToFlags(t);if(validateAliasConflicts(o.map(e=>e.long)),require$$0$i(i&&i.length>0,"run command must have unparsedArgs by definition"),i.shift(),void 0===r&&i[0]&&!i[0].startsWith("-"))throw new ExpectedError(`Unexpected positional argument: ${i[0]}`);if(r){if("array"===o.find(e=>kebabCaseToCamelCase(e.long)===r).type){const e=[]
3124
3124
  ;for(;void 0!==i[0]&&!i[0].startsWith("-");)e.push(i.shift());for(const t of e)i.push(`--${camelCaseToKebabCase(r)}`,t)}else if(i[0]&&!i[0].startsWith("-")){const e=i.shift();if(i.push(`--${camelCaseToKebabCase(r)}`,e),!i[0].startsWith("-"))throw new Error("Too many positional arguments received, this tool only accepts one.")}}const a=o.reduce((e,t)=>({...e,[`--${kebabCaseToCamelCase(t.long)}`]:typeStringToConstructor(t.long,t.type,n),[`--${t.long}`]:typeStringToConstructor(t.long,t.type,n),...t.short&&{[`-${t.short}`]:`--${t.long}`}}),{}),c=Object.entries(s).reduce((e,[t,r])=>({...e,[kebabCaseToCamelCase(t)]:r}),{}),u=arg(a,{argv:_nullishCoalesce$B(i,()=>[])});for(const e of o)c[kebabCaseToCamelCase(e.long)]=_nullishCoalesce$B(u[`--${e.long}`],()=>u[`--${kebabCaseToCamelCase(e.long)}`]);return c}function validateToolParams(e,t){const r=e.safeParse(t);if(!r.success){
3125
- const e=r.error.issues.filter(e=>"invalid_type"===e.code&&"undefined"===e.received).map(e=>e.path[0]),t=r.error.issues.filter(e=>!("invalid_type"===e.code&&"undefined"===e.received));if(t[0])throw new Error(_optionalChain$C([t,"access",e=>e[0],"optionalAccess",e=>e.message]));return{success:!1,missingFlags:e}}return{success:!0}}function typeStringToConstructor(e,t,r){if("string"===t)return String;if("number"===t)return Number;if("boolean"===t)return Boolean;if("array"===t)return[String];if("object"===t)return t=>{try{return JSON.parse(t)}catch(n){return _optionalChain$C([r,"optionalAccess",e=>e.error,"call",t=>t({err:n,param:e},"Failed to parse JSON")]),t}};throw new Error(`typeStringToConstructor not implemented for type ${t} (param: ${e})`)}function getModelParamsFlagConfig(){return schemaToFlags(getCliModelParamSchema()).reduce((e,{long:t,description:r,type:n,defaultValue:i,availableValues:s})=>({...e,[t]:{description:r,type:typeStringToConstructor(t,n),availableValues:s,
3126
- defaultValue:i}}),{})}function _nullishCoalesce$A(e,t){return null!=e?e:t()}function _optionalChain$B(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const inferToolParamsParamsSchema=objectType({task:stringType().describe("The task that the tool will be used for"),plan:stringType().describe("The plan that the task is part of"),toolName:stringType().describe("The name of the tool to infer params for"),turns:numberType().describe("The number of turns to run").default(3)}),inferToolParamsTool={name:"infer-tool-params",type:"fsd",impl:inferToolParams,paramsSchema:inferToolParamsParamsSchema,description:"Tries to infer params to run for a tool in a plan using Claude Code agent.",visibility:"private",denyRunIn:["cloud"]};async function inferToolParams({fsd:e,params:t,rc:r}){
3125
+ const e=r.error.issues.filter(e=>"invalid_type"===e.code&&"undefined"===e.received).map(e=>e.path[0]),t=r.error.issues.filter(e=>!("invalid_type"===e.code&&"undefined"===e.received));if(t[0])throw new Error(_optionalChain$B([t,"access",e=>e[0],"optionalAccess",e=>e.message]));return{success:!1,missingFlags:e}}return{success:!0}}function typeStringToConstructor(e,t,r){if("string"===t)return String;if("number"===t)return Number;if("boolean"===t)return Boolean;if("array"===t)return[String];if("object"===t)return t=>{try{return JSON.parse(t)}catch(n){return _optionalChain$B([r,"optionalAccess",e=>e.error,"call",t=>t({err:n,param:e},"Failed to parse JSON")]),t}};throw new Error(`typeStringToConstructor not implemented for type ${t} (param: ${e})`)}function getModelParamsFlagConfig(){return schemaToFlags(getCliModelParamSchema()).reduce((e,{long:t,description:r,type:n,defaultValue:i,availableValues:s})=>({...e,[t]:{description:r,type:typeStringToConstructor(t,n),availableValues:s,
3126
+ defaultValue:i}}),{})}function _nullishCoalesce$A(e,t){return null!=e?e:t()}function _optionalChain$A(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const inferToolParamsParamsSchema=objectType({task:stringType().describe("The task that the tool will be used for"),plan:stringType().describe("The plan that the task is part of"),toolName:stringType().describe("The name of the tool to infer params for"),turns:numberType().describe("The number of turns to run").default(3)}),inferToolParamsTool={name:"infer-tool-params",type:"fsd",impl:inferToolParams,paramsSchema:inferToolParamsParamsSchema,description:"Tries to infer params to run for a tool in a plan using Claude Code agent.",visibility:"private",denyRunIn:["cloud"]};async function inferToolParams({fsd:e,params:t,rc:r}){
3127
3127
  const{task:n,turns:i}=t,{reporter:s}=r,o=await e.readText(t.plan),a=builtInTools().find(e=>e.name===t.toolName);if(!a)return r.logger.warn({toolName:t.toolName},"Unexpectedly unable to find tool"),FAILURE;let c,u,l=!1;const d=await createFilesystemMCPServer(r,e),p={...DEFAULT_MCP_CONFIG,...d.config};try{await r.reporter.wait("Waiting for MCP server to be ready...",async e=>{await waitForMcpServer(d.healthUrl,e)});const e=getPromptTemplate(_nullishCoalesce$A(o,()=>""),n,a);for(let t=0;!l&&t<DEFAULT_MAX_ATTEMPTS;t++){const s=DEFAULT_MAX_ATTEMPTS-t,o=await runClaude({prompt:e,rc:r,session:c,mcpServers:p,turns:i});if("number"==typeof o)return o;const a=o[o.length-1];a?isResultMessage(a)?(u=a,"success"===a.subtype?l=!0:c=a.session_id):r.logger.warn({attempts_remaining:s,task:n,message:a},`Expected a result message, but got ${a.type} instead, continuing if there are remaining retries`):r.logger.warn({attempts_remaining:s,task:n
3128
- },"0 messages returned from runClaude, continuing if there are remaining retries")}return"success"===_optionalChain$B([u,"optionalAccess",e=>e.subtype])?s.success([u.result]):s.failure(`Task failed after ${DEFAULT_MAX_ATTEMPTS} attempts`,{session:c})}finally{await d.stop()}}
3128
+ },"0 messages returned from runClaude, continuing if there are remaining retries")}return"success"===_optionalChain$A([u,"optionalAccess",e=>e.subtype])?s.success([u.result]):s.failure(`Task failed after ${DEFAULT_MAX_ATTEMPTS} attempts`,{session:c})}finally{await d.stop()}}
3129
3129
  const getPromptTemplate=(e,t,r)=>`\nYou are assisting a system that is running tasks using the Tessl CLI. Your job is to generate a map of key-value pairs, describing the names and values of params that should be passed through to the Tessl CLI when it is run for the described task.\n\nThe tool you need to find params for is called ${r.name}.\n\nIts description is: ${r.description}\n\nIts params schema is:\n${schemaToFlags(r.paramsSchema).map(e=>`- ${e.long}: ${e.description}`).join("\n")}\n\nFor context, the overall plan is:\n${e}\n\nThe current task which you are determining parameters for is:\n${t}\n\nImportant: Return only the params, as a map of key-value pairs; do not include any other context. The return value should be parsable JSON and not include any metadata. Do not try to run the tool yourself, just infer the params.\n`,removeMarkdownCodeWrapper=e=>e.replaceAll(/```\w*/g,""),parseToolParamsFromCodeMarkdown=(e,t)=>{
3130
3130
  const r=removeMarkdownCodeWrapper(e),n=JSON.parse(r),i=builtInTools().find(e=>e.name===t);if(!i)throw new Error(`Unexpectedly unable to find tool: ${t}`);const s=validateToolParams$1(i,n);return{...structuredClone(defaultDefaults),...s}};async function selectToolAndParams({nextOpenTask:e,isInteractiveMode:t,rc:r,fsd:n,planPath:i}){const s=e.tool||agentWrapperTool.name;let o=s;if(s!==agentWrapperTool.name&&"run-parallel"!==s){const e=INTERACTIVE_TOOL_NAMES.includes(s)&&!t,n=await r.lookupTool(s);!e&&n||(n||r.reporter.alert("warning",`Unable to find tool: ${s}. Falling back to processing task with agent.`),o=agentWrapperTool.name)}const a={task:e.task,plan:i,interactive:t};switch(o){case"request-input":return{toolName:o,toolParams:{task:e.task,plan:i}};case"request-review":return{toolName:o,toolParams:{changedFiles:[]}};case"agent-wrapper":return{toolName:o,toolParams:a};case"run-parallel":return{toolName:"agent-wrapper",toolParams:a};default:{const t=await callInferToolParams({rc:r,
3131
- fsd:n,task:e.task,planPath:i,toolName:o});return t?{toolName:o,toolParams:t}:(r.reporter.alert("warning",`Unable to infer params for tool: ${o}. Falling back to agent.`),{toolName:agentWrapperTool.name,toolParams:a})}}}async function callInferToolParams({rc:e,fsd:t,task:r,planPath:n,toolName:i}){const{summaries:s,handleManagementEvent:o}=createMessageCollector(inferToolParamsTool.name),a=e.reporter.withReportHandler(async e=>{await o(e,async()=>{})});if(await runTool({tool:inferToolParamsTool,params:{task:r,plan:n,toolName:i}},{rc:{...e,reporter:a},fsd:t})===SUCCESS&&s[0])try{return parseToolParamsFromCodeMarkdown(s[0],i)}catch(t){return void e.logger.warn({error:t,toolName:i,task:r},"Failed to parse tool params")}}function _optionalChain$A(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}
3132
- return r}async function resolveInput(e,t,r){if(!e&&!t)throw new Error("plan or template must be provided");if(e&&t)throw new Error("only plan or template must be set");if(_optionalChain$A([e,"optionalAccess",e=>e.endsWith,"call",e=>e(PLAN_FILE_EXTENSION)]))return{type:"plan",workingPlanPath:e};if(_optionalChain$A([t,"optionalAccess",e=>e.endsWith,"call",e=>e(PLAN_FILE_EXTENSION)]))return resolveTemplateFile(t,r);throw new Error(e?`Plan file must end with ${PLAN_FILE_EXTENSION}, got: ${e}`:`Template file must end with ${PLAN_FILE_EXTENSION}, got: ${t}`)}async function resolveTemplateFile(e,t){const r=await t.readText(e);if(!r)throw new Error(`Plan file not found: ${e}`);return{type:"template",workingPlanPath:await createWorkingPlanCopy(e,r,t)}}async function createWorkingPlanCopy(e,t,r){const n=basename(e,PLAN_FILE_EXTENSION),i=`${getTimestampedPlanPath()}-${n}${PLAN_FILE_EXTENSION}`,s=join$1(DEFAULT_PLAN_DIR,i),o=resetPlan(t);return await r.writeText(s,o),s}
3131
+ fsd:n,task:e.task,planPath:i,toolName:o});return t?{toolName:o,toolParams:t}:(r.reporter.alert("warning",`Unable to infer params for tool: ${o}. Falling back to agent.`),{toolName:agentWrapperTool.name,toolParams:a})}}}async function callInferToolParams({rc:e,fsd:t,task:r,planPath:n,toolName:i}){const{summaries:s,handleManagementEvent:o}=createMessageCollector(inferToolParamsTool.name),a=e.reporter.withReportHandler(async e=>{await o(e,async()=>{})});if(await runTool({tool:inferToolParamsTool,params:{task:r,plan:n,toolName:i}},{rc:{...e,reporter:a},fsd:t})===SUCCESS&&s[0])try{return parseToolParamsFromCodeMarkdown(s[0],i)}catch(t){return void e.logger.warn({error:t,toolName:i,task:r},"Failed to parse tool params")}}function _optionalChain$z(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}
3132
+ return r}async function resolveInput(e,t,r){if(!e&&!t)throw new Error("plan or template must be provided");if(e&&t)throw new Error("only plan or template must be set");if(_optionalChain$z([e,"optionalAccess",e=>e.endsWith,"call",e=>e(PLAN_FILE_EXTENSION)]))return{type:"plan",workingPlanPath:e};if(_optionalChain$z([t,"optionalAccess",e=>e.endsWith,"call",e=>e(PLAN_FILE_EXTENSION)]))return resolveTemplateFile(t,r);throw new Error(e?`Plan file must end with ${PLAN_FILE_EXTENSION}, got: ${e}`:`Template file must end with ${PLAN_FILE_EXTENSION}, got: ${t}`)}async function resolveTemplateFile(e,t){const r=await t.readText(e);if(!r)throw new Error(`Plan file not found: ${e}`);return{type:"template",workingPlanPath:await createWorkingPlanCopy(e,r,t)}}async function createWorkingPlanCopy(e,t,r){const n=basename(e,PLAN_FILE_EXTENSION),i=`${getTimestampedPlanPath()}-${n}${PLAN_FILE_EXTENSION}`,s=join$1(DEFAULT_PLAN_DIR,i),o=resetPlan(t);return await r.writeText(s,o),s}
3133
3133
  function _nullishCoalesce$z(e,t){return null!=e?e:t()}const execParamsSchema=objectType({plan:stringType().describe("Path to the plan being executed. If omitted, the tool executes the most recent plan").transform(stripSurroundingQuotes).refine(e=>e.endsWith(PLAN_FILE_EXTENSION),{message:`Plan file must end with ${PLAN_FILE_EXTENSION}`}).optional(),template:stringType().describe("Plan to use as a template").transform(stripSurroundingQuotes).refine(e=>e.endsWith(PLAN_FILE_EXTENSION),{message:`Template must end with ${PLAN_FILE_EXTENSION}`}).optional(),maxTurns:numberType().describe("Maximum number of turns to execute the plan").default(50),interactive:booleanType().describe("Whether to run the plan in interactive mode").optional().transform(e=>_nullishCoalesce$z(e,()=>isInteractive$1()))}),execTool={name:"exec",type:"fsd",impl:exec,paramsSchema:execParamsSchema,description:"Executes a given plan",visibility:"private"};async function exec({fsd:e,params:t,rc:r}){const{template:n}=t
3134
3134
  ;let{plan:i}=t;const{reporter:s}=r;let{maxTurns:o}=t;const{interactive:a}=t;if(i&&n)return r.reporter.failure("Must provide either a plan or a template, not both");if(!i&&!n){const t=await e.glob(`${DEFAULT_PLAN_DIR}/*${PLAN_FILE_EXTENSION}`);if(i=t.toSorted()[t.length-1],!i)return r.reporter.failure("Must provide a plan or a template");r.reporter.alert("info",`No plan or template provided, using the most recent plan: ${i}`)}let c;try{c=await resolveInput(i,n,e)}catch(e){return s.failure("Failed to resolve input",{err:e,planPath:i,template:n})}"plan"!==c.type&&s.message(`Created working plan copy from template: ${c.workingPlanPath}`);const u=await e.readText(c.workingPlanPath);if(!u)return s.failure("Plan file not found",{planPath:c.workingPlanPath});if(!getFirstOpenTask(planFromMarkdown(u)))return s.failure("No open tasks found in plan file",{planPath:c.workingPlanPath});const l=c.workingPlanPath;for(;o>0;){const n=await e.readText(l);if(!n)return s.failure("Path not found",{
3135
3135
  planPath:l});const i=planFromMarkdown(n);r.reporter.plan("Executing plan",l,getAllTasks(i));const c=getFirstOpenTask(i);if(!c)return s.success(["No open tasks found, plan is complete"]);const{toolName:u,toolParams:d}=await selectToolAndParams({nextOpenTask:c,isInteractiveMode:a,rc:r,fsd:e,planPath:l}),p=[],h=r.reporter.withReportHandler(async e=>{if("message"===e.data.type&&e.data.message.toolName===u)switch(e.data.message.type){case"message":p.push(e.data.message.content);break;case"summary":p.push(...e.data.message.content);break;case"list":case"alert":p.push(JSON.stringify(e.data.message.content))}return Promise.resolve()}),A=await r.lookupTool(u);if(!A)return s.failure("Unexpectedly unable to find tool",{toolName:u});const f=await runTool({tool:A,params:{...t,...d}},{rc:{...r,reporter:h},fsd:e});f!==SUCCESS&&r.logger.debug({toolCallResult:f,toolName:u,toolParams:d},"Tool call returned failure code");const g=await runTool({tool:primitiveEditPlanTool,params:{...t,plan:l,
@@ -3154,17 +3154,17 @@ help:"[Experimental] This tool is designed for use if you're planning on using T
3154
3154
  The native Read, Write, Edit, LS and Grep tools are disabled. Always use the MCP ${MCP_NAME} tools for all these operations.
3155
3155
  `].filter(e=>void 0!==e).join("\n\n"),i=conditionalLogger(e.logger,"CLAUDE_CODE"),{controller:s,cleanup:o}=childAbortController(e.abortSignal),a=[],c={prompt:'Analyze this codebase and determine the following:\n\n Which stack does this codebase use (e.g. Node, TypeScript/ESM, Python, Java/Maven - determine this from the file paths)\n What testing framework to use (determine this from the imports and configuration files)\n Where code files and test files are located (e.g. ./src, ./tests)\n\n Once complete, replace the "New Project Bootstrapping" section of ./AGENTS.md with the project configuration information. Leave the other sections in.\n\n\n ',options:{maxTurns:20,allowedTools:[`mcp__${MCP_NAME}__read_text_file`,`mcp__${MCP_NAME}__glob_files`,`mcp__${MCP_NAME}__write_text_file`,`mcp__${MCP_NAME}__grep_files`],disallowedTools:["Bash","Edit","Glob","Grep","LS","MultiEdit","NotebookEdit","NotebookRead","Read","Task","TodoWrite","WebFetch","WebSearch","Write"],
3156
3156
  mcpServers:t,appendSystemPrompt:n,stderr:e=>a.push(e),abortController:s}},u=[];try{await e.reporter.wait("Chatting with Claude...",async t=>{for await(const t of query(c))u.push(t),i.info({claudeMessage:t},"Claude message received"),await handleClaudeMessage(t,e.reporter.message.bind(e.reporter),r)})}catch(t){return e.reporter.failure(t instanceof Error?t.message:"Claude code failed with an unknown error",a.length?{stderr:a}:{})}finally{o()}return u}async function getSpecType(e,t){const r=await e.readText(t);if(void 0===r)throw new Error(`Spec file not found: ${t}`);const n=specFromMarkdown(r),i=findDescribePaths(n);return findGeneratePaths(n).length>0?"generate":i.length>0?"describe":"generate"}function getSpecTypeDescription(e){
3157
- return"describe"===e?"This is a @describe spec - it documents existing code that is actively written and maintained. The code files are the source of truth.":"This is a @generate spec - it is the source of truth for its associated code files, which are LLM-generated from the spec requirements."}function _optionalChain$z(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function statusSingleSpec(e,t,r,n){try{if(void 0===await e.readText(t))return r.failure(`Spec file not found: ${t}`);const i=getSpecTypeDescription(await getSpecType(e,t));r.message(`Checking ${t}\n`),r.message(`${figures.info} ${i}\n`);const s=await r.wait("Checking diagnostics…",async()=>await getDiagnostics(e,t));if(s&&0===s.length)return r.failure(`{red ${figures.cross} Error running diagnostics for ${t}}`)
3158
- ;if(0===_optionalChain$z([s,"access",e=>e[0],"optionalAccess",e=>e.diagnostics,"optionalAccess",e=>e.length]))return n.info({},"no issues found in status check"),r.success([`{green ${figures.tick} Everything looks good in ${t}}`]);for(const{uri:e,diagnostics:t}of s)n.info({uri:e,diagnostics:t},"found issues in spec");displayDiagnostics(s,r,"Some spec checks failed");const o=s.flatMap(({diagnostics:e})=>e),a=o.filter(isError$1).length,c=o.filter(isWarning).length,u=[];a>0&&u.push(`${a} ${pluralize$1("error",a)}`),c>0&&u.push(`${c} ${pluralize$1("warning",c)}`);const l=`${u.join(" and ")} found with spec`;return a>0?r.failure(l):(r.message(`{yellow ${figures.warning} ${l}}`),SUCCESS)}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";return r.failure(`Unable to check spec: ${t}`)}}async function pMap(e,t,{concurrency:r=Number.POSITIVE_INFINITY,stopOnError:n=!0,signal:i}={}){return new Promise((s,o)=>{
3157
+ return"describe"===e?"This is a @describe spec - it documents existing code that is actively written and maintained. The code files are the source of truth.":"This is a @generate spec - it is the source of truth for its associated code files, which are LLM-generated from the spec requirements."}function _optionalChain$y(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function statusSingleSpec(e,t,r,n){try{if(void 0===await e.readText(t))return r.failure(`Spec file not found: ${t}`);const i=getSpecTypeDescription(await getSpecType(e,t));r.message(`Checking ${t}\n`),r.message(`${figures.info} ${i}\n`);const s=await r.wait("Checking diagnostics…",async()=>await getDiagnostics(e,t));if(s&&0===s.length)return r.failure(`{red ${figures.cross} Error running diagnostics for ${t}}`)
3158
+ ;if(0===_optionalChain$y([s,"access",e=>e[0],"optionalAccess",e=>e.diagnostics,"optionalAccess",e=>e.length]))return n.info({},"no issues found in status check"),r.success([`{green ${figures.tick} Everything looks good in ${t}}`]);for(const{uri:e,diagnostics:t}of s)n.info({uri:e,diagnostics:t},"found issues in spec");displayDiagnostics(s,r,"Some spec checks failed");const o=s.flatMap(({diagnostics:e})=>e),a=o.filter(isError$1).length,c=o.filter(isWarning).length,u=[];a>0&&u.push(`${a} ${pluralize$1("error",a)}`),c>0&&u.push(`${c} ${pluralize$1("warning",c)}`);const l=`${u.join(" and ")} found with spec`;return a>0?r.failure(l):(r.message(`{yellow ${figures.warning} ${l}}`),SUCCESS)}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";return r.failure(`Unable to check spec: ${t}`)}}async function pMap(e,t,{concurrency:r=Number.POSITIVE_INFINITY,stopOnError:n=!0,signal:i}={}){return new Promise((s,o)=>{
3159
3159
  if(void 0===e[Symbol.iterator]&&void 0===e[Symbol.asyncIterator])throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof e})`);if("function"!=typeof t)throw new TypeError("Mapper function is required");if(!(Number.isSafeInteger(r)&&r>=1||r===Number.POSITIVE_INFINITY))throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${r}\` (${typeof r})`);const a=[],c=[],u=new Map;let l=!1,d=!1,p=!1,h=0,A=0;const f=void 0===e[Symbol.iterator]?e[Symbol.asyncIterator]():e[Symbol.iterator](),g=()=>{E(i.reason)},m=()=>{i?.removeEventListener("abort",g)},y=e=>{s(e),m()},E=e=>{l=!0,d=!0,o(e),m()};i&&(i.aborted&&E(i.reason),i.addEventListener("abort",g,{once:!0}));const b=async()=>{if(d)return;const e=await f.next(),r=A;if(A++,e.done){if(p=!0,0===h&&!d){if(!n&&c.length>0)return void E(new AggregateError(c));if(d=!0,0===u.size)return void y(a);const e=[];for(const[t,r]of a.entries())u.get(t)!==pMapSkip&&e.push(r)
3160
- ;y(e)}}else h++,(async()=>{try{const n=await e.value;if(d)return;const i=await t(n,r);i===pMapSkip&&u.set(r,i),a[r]=i,h--,await b()}catch(e){if(n)E(e);else{c.push(e),h--;try{await b()}catch(e){E(e)}}}})()};(async()=>{for(let e=0;e<r;e++){try{await b()}catch(e){E(e);break}if(p||l)break}})()})}const pMapSkip=Symbol("skip");function _nullishCoalesce$x(e,t){return null!=e?e:t()}function _optionalChain$y(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function cMap(e,t,r){const n=_nullishCoalesce$x(_optionalChain$y([r,"optionalAccess",e=>e.concurrency]),()=>8);return pMap(e,t,{...r,concurrency:n})}async function statusWholeProject(e,t){const{reporter:r}=t;r.message("Checking the health status of the project.\n")
3160
+ ;y(e)}}else h++,(async()=>{try{const n=await e.value;if(d)return;const i=await t(n,r);i===pMapSkip&&u.set(r,i),a[r]=i,h--,await b()}catch(e){if(n)E(e);else{c.push(e),h--;try{await b()}catch(e){E(e)}}}})()};(async()=>{for(let e=0;e<r;e++){try{await b()}catch(e){E(e);break}if(p||l)break}})()})}const pMapSkip=Symbol("skip");function _nullishCoalesce$x(e,t){return null!=e?e:t()}function _optionalChain$x(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function cMap(e,t,r){const n=_nullishCoalesce$x(_optionalChain$x([r,"optionalAccess",e=>e.concurrency]),()=>8);return pMap(e,t,{...r,concurrency:n})}async function statusWholeProject(e,t){const{reporter:r}=t;r.message("Checking the health status of the project.\n")
3161
3161
  ;const n=await r.wait("Checking project configuration…",async()=>await getProjectDiagnostics(e));n.length>0&&displayDiagnostics(n,r,"Project checks failed");const i=await r.wait("Finding all specs…",async()=>await listSpecs(e));if(0===i.length)return 0===n.length?r.failure("No specs found in project. Run `tessl create` to create a spec."):r.failure("No specs found in project and configuration issues detected. Fix the issues above, then run `tessl create` to create a spec.");const s=await r.wait("Checking specs…",async()=>await cMap(i,async n=>{try{const[t,r]=await Promise.all([getSpecType(e,n),getDiagnostics(e,n)]),i=r.flatMap(({diagnostics:e})=>e),s=i.filter(isWarning),o=i.filter(isError$1),a=i.length,c=s.length,u=o.length,l=[...new Set(i.map(e=>e.message))];return{spec:n,type:t,issueCount:a,warningCount:c,errorCount:u,issues:l,fixes:[...new Set(i.map(e=>e.resolution.message))]}}catch(i){t.logger.error({error:i},"Unable to run diagnostics on spec"),
3162
3162
  r.alert("error",`Unable to run diagnostics on ${n}: ${i instanceof Error?i.message:String(i)}`);let s="generate";try{s=await getSpecType(e,n)}catch(e){}return{spec:n,type:s,issueCount:1,warningCount:0,errorCount:1,issues:[],fixes:[]}}})),o=s.filter(({type:e})=>"describe"===e),a=s.filter(({type:e})=>"generate"===e),c=o.length,u=a.length;r.message(`{green ${figures.tick}} Found ${i.length} ${pluralize$1("spec",i.length)} (${c} @describe ${pluralize$1("spec",c)} and ${u} @generate ${pluralize$1("spec",u)})`);const l=e=>(e.sort((e,t)=>e.issueCount!==t.issueCount?e.issueCount-t.issueCount:e.spec.localeCompare(t.spec)),e);l(o),l(a);const d=({spec:e,issueCount:t,warningCount:r,errorCount:n})=>{const i=r>0,s=`${n>0?`{red ${figures.cross}`:i?`{yellow ${figures.warning}`:`{green ${figures.tick}`} ${e}}`;if(0===t)return[s];const o=[];return n>0&&o.push(`{red ${n} ${pluralize$1("error",n)}}`),r>0&&o.push(`{yellow ${r} ${pluralize$1("warning",r)}}`),[s,`└─ ${o.join(", ")}`]},p=o.flatMap(d)
3163
3163
  ;a.length>0&&p.push(""),r.list(`{green ${figures.tick}} Checked ${c} @describe ${pluralize$1("spec",c)}`,p,""),r.list(`{green ${figures.tick}} Checked ${u} @generate ${pluralize$1("spec",u)}`,a.flatMap(d),"");const h=s.reduce((e,{errorCount:t})=>e+t,0),A=s.reduce((e,{warningCount:t})=>e+t,0),f=n.flatMap(({diagnostics:e})=>e.filter(isError$1)),g=n.flatMap(({diagnostics:e})=>e.filter(isWarning)),m=f.length,y=g.length,E=h+m,b=E+(A+y),C=s.filter(({errorCount:e})=>e>0),I=s.filter(({warningCount:e})=>e>0);if(b>0){const e=[];return m>0&&e.push(`{red Error: ${m} ${pluralize$1("project error",m)}}`),y>0&&e.push(`{yellow Warning: ${y} ${pluralize$1("project warning",y)}}`),C.length>0&&e.push(`{red Error: ${C.length} ${pluralize$1("spec",C.length)} with errors}`),I.length>0&&e.push(`{yellow Warning: ${I.length} ${pluralize$1("spec",I.length)} with warnings}`),b>0&&e.push("{cyan └─ Run `tessl status <spec-path>` for more details on an individual spec}"),r.message("\n"),
3164
- E>0?r.failure(e.join("\n")):(r.message(e.join("\n")),SUCCESS)}return r.success([`{green ${figures.tick}} All specs are healthy`])}const statusParamsSchema=objectType({spec:stringType().describe("Path to a specific spec being checked, relative to the project root").transform(stripSurroundingQuotes).refine(e=>!e||e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec file must have ${SPEC_FILE_EXTENSION} extension`}).optional()}),statusTool={name:"status",type:"fsd",impl:status,paramsSchema:statusParamsSchema,visibility:"public",description:"Checks the project for errors and suggests fixes. Pass the spec param for details on a specific spec.",positionalParam:"spec"};async function status({fsd:e,params:t,rc:r}){const{spec:n}=t,{logger:i,reporter:s}=r;return s.hideOverview(),n?await statusSingleSpec(e,n,s,i):await statusWholeProject(e,r)}function _nullishCoalesce$w(e,t){return null!=e?e:t()}function _optionalChain$x(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
3164
+ E>0?r.failure(e.join("\n")):(r.message(e.join("\n")),SUCCESS)}return r.success([`{green ${figures.tick}} All specs are healthy`])}const statusParamsSchema=objectType({spec:stringType().describe("Path to a specific spec being checked, relative to the project root").transform(stripSurroundingQuotes).refine(e=>!e||e.endsWith(SPEC_FILE_EXTENSION),{message:`Spec file must have ${SPEC_FILE_EXTENSION} extension`}).optional()}),statusTool={name:"status",type:"fsd",impl:status,paramsSchema:statusParamsSchema,visibility:"public",description:"Checks the project for errors and suggests fixes. Pass the spec param for details on a specific spec.",positionalParam:"spec"};async function status({fsd:e,params:t,rc:r}){const{spec:n}=t,{logger:i,reporter:s}=r;return s.hideOverview(),n?await statusSingleSpec(e,n,s,i):await statusWholeProject(e,r)}function _nullishCoalesce$w(e,t){return null!=e?e:t()}function _optionalChain$w(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
3165
3165
  ("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const evalSummaryParamsSchema=objectType({dir:stringType().describe("Directory to summarize"),excludeTests:booleanType().describe("Whether to exclude tests in the summary").default(!1),excludeReviews:booleanType().describe("Whether to exclude reviews in the summary").default(!1)}),evalSummaryTool={name:"eval-summary",type:"fsd",impl:evalSummary,paramsSchema:evalSummaryParamsSchema,description:"Summarize the results of an eval",visibility:"private"};async function evalSummary({params:e,rc:t}){const{dir:r}=e,{logger:n,projectDir:i}=t;n.info({dir:r},"Starting eval summary");const{excludeTests:s=!1,excludeReviews:o=!1}=e;if(s&&o)return n.warn({dir:r},"Should have at least one of tests or reviews"),1;const a=fs$4.readdirSync(`${i}/${r}`,{withFileTypes:!0}).filter(e=>!e.name.startsWith("."));let c=0,u=0
3166
- ;const l={pass:[],fail:[],missing:[]},d={pass:[],fail:[],missing:[]};for(const e of a){const t=sessionData(`${i}/${r}/${e.name}`);let n=!0;if(!1===s){const r=await t.glob(`**/${testResultFileName}`);if(0===r.length)_optionalChain$x([l,"access",e=>e.missing,"optionalAccess",e=>e.push,"call",t=>t(e.name)]),n=!1;else for(const i of r){const r=await t.readText(i);JSON.parse(r).numErrorTests>0?(_optionalChain$x([l,"access",e=>e.fail,"optionalAccess",e=>e.push,"call",t=>t(e.name)]),n=!1):_optionalChain$x([l,"access",e=>e.pass,"optionalAccess",e=>e.push,"call",t=>t(e.name)])}}if(!1===o){const r=await t.glob("reviews/*.bool");if(0===r.length)_optionalChain$x([d,"access",e=>e.missing,"optionalAccess",e=>e.push,"call",t=>t(e.name)]),n=!1;else for(const i of r){const r=await t.readText(i),s=`${_nullishCoalesce$w(_optionalChain$x([i,"access",e=>e.split,"call",e=>e("/"),"access",e=>e.pop,"call",e=>e(),"optionalAccess",e=>e.replace,"call",e=>e(".bool","")]),()=>"")}: ${e.name}`
3167
- ;"false"===r?(_optionalChain$x([d,"access",e=>e.fail,"optionalAccess",e=>e.push,"call",e=>e(s)]),n=!1):_optionalChain$x([d,"access",e=>e.pass,"optionalAccess",e=>e.push,"call",e=>e(s)])}}n?c++:u++}let p=`${r}\n`;if(c===a.length?p+="✅ All checks passed! 🎉\n\n":p+="❌ Some checks failed! 😢\n\n",p+=`PASSED: ${c}\n`,p+=`FAILED: ${u}\n`,p+=`TOTAL: ${a.length}\n\n`,!1===s){p+="\n\n🚨🚨🚨 Test Error Results 🚨🚨🚨\n";for(const[e,t]of Object.entries(l))p+=`➡️ ${e}:\n ${t.join(", ")}\n`}if(!1===o){p+="\n\n🏁🏁🏁 Review Results 🏁\n";for(const[e,t]of Object.entries(d))p+=`➡️ ${e}:\n ${t.join(", ")}\n`}return await sessionData().writeText(`${r}-summary.md`,p),n.info({summary:p},"Eval summary"),c===a.length?0:1}async function runToolWithDefaults(e,t){return runTool({...e,params:{...defaultDefaults,...e.params}},t)}const paramsSchema$7=objectType({input:stringType().optional().describe("Input directory path containing the suite of packages to evaluate"),
3166
+ ;const l={pass:[],fail:[],missing:[]},d={pass:[],fail:[],missing:[]};for(const e of a){const t=sessionData(`${i}/${r}/${e.name}`);let n=!0;if(!1===s){const r=await t.glob(`**/${testResultFileName}`);if(0===r.length)_optionalChain$w([l,"access",e=>e.missing,"optionalAccess",e=>e.push,"call",t=>t(e.name)]),n=!1;else for(const i of r){const r=await t.readText(i);JSON.parse(r).numErrorTests>0?(_optionalChain$w([l,"access",e=>e.fail,"optionalAccess",e=>e.push,"call",t=>t(e.name)]),n=!1):_optionalChain$w([l,"access",e=>e.pass,"optionalAccess",e=>e.push,"call",t=>t(e.name)])}}if(!1===o){const r=await t.glob("reviews/*.bool");if(0===r.length)_optionalChain$w([d,"access",e=>e.missing,"optionalAccess",e=>e.push,"call",t=>t(e.name)]),n=!1;else for(const i of r){const r=await t.readText(i),s=`${_nullishCoalesce$w(_optionalChain$w([i,"access",e=>e.split,"call",e=>e("/"),"access",e=>e.pop,"call",e=>e(),"optionalAccess",e=>e.replace,"call",e=>e(".bool","")]),()=>"")}: ${e.name}`
3167
+ ;"false"===r?(_optionalChain$w([d,"access",e=>e.fail,"optionalAccess",e=>e.push,"call",e=>e(s)]),n=!1):_optionalChain$w([d,"access",e=>e.pass,"optionalAccess",e=>e.push,"call",e=>e(s)])}}n?c++:u++}let p=`${r}\n`;if(c===a.length?p+="✅ All checks passed! 🎉\n\n":p+="❌ Some checks failed! 😢\n\n",p+=`PASSED: ${c}\n`,p+=`FAILED: ${u}\n`,p+=`TOTAL: ${a.length}\n\n`,!1===s){p+="\n\n🚨🚨🚨 Test Error Results 🚨🚨🚨\n";for(const[e,t]of Object.entries(l))p+=`➡️ ${e}:\n ${t.join(", ")}\n`}if(!1===o){p+="\n\n🏁🏁🏁 Review Results 🏁\n";for(const[e,t]of Object.entries(d))p+=`➡️ ${e}:\n ${t.join(", ")}\n`}return await sessionData().writeText(`${r}-summary.md`,p),n.info({summary:p},"Eval summary"),c===a.length?0:1}async function runToolWithDefaults(e,t){return runTool({...e,params:{...defaultDefaults,...e.params}},t)}const paramsSchema$7=objectType({input:stringType().optional().describe("Input directory path containing the suite of packages to evaluate"),
3168
3168
  output:stringType().describe("Output directory path where evaluation results will be stored"),toolName:stringType().optional().describe("Name of the tool to run on each input package"),toolParams:stringType().optional().describe("JSON string containing default parameters for the tool"),regex:stringType().optional().describe("Regular expression to filter input packages by name"),complement:booleanType().optional().describe("Skip processing packages that already exist in output directory"),branches:numberType().optional().describe("Number of copies to create for each input package"),concurrency:numberType().optional().describe("Maximum number of parallel tool executions")}),evalTool={name:"eval",type:"fsd",impl:runEvaluation,paramsSchema:paramsSchema$7,description:"Runs an eval on given inputs by copying them over to an output directory and running a tool on them.",visibility:"private"};async function arrange(e){const t=await copyAndBranch(e);return await configureAndValidate({
3169
3169
  outputDirectories:t,...e})}async function copyAndBranch({params:e,rc:t,fsd:r}){const{input:n,output:i,branches:s=1,regex:o,complement:a}=e,c=n||join(dirname$1(i),"input");if(!c)throw new Error("Input directory is required");const u=(await r.glob(`${i}/**`)).length>0;if(u&&!a)throw new Error("Output directory exists but complement parameter not provided");t.logger.info({input:c,output:i,branches:s},"Starting copying and branching");const l=await r.glob(`${c}/**`),d=new Set;for(const e of l){const t=relative$1(c,e).split(sep$1),r=t[0];r&&".init"!==r&&t.length>1&&d.add(r)}const p=new Set;if(a&&u)for(const e of d)for(let t=0;t<s;t++){const n=join(i,`${e}=${t}`);if((await r.glob(`${n}/**`)).length>0){p.add(e);break}}t.logger.info({existingPackages:Array.from(p)},"Found existing packages");let h=Array.from(d);if(o){const e=new RegExp(o);h=h.filter(t=>e.test(t))}a&&(h=h.filter(e=>!p.has(e)));const A=await r.glob(`${c}/.init/**`,{dot:!0}),f=A.length>0;if(0===h.length)return t.logger.warn({
3170
3170
  input:c},"No packages found in input directory"),[];t.logger.info({packages:h},"Found packages");for(const e of h){const n=await r.glob(`${c}/${e}/**`,{dot:!0});t.logger.info({packageName:e,fileCount:n.length,branches:s},"Copying package");for(let t=0;t<s;t++){const s=join(i,`${e}=${t}`);if(f)for(const e of A){const t=relative$1(join(c,".init"),e),n=join(s,t),i=await r.readText(e);void 0!==i&&await r.writeText(n,i)}for(const t of n){const n=relative$1(join(c,e),t),i=join(s,n),o=await r.readText(t);void 0!==o&&await r.writeText(i,o)}}}const g=[];for(const e of h)for(let t=0;t<s;t++){const r=join(i,`${e}=${t}`);g.push({name:e,branchIndex:t,outputDir:r})}return t.logger.info({packagesCount:h.length},"Copying and branching completed"),g}async function configureAndValidate({outputDirectories:e,...t}){const{params:r,rc:n,fsd:i}=t;if(n.logger.info({outputDirectoriesCount:e.length},"Starting configuration and validation"),0===e.length)return{packages:[],resolvedTools:new Map}
@@ -3299,10 +3299,10 @@ const t=await n.onError({request:R,error:r,schemaPath:e,params:f,options:D,id:_}
3299
3299
  })):r="object"!=typeof o?"matrix"!==s?r.replace(n,"label"===s?`.${encodeURIComponent(o)}`:encodeURIComponent(o)):r.replace(n,`;${serializePrimitiveParam(e,o)}`):r.replace(n,serializeObjectParam(e,o,{style:s,explode:i}))}return r}function defaultBodySerializer(e,t){if(e instanceof FormData)return e;if(t){if("application/x-www-form-urlencoded"===(t.get instanceof Function?t.get("Content-Type")??t.get("content-type"):t["Content-Type"]??t["content-type"]))return new URLSearchParams(e).toString()}return JSON.stringify(e)}function createFinalURL(e,t){let r=`${t.baseUrl}${e}`;t.params?.path&&(r=defaultPathSerializer(r,t.params.path));let n=t.querySerializer(t.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(r+=`?${n}`),r}function mergeHeaders(...e){const t=new Headers;for(const r of e){if(!r||"object"!=typeof r)continue;const e=r instanceof Headers?r.entries():Object.entries(r)
3300
3300
  ;for(const[r,n]of e)if(null===n)t.delete(r);else if(Array.isArray(n))for(const e of n)t.append(r,e);else void 0!==n&&t.set(r,n)}return t}function removeTrailingSlash$1(e){return e.endsWith("/")?e.substring(0,e.length-1):e}async function initialiseDeviceAuthFlow(e){const t=await fetch("https://api.workos.com/user_management/authorize/device",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e})}),r=await t.json();return{deviceCode:r.device_code,userCode:r.user_code,verificationUri:r.verification_uri,verificationUriComplete:r.verification_uri_complete,expiresIn:r.expires_in,interval:r.interval}}async function pollForTokens({authClientId:e,deviceCode:t,expiresIn:r,interval:n,signal:i}){const s=AbortSignal.timeout(r);for(;;){i&&throwWhenAborted(i);const r=await _fetchTokens({authClientId:e,deviceCode:t,timeoutSignal:s});if("access_token"in r)return{accessToken:r.access_token,refreshToken:r.refresh_token}
3301
3301
  ;if(!("error"in r))return{error:"Authorization failed"};switch(r.error){case"authorization_pending":await sleepWithAbort(n,i);break;case"slow_down":n+=1e3,await sleepWithAbort(n,i);break;case"access_denied":return{error:"Access denied"};case"expired_token":return{error:"Expired token"};default:return{error:"Authorization failed"}}}}async function _fetchTokens(e){try{const t=await fetch("https://api.workos.com/user_management/authenticate",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e.deviceCode,client_id:e.authClientId}),signal:e.timeoutSignal});return await t.json()}catch(e){if(e instanceof Error&&"TimeoutError"===e.name)return{error:"Authorization timed out"};throw e}}async function authenticateWithRefreshToken(e,t){const r=await fetch("https://api.workos.com/user_management/authenticate",{method:"POST",headers:{"Content-Type":"application/json"},
3302
- body:JSON.stringify({grant_type:"refresh_token",client_id:e,refresh_token:t,user_agent:"tessl.cli"})});if(r.ok){const e=await r.json();return{user:{id:e.user.id,email:e.user.email,firstName:e.user.first_name,lastName:e.user.last_name},accessToken:e.access_token,refreshToken:e.refresh_token}}return{error:"Failed to authenticate"}}function getAuthClientId(){const e="client_01HXSHDD9KV92A4892CWHZZDDR";if(!e.startsWith("client_"))throw new Error("Auth client id not set to appropriate value - please check `WORKOS_CLIENT_ID` env var");return e}const DEFAULT_TESSL_PATHS={globalConfigDir:getDefaultGlobalConfigDir(),projDir:process.cwd()};function _nullishCoalesce$t(e,t){return null!=e?e:t()}function _optionalChain$w(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
3303
- const CredsSchema=Type.Object({accessToken:Type.String(),refreshToken:Type.String(),user:Type.Object({id:Type.String(),email:Type.String(),firstName:Type.Optional(Type.String()),lastName:Type.Optional(Type.String()),username:Type.Optional(Type.String())})}),AUTH_FILENAME="api-credentials.json",writeAuth=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const n=resolve$3(r,AUTH_FILENAME);return _optionalChain$w([t,"optionalAccess",e=>e.debug,"call",e=>e({path:n},"writing auth")]),await writeText(n,JSON.stringify(e),384),e},updateAuth=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const n=resolve$3(r,AUTH_FILENAME),i={...await readAuth(t,r),...e};return _optionalChain$w([t,"optionalAccess",e=>e.debug,"call",e=>e({path:n},"updating auth")]),await writeText(n,JSON.stringify(i),384),i},readAuth=async(e,t=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const r=resolve$3(t,AUTH_FILENAME);_optionalChain$w([e,"optionalAccess",e=>e.debug,"call",e=>e({path:r},"reading auth")])
3304
- ;const n=await readFile$2(r),i=JSON.parse(n.toString());if(strictCheck(CredsSchema,i))return deepFreeze(i)},isAuthed=async e=>{if(process.env.TESSL_SIMULATE_LOGOUT)return!1;if(process.env.TESSL_TOKEN)return!0;try{return await readAuth(e.logger,_nullishCoalesce$t(e.basePath,()=>DEFAULT_TESSL_PATHS.globalConfigDir)),!0}catch(e){return!1}},clearAuth=async(e,t=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const r=resolve$3(t,AUTH_FILENAME);_optionalChain$w([e,"optionalAccess",e=>e.debug,"call",e=>e({path:r},"clearing auth")]),existsSync$1(r)?await unlink(r):_optionalChain$w([e,"optionalAccess",e=>e.debug,"call",e=>e({path:r},"auth file does not exist, nothing to clear")])};function _optionalChain$v(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function createDotenvFile(e,t,r,n){
3305
- e.debug({},"provisioning dotenv file");const i=getTesslClient(e,t,r,n),s=await i.GET("/experimental/cli-env");if("error"in s)throw e.error({err:s.error},"Failed to fetch dotenv data"),new Error("Failed to setup environment file: please try again");const o=_optionalChain$v([s,"access",e=>e.data,"optionalAccess",e=>e.data,"optionalAccess",e=>e.attributes,"optionalAccess",e=>e.envVars]);if(!o||"object"!=typeof o)throw e.warn({},"No environment variables received from API"),new Error("Failed to setup environment file: please try again");const a=`# Generated on ${(new Date).toISOString()} from ${t.TESSL_BASE_API_URL}`,c=Object.entries(o).map(([e,t])=>`${e}="${t}"`).join("\n"),u=c?`${a}\n${c}`:a,l=join(r,"dotenv");await mkdir(dirname$1(l),{recursive:!0}),await writeFile(l,u,"utf-8"),await chmod(l,384),e.debug({path:l},"Created dotenv file")}const SKIP_AUTH_ROUTES=["/openapi"];function getTesslClient(e,t,r,n){const i={async onRequest({request:i,schemaPath:s}){
3302
+ body:JSON.stringify({grant_type:"refresh_token",client_id:e,refresh_token:t,user_agent:"tessl.cli"})});if(r.ok){const e=await r.json();return{user:{id:e.user.id,email:e.user.email,firstName:e.user.first_name,lastName:e.user.last_name},accessToken:e.access_token,refreshToken:e.refresh_token}}return{error:"Failed to authenticate"}}function getAuthClientId(){const e="client_01HXSHDD9KV92A4892CWHZZDDR";if(!e.startsWith("client_"))throw new Error("Auth client id not set to appropriate value - please check `WORKOS_CLIENT_ID` env var");return e}const DEFAULT_TESSL_PATHS={globalConfigDir:getDefaultGlobalConfigDir(),projDir:process.cwd()};function _nullishCoalesce$t(e,t){return null!=e?e:t()}function _optionalChain$v(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}
3303
+ const CredsSchema=Type.Object({accessToken:Type.String(),refreshToken:Type.String(),user:Type.Object({id:Type.String(),email:Type.String(),firstName:Type.Optional(Type.String()),lastName:Type.Optional(Type.String()),username:Type.Optional(Type.String())})}),AUTH_FILENAME="api-credentials.json",writeAuth=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const n=resolve$3(r,AUTH_FILENAME);return _optionalChain$v([t,"optionalAccess",e=>e.debug,"call",e=>e({path:n},"writing auth")]),await writeText(n,JSON.stringify(e),384),e},updateAuth=async(e,t,r=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const n=resolve$3(r,AUTH_FILENAME),i={...await readAuth(t,r),...e};return _optionalChain$v([t,"optionalAccess",e=>e.debug,"call",e=>e({path:n},"updating auth")]),await writeText(n,JSON.stringify(i),384),i},readAuth=async(e,t=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const r=resolve$3(t,AUTH_FILENAME);_optionalChain$v([e,"optionalAccess",e=>e.debug,"call",e=>e({path:r},"reading auth")])
3304
+ ;const n=await readFile$2(r),i=JSON.parse(n.toString());if(strictCheck(CredsSchema,i))return deepFreeze(i)},isAuthed=async e=>{if(process.env.TESSL_SIMULATE_LOGOUT)return!1;if(process.env.TESSL_TOKEN)return!0;try{return await readAuth(e.logger,_nullishCoalesce$t(e.basePath,()=>DEFAULT_TESSL_PATHS.globalConfigDir)),!0}catch(e){return!1}},clearAuth=async(e,t=DEFAULT_TESSL_PATHS.globalConfigDir)=>{const r=resolve$3(t,AUTH_FILENAME);_optionalChain$v([e,"optionalAccess",e=>e.debug,"call",e=>e({path:r},"clearing auth")]),existsSync$1(r)?await unlink(r):_optionalChain$v([e,"optionalAccess",e=>e.debug,"call",e=>e({path:r},"auth file does not exist, nothing to clear")])};function _optionalChain$u(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function createDotenvFile(e,t,r,n){
3305
+ e.debug({},"provisioning dotenv file");const i=getTesslClient(e,t,r,n),s=await i.GET("/experimental/cli-env");if("error"in s)throw e.error({err:s.error},"Failed to fetch dotenv data"),new Error("Failed to setup environment file: please try again");const o=_optionalChain$u([s,"access",e=>e.data,"optionalAccess",e=>e.data,"optionalAccess",e=>e.attributes,"optionalAccess",e=>e.envVars]);if(!o||"object"!=typeof o)throw e.warn({},"No environment variables received from API"),new Error("Failed to setup environment file: please try again");const a=`# Generated on ${(new Date).toISOString()} from ${t.TESSL_BASE_API_URL}`,c=Object.entries(o).map(([e,t])=>`${e}="${t}"`).join("\n"),u=c?`${a}\n${c}`:a,l=join(r,"dotenv");await mkdir(dirname$1(l),{recursive:!0}),await writeFile(l,u,"utf-8"),await chmod(l,384),e.debug({path:l},"Created dotenv file")}const SKIP_AUTH_ROUTES=["/openapi"];function getTesslClient(e,t,r,n){const i={async onRequest({request:i,schemaPath:s}){
3306
3306
  if(SKIP_AUTH_ROUTES.includes(s))return;const o=n||await getAndMaybeRefreshAccessToken(e,{...t,NODE_ENV:t.NODE_ENV||"development"},r);return o&&i.headers.set("Authorization",`Bearer ${o}`),i}},s=t.TESSL_BASE_API_URL;if(!s)throw new Error("no base api URL configured");const o=createClient({baseUrl:s});return o.use(i),o}async function getAndMaybeRefreshAccessToken(e,t,r){if(!await isAuthed({logger:e,basePath:r}))return null;const{accessToken:n,refreshToken:i}=await readAuth(e,r);if(!n)throw new Error("No access token found. Please log in with 'tessl login'");const s=srcExports$1.createDecoder(),{exp:o}=s(n);if(Math.floor(Date.now()/1e3)<o-5)return e.debug({},"valid Access token found"),n;if(e.debug({},"Access token expired, refreshing"),!i)throw new Error("No refresh token found. Please log in with 'tessl auth login'");const a=t.WORKOS_CLIENT_ID;if(!a)throw new Error("no auth client id configured");const c=await authenticateWithRefreshToken(a,i)
3307
3307
  ;if("error"in c)throw new Error("Error while authenticating with refresh token");const{accessToken:u,refreshToken:l}=c;await updateAuth({accessToken:u,refreshToken:l},e);try{await createDotenvFile(e,{WORKOS_CLIENT_ID:t.WORKOS_CLIENT_ID,TESSL_BASE_API_URL:t.TESSL_BASE_API_URL,NODE_ENV:t.NODE_ENV},r||DEFAULT_TESSL_PATHS.globalConfigDir)}catch(t){throw e.error({err:t},"Failed to create dotenv file after token refresh"),t}return e.debug({},"Tokens refreshed successfully"),u}function apiErrToString(e){const t=e.errors[0];return`${t.status} ${t.title}\n${t.detail}`}const baseSchema=Type.Object({LOG_LEVEL:Type.Union([Type.Literal("debug"),Type.Literal("info"),Type.Literal("warn"),Type.Literal("error"),Type.Literal("fatal")],{default:"info"}),NODE_ENV:Type.Union([Type.Literal("development"),Type.Literal("test"),Type.Literal("production")],{default:"development"}),GIT_COMMIT_ID:Type.String({default:"unset"}),TESSL_BASE_API_URL:Type.String({default:"https://api.tessl.io/"}),
3308
3308
  TESSL_LOG_LEVEL:Type.Union([Type.Literal("trace"),Type.Literal("debug"),Type.Literal("info"),Type.Literal("warn"),Type.Literal("error"),Type.Literal("fatal"),Type.Literal("silent")],{default:"info"}),TESSL_LOG_FILE:Type.Optional(Type.String()),WORKOS_CLIENT_ID:Type.Optional(Type.String()),TESSL_LLM_API_KEY:Type.Optional(Type.String()),TESSL_LLM_BASE_URL:Type.Optional(Type.String()),TESSL_DISABLE_LLM_CACHE:Type.Optional(Type.Union([Type.Literal("true"),Type.Literal("false")],{default:"false"}))}),cliMonitoringSchema=Type.Composite([Type.Object({LANGFUSE_PROXY_TOKEN:Type.String(),TELEMETRY_USER:Type.String(),TELEMETRY_PASSWORD:Type.String()}),baseSchema]);function validateBaseEnv(e){return validateEnv(baseSchema,e)}function validateEnv(e,t){const r=structuredClone(t);return Default(e,r),Check(e,r)||throwValidationError(e,r),Clean(e,r),r}Type.Composite([Type.Object({GRPC_BIND_ADDR:Type.String({default:"[::]:5054"}),HTTP_BIND_PORT:Type.String({default:"5055"}),WS_BIND_PORT:Type.String({
@@ -3376,14 +3376,13 @@ entries:i})}});function _enum(e,t){const r=Array.isArray(e)?Object.fromEntries(e
3376
3376
  e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable({type:"nullable",innerType:e})}const ZodDefault=$constructor("ZodDefault",(e,t)=>{$ZodDefault.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():t}})}const ZodPrefault=$constructor("ZodPrefault",(e,t)=>{$ZodPrefault.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():t}})}const ZodNonOptional=$constructor("ZodNonOptional",(e,t)=>{$ZodNonOptional.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:"nonoptional",innerType:e,...normalizeParams(t)})}const ZodCatch=$constructor("ZodCatch",(e,t)=>{$ZodCatch.init(e,t),ZodType.init(e,t),
3377
3377
  e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const ZodPipe=$constructor("ZodPipe",(e,t)=>{$ZodPipe.init(e,t),ZodType.init(e,t),e.in=t.in,e.out=t.out});function pipe$3(e,t){return new ZodPipe({type:"pipe",in:e,out:t})}const ZodReadonly=$constructor("ZodReadonly",(e,t)=>{$ZodReadonly.init(e,t),ZodType.init(e,t)});function readonly(e){return new ZodReadonly({type:"readonly",innerType:e})}const ZodCustom=$constructor("ZodCustom",(e,t)=>{$ZodCustom.init(e,t),ZodType.init(e,t)});function check$1(e){const t=new $ZodCheck({check:"custom"});return t._zod.check=e,t}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e){const t=check$1(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(issue(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),
3378
3378
  n.continue??(n.continue=!t._zod.def.abort),r.issues.push(issue(n))}},e(r.value,r)));return t}const TesslJsonSchema=object$1({name:string$1(),dependencies:record(string$1(),object$1({version:string$1()})).optional()}),TESSL_JSON_FILENAME="tessl.json";async function hasTesslJson(e){try{return await access(path__default$1.join(e,TESSL_JSON_FILENAME)),!0}catch(e){return!1}}async function readTesslJson$1(e){const t=path__default$1.join(e,TESSL_JSON_FILENAME),r=await readFile$1(t,"utf-8");return JSON.parse(r)}function safeParseTesslJson(e){return TesslJsonSchema.safeParse(e)}function validateTesslJson(e){const t=safeParseTesslJson(e);if(!t.success)throw new Error(`Tessl JSON validation failed: ${t.error.message}`);return t.data}function ensureTesslJsonSync(e,t){const r=path__default$1.join(e,TESSL_JSON_FILENAME);if(!existsSync(r))return writeFileSync$1(r,JSON.stringify(t,null,2)),path__default$1.relative(e,r)}async function throwIfNotInitialised(e){
3379
- if(!await hasTesslJson(e))throw new RequiresInitError;validateTesslJson(await readTesslJson$1(e))}function _nullishCoalesce$s(e,t){return null!=e?e:t()}function _optionalChain$u(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const TileManifest=object$1({docs:string$1(),describes:string$1(),name:string$1(),version:string$1(),summary:string$1()}),USAGE_SPEC_DIR_NAME="usage-specs",USAGE_SPEC_DIR_PATH=join$1(CONFIG_DIR_NAME,USAGE_SPEC_DIR_NAME);async function isAlreadyInstalled(e){if(!await exists(e))return!1;const t=join$1(e,SPEC_MANIFEST_NAME);if(!await exists(t))return await rmdir(e,{recursive:!0}),!1;const r=await readText(t),n=JSON.parse(r);return!!TileManifest.safeParse(n).success||(await rmdir(e,{recursive:!0}),!1)}async function downloadAndWriteTile(e,t,r,n,i){
3380
- const s=join$1(e,r,n,i);if(!await isAlreadyInstalled(s)){const e=await t.GET("/v1/tiles/{workspaceName}/{tileName}/versions/{version}/files",{params:{path:{workspaceName:r,tileName:n,version:i},header:{accept:"application/gzip"}},parseAs:"arrayBuffer"});if(e.error)return{success:!1,error:apiErrToString(e.error)};const o=await writeDocs(Buffer.from(e.data),s);if(!o.success)return{success:!1,error:o.errMsg}}const o=join$1(s,SPEC_MANIFEST_NAME);if(!await exists(o))return{success:!1,error:`Download is malformed: ${SPEC_MANIFEST_NAME} manifest not found in ${s}`};const a=await readText(o),c=JSON.parse(a),u=TileManifest.safeParse(c);return u.success?{success:!0,manifest:u.data}:{success:!1,error:`Download is malformed: ${o} is invalid`}}async function writeDocs(e,t){try{return await extractTarGz(e,t),{success:!0}}catch(e){return{success:!1,errMsg:`Failed to extract usage spec files: ${e instanceof Error?e.message:"Unknown error"}`}}}async function extractTarGz(e,t){
3381
- return new Promise((r,n)=>{const i=tarStreamExports.extract();i.on("entry",(e,r,i)=>{(async()=>{try{if("file"===e.type){const n=safeJoin(t,e.name);await mkdir$1(dirname(n),{recursive:!0});const i=createWriteStream(n);await pipeline$1(r,i)}else r.resume();i()}catch(e){n(e instanceof Error?e:new Error(String(e)))}})().catch(e=>{n(e instanceof Error?e:new Error(String(e)))})}),i.on("error",n),i.on("finish",r);const s=createGunzip$1();s.on("error",n);Readable.from(e).pipe(s).pipe(i)})}function safeJoin(e,t){const r=normalize$3(join$1(e,t)),n=normalize$3(resolve$3(e))+sep$2;if(!r.startsWith(n))throw new Error(`Refusing to write outside destination: ${t}`);return r}function purlToNameAndLink(e){if(e.startsWith("pkg:"))try{const t=packageurlJsExports.PackageURL.fromString(e),{namespace:r,name:n}=t;return{name:r?`${r}/${n}`:n,link:_optionalChain$u([purlToPackageRegistry,"access",e=>e[t.type],"optionalCall",e=>e(t)])}}catch(t){return{name:e}}return{name:e}}const purlToPackageRegistry={
3382
- npm:e=>`https://npmjs.com/package/${e.namespace?`${e.namespace}/${e.name}`:e.name}`,pypi:e=>`https://pypi.org/project/${e.name}`,github:e=>`https://github.com/${e.namespace}/${e.name}`},SPEC_MANIFEST_NAME="specs.json";async function readTesslJson(e){const t=await e.readText(TESSL_JSON_FILENAME);if(void 0===t)return{success:!1,error:"Tessl JSON not found"};const r=safeParseTesslJson(JSON.parse(t));return r.success?{success:!0,data:r.data}:{success:!1,error:r.error.message}}async function updateTesslJsonDependencies(e,{add:t,remove:r}){if(!t&&!r)return{success:!0};const n=await readTesslJson(e);if(!n.success)return{success:!1,error:n.error};const i=n.data,s=structuredClone(_nullishCoalesce$s(i.dependencies,()=>({})));for(const e of _nullishCoalesce$s(r,()=>[]))delete s[e];for(const{workspaceName:e,tileName:r,newVersion:n}of _nullishCoalesce$s(t,()=>[])){s[`${e}/${r}`]={version:n}}const o=Object.fromEntries(Object.entries(s).sort((e,t)=>e[0].localeCompare(t[0]))),a={...i,dependencies:o}
3383
- ;try{const t=JSON.stringify(a,null,2)+EOL;await e.writeText(TESSL_JSON_FILENAME,t)}catch(e){return{success:!1,error:e instanceof Error?e.message:"Error updating Tessl JSON"}}return{success:!0}}async function syncUsageSpecs(e,t,r){const n=await readTesslJson(t);if(!n.success)return{success:!1,error:n.error};const i=n.data,s=path__default$1.join(e,USAGE_SPEC_DIR_PATH);await t.exists(s)||await mkdir$1(s,{recursive:!0});const o=await pMap(Object.entries(_nullishCoalesce$s(i.dependencies,()=>({}))),async([e,{version:t}])=>{const[n,i]=e.split("/");return n&&i?downloadAndWriteTile(s,r,n,i,t):{success:!1,error:`Invalid name: ${e}`}},{concurrency:8});if(!o.every(e=>e.success)){return{success:!1,error:o.filter(e=>!e.success).map(e=>e.error).join("\n")}}return await createKnowledgeDoc(t,o.map(e=>e.manifest)),{success:!0}}const KNOWLEDGE_MD_FILENAME="KNOWLEDGE.md";async function createKnowledgeDoc(e,t){const r=t.map(e=>{
3384
- const t=packageurlJsExports.PackageURL.fromString(e.describes),[r,n]=e.name.split("/");return{name:t.namespace?`${t.namespace}/${t.name}@${t.version}`:`${t.name}@${t.version}`,summary:e.summary,path:join$1(USAGE_SPEC_DIR_PATH,r,n,e.version,e.docs)}}),n=`# Knowledge Index\n\n## Dependencies\n\nConsult the relevant documentation when using any of the dependencies listed below:\n\n${r.map(({name:e,summary:t,path:r})=>`### ${e}\n\n${t}\n\n[docs](${r})`).join("\n\n")}\n`;await e.writeText(KNOWLEDGE_MD_FILENAME,n)}async function getSpecUpdates(e,t){const r=[],n=[],i=[],s=[];return await pMap(Object.entries(_nullishCoalesce$s(e.dependencies,()=>({}))),async([e,{version:o}])=>{const[a,c]=e.split("/");if(!a||!c||!o)return void s.push({tileName:e,tileVersion:o,error:`Invalid name: ${e}`});const[u,l,d]=o.split("."),[p,h,A]=await Promise.all([t.GET("/v1/tiles/{workspaceName}/{tileName}/versions",{params:{path:{workspaceName:a,tileName:c},query:{"filter[major][eq]":u,"filter[minor][eq]":l,
3385
- "filter[patch][gt]":d,"page[size]":1}}}),t.GET("/v1/tiles/{workspaceName}/{tileName}/versions",{params:{path:{workspaceName:a,tileName:c},query:{"filter[major][eq]":u,"filter[minor][gt]":l,"page[size]":1}}}),t.GET("/v1/tiles/{workspaceName}/{tileName}/versions",{params:{path:{workspaceName:a,tileName:c},query:{"filter[major][gt]":u,"page[size]":1}}})]);if(A.error||h.error||p.error){const e=A.error||h.error||p.error;return void s.push({tileName:c,tileVersion:o,error:e?apiErrToString(e):"Unknown error while checking for updates"})}const f=A.data.data[0],g=h.data.data[0],m=p.data.data[0];f&&r.push({workspaceName:a,tileName:c,tileVersion:o,newVersion:f.attributes.version,docPath:f.attributes.docs}),g&&n.push({workspaceName:a,tileName:c,tileVersion:o,newVersion:g.attributes.version,docPath:g.attributes.docs}),m&&i.push({workspaceName:a,tileName:c,tileVersion:o,newVersion:m.attributes.version,docPath:m.attributes.docs})},{concurrency:8}),{majorUpdates:r,minorUpdates:n,patchUpdates:i,
3386
- updateCheckFailures:s}}const paramsSchema$1=z.object({name:z.string().describe('The full name of the tile e.g. "tessl/svelte@5.38.0". The version is optional; if omitted, the latest version will be used')}),installTool={name:"install",type:"fsd",impl:installToolImpl,paramsSchema:paramsSchema$1,description:'Install docs (usage specs) for your project by providing the full name of the spec e.g. "tessl/svelte@5.38.0". If a version is not provided, the latest version will be used. This can help provide context for your LLM tooling. You can find more with the search tool',visibility:"private"};async function installToolImpl({params:e,fsd:t,rc:{reporter:r,tesslClient:n,projectDir:i}}){const{name:s}=e;if(s){const e=s.split("@"),i=e[0];let o=e[1];if(!i)return r.failure('The name argument must be in the format "workspace/tile" (or "workspace/tile@version")');const[a,c]=i.split("/")
3379
+ if(!await hasTesslJson(e))throw new RequiresInitError;validateTesslJson(await readTesslJson$1(e))}function _nullishCoalesce$s(e,t){return null!=e?e:t()}const TileManifest=object$1({docs:string$1(),describes:string$1(),name:string$1(),version:string$1(),summary:string$1()}),USAGE_SPEC_DIR_NAME="usage-specs",USAGE_SPEC_DIR_PATH=join$1(CONFIG_DIR_NAME,USAGE_SPEC_DIR_NAME);async function shouldInstall(e){if(!await exists(e))return!0;const t=join$1(e,SPEC_MANIFEST_NAME);if(!await exists(t))return!0;const r=await readText(t),n=JSON.parse(r);return!TileManifest.safeParse(n).success}async function downloadAndWriteTile(e,t,r,n,i){const s=join$1(e,r,n,i);if(await shouldInstall(s)){const e=await t.GET("/v1/tiles/{workspaceName}/{tileName}/versions/{version}/files",{params:{path:{workspaceName:r,tileName:n,version:i},header:{accept:"application/gzip"}},parseAs:"arrayBuffer"});if(e.error)return{success:!1,error:apiErrToString(e.error)};const o=await writeDocs(Buffer.from(e.data),s)
3380
+ ;if(!o.success)return{success:!1,error:o.errMsg}}const o=join$1(s,SPEC_MANIFEST_NAME);if(!await exists(o))return{success:!1,error:`Download is malformed: ${SPEC_MANIFEST_NAME} manifest not found in ${s}`};const a=await readText(o),c=JSON.parse(a),u=TileManifest.safeParse(c);return u.success?{success:!0,manifest:u.data}:{success:!1,error:`Download is malformed: ${o} is invalid`}}async function writeDocs(e,t){try{return await extractTarGz(e,t),{success:!0}}catch(e){return{success:!1,errMsg:`Failed to extract usage spec files: ${e instanceof Error?e.message:"Unknown error"}`}}}async function extractTarGz(e,t){return new Promise((r,n)=>{const i=tarStreamExports.extract();i.on("entry",(e,r,i)=>{(async()=>{try{if("file"===e.type){const n=safeJoin(t,e.name);await mkdir$1(dirname(n),{recursive:!0});const i=createWriteStream(n);await pipeline$1(r,i)}else r.resume();i()}catch(e){n(e instanceof Error?e:new Error(String(e)))}})().catch(e=>{n(e instanceof Error?e:new Error(String(e)))})}),
3381
+ i.on("error",n),i.on("finish",r);const s=createGunzip$1();s.on("error",n);Readable.from(e).pipe(s).pipe(i)})}function safeJoin(e,t){const r=normalize$3(join$1(e,t)),n=normalize$3(resolve$3(e))+sep$2;if(!r.startsWith(n))throw new Error(`Refusing to write outside destination: ${t}`);return r}const SPEC_MANIFEST_NAME="specs.json";async function readTesslJson(e){const t=await e.readText(TESSL_JSON_FILENAME);if(void 0===t)return{success:!1,error:"Tessl JSON not found"};const r=safeParseTesslJson(JSON.parse(t));return r.success?{success:!0,data:r.data}:{success:!1,error:r.error.message}}async function updateTesslJsonDependencies(e,{add:t,remove:r}){if(!t&&!r)return{success:!0};const n=await readTesslJson(e);if(!n.success)return{success:!1,error:n.error};const i=n.data,s=structuredClone(_nullishCoalesce$s(i.dependencies,()=>({})));for(const e of _nullishCoalesce$s(r,()=>[]))delete s[e];for(const{workspaceName:e,tileName:r,newVersion:n}of _nullishCoalesce$s(t,()=>[])){s[`${e}/${r}`]={version:n
3382
+ }}const o=Object.fromEntries(Object.entries(s).sort((e,t)=>e[0].localeCompare(t[0]))),a={...i,dependencies:o};try{const t=JSON.stringify(a,null,2)+EOL;await e.writeText(TESSL_JSON_FILENAME,t)}catch(e){return{success:!1,error:e instanceof Error?e.message:"Error updating Tessl JSON"}}return{success:!0}}async function syncUsageSpecs(e,t,r){const n=await readTesslJson(t);if(!n.success)return{success:!1,error:n.error};const i=n.data,s=path__default$1.join(e,USAGE_SPEC_DIR_PATH);await t.exists(s)||await mkdir$1(s,{recursive:!0});const o=await pMap(Object.entries(_nullishCoalesce$s(i.dependencies,()=>({}))),async([e,{version:t}])=>{const[n,i]=e.split("/");return n&&i?downloadAndWriteTile(s,r,n,i,t):{success:!1,error:`Invalid name: ${e}`}},{concurrency:8});if(!o.every(e=>e.success)){return{success:!1,error:o.filter(e=>!e.success).map(e=>e.error).join("\n")}}return await createKnowledgeDoc(t,o.map(e=>e.manifest)),{success:!0}}const KNOWLEDGE_MD_FILENAME="KNOWLEDGE.md"
3383
+ ;async function createKnowledgeDoc(e,t){const r=t.map(e=>{const t=packageurlJsExports.PackageURL.fromString(e.describes),[r,n]=e.name.split("/");return{name:t.namespace?`${t.namespace}/${t.name}@${t.version}`:`${t.name}@${t.version}`,summary:e.summary,path:join$1(USAGE_SPEC_DIR_PATH,r,n,e.version,e.docs)}}),n=`# Knowledge Index\n\n## Dependencies\n\nConsult the relevant documentation when using any of the dependencies listed below:\n\n${r.map(({name:e,summary:t,path:r})=>`### ${e}\n\n${t}\n\n[docs](${r})`).join("\n\n")}\n`;await e.writeText(KNOWLEDGE_MD_FILENAME,n)}async function getSpecUpdates(e,t){const r=[],n=[],i=[],s=[];return await pMap(Object.entries(_nullishCoalesce$s(e.dependencies,()=>({}))),async([e,{version:o}])=>{const[a,c]=e.split("/");if(!a||!c||!o)return void s.push({tileName:e,tileVersion:o,error:`Invalid name: ${e}`});const[u,l,d]=o.split("."),[p,h,A]=await Promise.all([t.GET("/v1/tiles/{workspaceName}/{tileName}/versions",{params:{path:{workspaceName:a,tileName:c},
3384
+ query:{"filter[major][eq]":u,"filter[minor][eq]":l,"filter[patch][gt]":d,"page[size]":1}}}),t.GET("/v1/tiles/{workspaceName}/{tileName}/versions",{params:{path:{workspaceName:a,tileName:c},query:{"filter[major][eq]":u,"filter[minor][gt]":l,"page[size]":1}}}),t.GET("/v1/tiles/{workspaceName}/{tileName}/versions",{params:{path:{workspaceName:a,tileName:c},query:{"filter[major][gt]":u,"page[size]":1}}})]);if(A.error||h.error||p.error){const e=A.error||h.error||p.error;return void s.push({tileName:c,tileVersion:o,error:e?apiErrToString(e):"Unknown error while checking for updates"})}const f=A.data.data[0],g=h.data.data[0],m=p.data.data[0];f&&r.push({workspaceName:a,tileName:c,tileVersion:o,newVersion:f.attributes.version,docPath:f.attributes.docs}),g&&n.push({workspaceName:a,tileName:c,tileVersion:o,newVersion:g.attributes.version,docPath:g.attributes.docs}),m&&i.push({workspaceName:a,tileName:c,tileVersion:o,newVersion:m.attributes.version,docPath:m.attributes.docs})},{concurrency:8}),{
3385
+ majorUpdates:r,minorUpdates:n,patchUpdates:i,updateCheckFailures:s}}const paramsSchema$1=z.object({name:z.string().describe('The full name of the tile e.g. "tessl/svelte@5.38.0". The version is optional; if omitted, the latest version will be used')}),installTool={name:"install",type:"fsd",impl:installToolImpl,paramsSchema:paramsSchema$1,description:'Install docs (usage specs) for your project by providing the full name of the spec e.g. "tessl/svelte@5.38.0". If a version is not provided, the latest version will be used. This can help provide context for your LLM tooling. You can find more with the search tool',visibility:"private"};async function installToolImpl({params:e,fsd:t,rc:{reporter:r,tesslClient:n,projectDir:i}}){const{name:s}=e;if(s){const e=s.split("@"),i=e[0];let o=e[1];if(!i)return r.failure('The name argument must be in the format "workspace/tile" (or "workspace/tile@version")');const[a,c]=i.split("/")
3387
3386
  ;if(!a||!c)return r.failure('The name argument must be in the format "workspace/tile" (or "workspace/tile@version")');const u=await n.GET("/v1/tiles/{workspaceName}/{tileName}",{params:{path:{workspaceName:a,tileName:c}}});if(u.error)return r.failure(apiErrToString(u.error));const l=u.data.data;if(!o){const e=l.attributes.latestVersion;if(!e)return r.failure("The tile does not have a latest version. Please specify a version");o=e}const d=await n.GET("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:a,tileName:c,version:o}}});if(d.error)return r.failure(apiErrToString(d.error));const p=d.data.data;if(!p.attributes.describes)return r.failure("Invalid usage spec; does not describe a package");const h=await updateTesslJsonDependencies(t,{add:[{workspaceName:a,tileName:c,newVersion:p.attributes.version}]});if(!h.success)return r.failure(h.error)}const o=await syncUsageSpecs(i,t,n);return o.success?r.success():r.failure(o.error)}
3388
3387
  const execCommand=async(e,t,r)=>{const n=await r.exec({cmd:e,cwd:t,timeoutSecs:600,mergeStdStreams:!0}),i=0===n.code?0:1;return{text:n.stdout,status:i}};function _optionalChain$t(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}const runCICommandParamsSchema=objectType({}),runCiTool={name:"run-ci",type:"fsd",impl:runCi,paramsSchema:runCICommandParamsSchema,description:"Runs project-level CI-type checks. This requires a ciCommand to be set in the config otherwise it will error.",visibility:"private",denyRunIn:["cloud"]};async function runCi({rc:e}){const{reporter:t,logger:r,projectDir:n,projectConfig:i}=e,s=_optionalChain$t([i,"optionalAccess",e=>e.ciCommand]);if(!s||0===s.length)return t.failure(stripIndent`Config does not contain a ciCommand, this is required for this tool to run.
3389
3388
  This is configured in ${TESSL_CONFIG_FILE_NAME}.`);r.debug({ciCommand:s},"Using the following CI command");let o="";const a=[];for(const r of s){const{text:i,status:s}=await execCommand(r,n,e);o+=i,t.message(`CI command output:\n${i}`),a.push(s)}if(!o)return t.failure("CI command gave no output, try running the command manually to see what the issue is",{ciCommand:s});r.debug({ciOutput:o},"CI output");const c=sessionData();await c.writeText("ci-output.txt",o);const u=path__default$1.join(c.root,"ci-output.txt");return r.info({ciOutput:o,ciOutputPath:u},"CI output"),a.some(e=>e===FAILURE)?t.failure("Some CI commands failed",{returnCodes:a}):t.success(["CI completed successfully",`${a.length} command${a.length>1?"s":""} executed`,`Output saved to: ${u}`])}const paramsSchema=z.object({query:z.string().describe("A name, package-url, or package registry web url").transform(stripSurroundingQuotes)}),searchTool={name:"search",type:"fsd",impl:searchToolImpl,paramsSchema,
@@ -3449,190 +3448,191 @@ if(r.upArrow||r.downArrow||r.ctrl&&"c"===t||r.tab||r.shift&&r.tab)return;if(r.re
3449
3448
  const feedbackCommand=new Command$1({name:"feedback",summary:"Send feedback to the Tessl team",requiresConfig:!1,positionals:[{name:"message",description:"The user's feedback message. Requested interactively if not provided"}],handler:async({monitoring:e,positionals:t,isInteractive:r})=>{const n=t.message,i=t=>{e.posthogCapture({event:"survey sent",properties:{sessionId:e.analytics.getSessionId(),projectId:e.analytics.getProjectId(),$survey_id:"0197d0d3-6704-0000-e36e-569911acb8ee",$survey_questions:[{id:"e34e48fc-938a-4af1-b255-3c55d6bdcbc7",question:"Feedback message"}],"$survey_response_e34e48fc-938a-4af1-b255-3c55d6bdcbc7":t}})};if(n)return i(n),render(jsxRuntimeExports.jsx(Feedback,{initialMessage:n,onSubmit:()=>{}})),Promise.resolve(SUCCESS);if(!r)throw new ExpectedError("In non-interactive mode, you must provide a feedback message as an argument");return new Promise(e=>{render(jsxRuntimeExports.jsx(Feedback,{onSubmit:t=>{t.trim()?(i(t.trim()),
3450
3449
  render(jsxRuntimeExports.jsx(Thanks,{})),e(SUCCESS)):(render(jsxRuntimeExports.jsx(Text,{color:"yellow",children:"Feedback submission cancelled - message was empty."})),e(FAILURE))}}))})}
3451
3450
  }),content$6="\n# Tessl\n\nTessl is a [spec driven development](./docs/spec-driven-development.md) framework and toolkit: @docs/spec-driven-development.md\n\n## Spec Driven Software Development Lifecycle\n\n### User Engagement\n\nUsers should be encouraged to engage directly with specs, so that they understand what is being asked for (or documented), and can steer the software development processes.\n\nIn order to do this, agents should:\n\n1. Interview the user to get details before creating or updating specs (but ask one or two questions at a time, so as not to overwhelm them).\n2. Ask for feedback on specs before building them. This should include pointing out key implementation choices, and highlighting any gaps in the spec.\n3. Include interview/feedback points as separate tasks in plans, so these steps are not skipped.\n\n### Primary Workflow: Spec to code\n\nSoftware is developed by creating or editing a spec and then `building` that spec to generate or update the implementation and then `fixing` to refine the spec and implementation until it works as intended.\n\n1. Create/edit the spec to reflect the desired functionality/changes requested, using the appropriate Tessl tool and providing it with relevant context (see the \"Using Tessl Tools\" instructions below)\n2. Install any new required dependencies from the spec\n3. Build the spec to generate the implementation code from the updated spec and fix\n4. When/if the user asks for tests, add them to the spec and generate them and fix.\n\n### Alternative Workflow: Code to spec\n\nSometimes the user may decide to change the code directly, or they may have legacy code they want to document. In such cases:\n\n1. Document the code changes into the spec + fix spec/tests to match observed code behaviors\n2. If the spec is changed, flag any capabilities that are lost or changed.\n\n### Using Tessl Tools\n\nTessl tools allow targeted changes to spec, code and test files ensuring that the methodology is followed, and that the correct context is provided at each step.\n\nBefore using any Tessl tool (`create`, `edit`, `build`, `document` etc) you must:\n\n1. **First: Check Knowledge Index:**\n\n - Read `./KNOWLEDGE.md` (the Knowledge Index)\n - Consider the Tessl tool call you're about to make, including any parameters\n - Decide if any entries in the Knowledge Index seem directly relevant to the current task\n - If so, spawn a research sub-agent to dig deeper into the chosen documents\n - If not, skip research and just call the tool\n\n2. **Research context** - Spawn a research sub-agent with details about:\n\n - The Knowledge Index candidates to explore\n - The specific Tessl tool you're about to call\n - The inputs to that tool call (what you're building, which files, etc.)\n\n3. **Research sub-agent identifies relevant context file paths:**\n\n - Explore the provided Knowledge Index entries\n - **Return**: Only relevant file paths (relative to the project root)\n\n4. **Then: Call the Tessl tool** - Use the file paths returned by the research sub-agent (relative to project root) in the `--context` parameter.\n\nRemember the research output and re-use it for similar tool calls (where the tool and inputs are the same).\n\nUse Tessl tools to:\n\n- Capture requirements for new code files in specs using the `create` tool\n- Edit specs / code / tests whenever the user wants to introduce or change behavior in existing specs / code / tests with the `edit` tool\n- Build code and tests from specs using the `build` and `build-tests` tools\n- Document code into specs using the `document` tool\n- Run tests using the `test` tool\n- Add extra functionality to code, by editing the spec and rebuilding\n- Check project and spec status using the `status` tool\n\nTessl also provides the capability to run its tools in parallel. Use this when you have multiple tasks to do that are independent of each other - e.g. rebuilding multiple specs at once.\n\n### Detailed Expectations Around Fixing Code and Tests:\n\nA key concept in spec-driven development is that built code and tests should be run to verify conformity to the spec. Often, however, working code and useful tests are not made on the first attempt. \n\nTessl tools will attempt to 'fix' before finishing build, but agents may need to continue or debug this process. \n\nBy default, the spec will have few if any test cases to start with, focus on getting the functionality working and then if the user asks for more tests, add them to the spec and generate them.\n\nTests should be prioritised in the following order:\n- Locked tests. Make sure the code is able to pass these tests, they are core functional requirements that have been confirmed by the user.\n- Draft tests. If draft tests have been generated, try to make the code pass. These tests have not been fully validated, so their definition or implementation may need to be refined until useful or removed altogether.\n- Impl tests. If generated, then try to make the code pass. These tests were created to capture details in an implementation that may not be important, so they may be deleted if they are no longer valid.\n\nFixes should be applied in this preference order:\n1. (Preferred fix): Install dependencies explicitly listed in the spec if needed.\n2. (Preferred fix): Iteratively run tests and update code to address errors, until the code passes the tests.\n3. (Cautious fix): Iteratively fix implementation errors in tests (e.g. syntax errors) and check they are still faithful to the spec.\n4. (Last resort): Identify if the spec contains errors, ambiguities or hard to implement definitions. Ask the user for how to proceed.\n\n**Never** simply remove requirements from the spec.\n**Never** add new capabilities to the code without updating the spec to capture how it will be verified.\n\n**Setup/Configuration errors**\nIt's possible the error stems from the overall project set up, in this case:\n\n- Ask the user to add dependencies to the spec if they are implied or necessary for the capabilities required.\n- Help the user configure their project further and make sure that their development environment is working.\n- Make sure that project details like the language(s), test runner(s) and ecosystem(s), and any testing or implementation guidelines are added to AGENTS.md to help guide the Tessl tools to produce consistent implementations that adhere to them.\n\n### Software Decomposition\n\nSpecs should map 1:1 with code files, with the structure of the specs and the links between them matching the intended decomposition of the software.\n\nIf the user asks for new functionality that would be challenging to fit into a single spec and code file, then you should first suggest decomposition approaches with them, and then make a plan to iteratively build up the software spec by spec.\n\nMake sure that specs link to each other as needed, and that there is a clear entry-point.\n\n**Pointers:**\n\n- Prefer to work in an incremental way, building up the software one piece at a time, improving the software with each iteration. Suggest a simple starting point, and include tasks in your plan to add additional features one by one later.\n- Check generated specs to make sure that they link to one another via \"dependencies\" links, and if not, call edit spec and ask for the dependency to be added.\n- Add more details on project expectations to AGENTS.md if you need more consistency in the project across specs - for example, on choices on key external dependencies, or testing guidelines.\n- Make sure the user provides explicit feedback and approval before deciding on a decomposition and beginning to create multiple specs and building them all.\n\n## The Knowledge Index\n\nThe Knowledge Index is a centralized reference for documentation about dependencies and processes used in the project.\n\nIt's stored in `./KNOWLEDGE.md` and contains links to versioned documentation files.\n\nThe Knowledge Index helps ensure consistency when selecting dependency versions and provides quick access to relevant documentation during development.\n\n## Important\n\nAlways modify code, tests or specs using Tessl tools. The only exceptions are when the user approves this behavior interactively. In either case **specs and generated code and tests must be always in sync**\n",content$5='\n# Project Information Bootstrapping\n\nBefore you can use any Tessl tools, you need to write information about the project into the AGENTS.md file\n\nFollow these steps:\n\n## 1. Interview\n\nWork out the following information, either by:\na. working out what setup already exists in the directory and confirming it with the user, or \nb. by interviewing the user interactively to work out what they\'d like to use:\n\nCover:\n- What stack to use (e.g. Node, TypeScript/ESM, Python, Java/Maven)\n- What testing framework to use (you can provide suggestions like `vitest`)\n- Where to put specs, code files and test files (e.g. `./specs`, `./src`, `./tests`)\n- How to set up the development environment (e.g. environment management and build tools)\n\nAsk these questions one at a time, and ask follow up questions when answers are unclear.\n\n## 2. Setup\n\nUsing the supplied information, perform any necessary steps to get the project set up as needed. This might involve creating directories, or installing a minimal set of core dependencies. Consider the local Knowledge Index when selecting dependency versions, if it exists.\n\n## 3. Update Project Configuration\n\nRecord the project configuration information in `./AGENTS.md` and remove the "New Project Bootstrapping" section from the file. Make sure to include the test command(s).\n\nWhen writing up the test command(s), beware of "watch mode" that might interfere with agentic testing feedback loops. For example: the `vitest` command will run in watch mode by default, which will appear to hang as it will not exit - instead the `vitest run` command should be used.\n\n## 4. Interview the user about their task\n\nBefore making a spec or making code changes, you should again interview the user about their task. This time, ask clarifying questions about the details of what they want to build, and the plan to build it. \n\nUsers are generally more successful if:\na. they approach the task in an agile way, building the software in small increments, focussing on one or two files at the most each time. See if there\'s a way to start simply and add details about extra features to the plan to be added later, after you get the first slice working.\nb. you get feedback from them about the spec before starting to build it. For example, ask if the test definitions are precise enough, and whether key capabilities are reflected in the spec.\n\nInclude steps in your plan for when you need to get feedback from the user.\n\n',content$4="\n# Spec Driven Development (SDD)\n\nSpec driven development places specs at the center of the software development lifecycle. Specs are considered the canonical source of truth when they are verifiable. Code is considered disposable when it can be reliably regenerated from a spec.\n\nSpecs capture _intent_, and may contain or link to files containing the API and test cases. Over time specs are updated to add new features or requirements, and code is regenerated to align with the specs.\n\nEach spec usually maps 1:1 to a code file. Larger units are composed of multiple linked specs (via dependencies), mirroring decomposition. A linked set of specs with their code and tests is a **tile** or **Tessl tile**. Projects may contain multiple tiles.\n\n## Specs\n\n- Follow the [Spec Format](./spec-format.md)\n- Used to capture all user intent\n- MUST NOT be modified without explicit user instruction or review\n- Together reflect the expected software decomposition with local spec dependencies mirroring targeted local code files, and with links to external dependencies\n\n## Code\n\n- Follow language and ecosystem requirements specified in AGENTS.md, and APIs and requirements in spec\n- Can be edited or rebuilt by tools or agents\n- Makes good use of dependencies explicitly linked in spec - following dependency APIs if provided and without reimplementing functionality\n- Doesn't use dependencies not explicitly listed in the spec\n\n## Tests\n\n- Follow the test runner requirements specified in AGENTS.md\n- Can be edited or rebuilt by tools or agents\n- Each test implements exactly one test definition from the spec, and only verifies that exact case\n- Assumes code complies exactly with the defined APIs\n- Can be tagged to indicate prioritization: draft (default), locked, impl\n",content$3='\n# Spec Format\n\nSpecs are markdown files with some annotations for parsing. Typically one spec is written for each module.\n\nThey can contain the following sections, empty sections can be omitted:\n\n- Name.\n - Short overview to explain overall purpose.\n- Target.\n - Relative link to the code file this spec targets.\n- Capabilities.\n - Headings for each capability with an optional description.\n - List of test definitions for each capability, with relative links to the test files where they will be implemented.\n- API.\n - Description of the module\'s API that code and tests will be written to conform to.\n- Dependencies.\n - List of dependencies the spec has on other modules and external libraries.\n\nA further explanation of each is provided below.\n\n## Target\n\nShould contain a relative link to the code file that will contain the code this spec targets. This can be one of two flavors:\n\n- [@generate](./relative/path/to/code/file) or\n- [@describe](./relative/path/to/code/file)\n\n@generate is used where the spec is the primary artifact and the linked code will be generated (and regenerated) from the spec. This is the default.\n@describe is used to provide a wrapper to an existing code file, where the code is the primary artifact. This is provided to allow the spec to act as a reference material. The spec will be updated to match code changes.\n\nA spec may contain multiple links if multiple code files are generated from or described by the spec, but it is best practice to have one spec for one code file.\n\n## Capabilities\n\nList of capabilities of the module.\n\nEach capability:\n\n- Should be precise and concise.\n- Should explicitly describe the _intent_ of the capability, rather than describing the approach.\n- Can optionally have a short description under the title to explain the capability in more detail.\n\nEach capability should be followed by a list of requirements.\n\nEach requirement:\n\n- Should be concise, precise and opinionated on specific behaviors.\n- Can cover internal logic or external behavior.\n- Requirements can be converted into test cases by adding a corresponding [@test](./relative/path/to/test/file) annotation. Test cases must have clearly defined inputs and outputs, as well as setup/mocking notes if needed.\n\nExample:\n\n```markdown\nReverses any string. Preserves capitalization and whitespaces during reversal.\n\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file)\n- "Hello, world!" becomes "!dlrow ,olleH" [@test](./relative/path/to/test/file_impl) { .impl }\n```\n\n## API\n\n- Describe the external interface for the module, including function signatures and parameters with types.\n- Must be wrapped in code block with a language identifier, with an { .api } tag on the block.\n- Should be an appropriate format for the language, and should be consistent with any project configuration provided.\n\n## Dependencies\n\nList of dependencies on other specs, files or external libraries that the module is expected to have. No other dependencies should be assumed, unless explicitly specified in the project configuration or in a user goal. Links can either be to the spec for the module if available, or directly to the code itself if the spec is not available.\n\n- Each lists what is expected from the dependency and has a link to the dependency.\n- New dependencies should only be added when explicitly requested by the user.\n\n- The whole section can be skipped if there are no requirements.\n- Each requirement should have a @use link.\n- For local dependencies, the link will be a relative path, for example [@use](./relative/path/to/dependency-spec)\n- For external dependencies a package name will be used, for example [@use](package-name)\n- For code dependencies, the link will be a relative path, for example [@use](./relative/path/to/code-file).\n\nExample dependencies:\n\n```markdown\n# Dependencies\n\n## Code Dependency Example\n\nDescription of the requirements for the module.\n[@use](./relative/path/to/code-file)\n\n## Spec Dependency Example\n\nDescription of the requirements for the module.\n[@use](./relative/path/to/dependency-spec)\n\n## External Dependency Example\n\nDescription of the requirements for the module.\n[@use](package-name)\n```\n\n## Content tags\n\nSections of the spec can be annotated with tags to explain the prioritization and level of editing that is appropriate. They are most often used for annotating specific tests.\n\nRules for applying tags:\n- By default, do not add tags.\n- Tags applied to a section will apply to all tests in the section.\n- Tests must not have more than one kind. e.g: you should not have a test marked as `impl` and `locked`, or a section marked with both `impl` and a test marked with `locked`.\n- Tests files must not mix test kinds. e.g: you should not have untagged and `locked` tests in the same test file.\n- Locked content must never be edited unless instructed to do so by the user.\n- Content must never be tagged as locked unless explicitly requested by the user.\n\n### Untagged (default)\n\nUntagged content is the standard and is considered draft.\n\nUntagged test cases \n- **Purpose**: Regular test cases that can be modified during development as necessary.\n- **Annotation**: No special class required (default behavior)\n- **Priority**: Medium priority, they can be changed during the development flow as the spec is refined\n\nExample:\n```markdown\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file)\n```\n\n\n### Locked { .locked }\n\nLocked tags capture core functional requirements that should remain stable over time. They represent critical test cases that define the essential behavior of the module that have been confirmed by the user.\n\n- **Purpose**: Capture core functional requirements that should remain stable over time\n- **Annotation**: `{ .locked }` class on individual tests or section headers\n- **Priority**: High priority, they are applied deliberately by the user after reviews have been completed.\n\nExamples:\n```markdown\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file) { .locked }\n\n### Core functionality { .locked }\n- "test1" becomes "1tset" [@test](./relative/path/to/test/file1)\n- "test2" becomes "2tset" [@test](./relative/path/to/test/file2)\n```\n\n### Implementation { .impl }\n\nImplementation tags are used to mark incidental implementation by-products rather than user-specified capabilities. They have lower priority and can be changed more freely.\n\n- **Purpose**: Cover implementation details that were not explicitly specified by the user.\n- **Annotation**: `{ .impl }` class on individual tests or section headers\n- **Priority**: Lower priority, they should be more freely changed if user requirements change.\n\nExamples:\n```markdown\n- "Hello" becomes "olleH" [@test](./relative/path/to/test/file) { .impl }\n\n### Implementation details { .impl }\n- Edge case behavior [@test](./relative/path/to/test/file1)\n- Performance characteristics [@test](./relative/path/to/test/file2)\n```\n\n\n## Example spec (with placeholders for the api details)\n\n````markdown\n# String Reverser\n\nString reverser. Switches the order of characters in a string.\n\n## Target\n\n[@generate](./relative/path/to/code/file)\n\n## Capabilities\n\n### Reverses a string.\n\n- "hello" becomes "olleh" [@test](./relative/path/to/test/file1)\n- "iPhone 5 Samsung" becomes "gnusmaS 5 enohPi" [@test](./relative/path/to/test/file2)\n\n### Reverses within a delimiter.\n\nDelimiter is optional, but if provided, reversing only happens between each delimited block, with block order preserved.\n\n- ("hello friend", " ") becomes "olleh dneirf" [@test](./relative/path/to/test/file4)\n\n### Efficient implementation\n\n- Uses a single pass buffer approach.\n- Doesn\'t modify the original string.\n\n\n## API\n\n```{{LANGUAGE}} { .api }\n\n{{API_CODE}}\n\n```\n\n````\n\n\n',content$2='# Plan Files\n\n**CRITICAL: Create a plan file EVERY TIME you make a plan:**\n\n1. Create a new plan file in the `plans/` directory at the root of the project.\n2. Plan filename format: `YYYY-MM-DD_HH-mm-ss_descriptive-name.plan.md`\n - Example: `2025-08-25_14-37-12_user-authentication.plan.md`\n3. Keep the plan file in sync with your own native task tracking tool.\n4. Update the plan file IMMEDIATELY after completing EACH task. Do NOT batch updates.\n\n## Plan File Structure\n\n### Format\nA plan file is a markdown document (`.plan.md`) that records tasks to achieve a goal, and acts as an audit trail of the plan.\n\n### Components\n1. **Header**: Overall goal and any relevant background context\n2. **Task List**: Markdown checkboxes for each task\n - `- [ ]` for pending tasks\n - `- [x]` for completed tasks\n3. **User Tasks**: Mark with `{ @user }` directive for user-completed tasks\n4. **Task Outputs**: Document results as blockquotes after each task\n\n## Rules for Executing Plans with Plan Files\n\n### 1. Task Documentation\nAfter completing each task, document comprehensively:\n\n- **Update status**: Change checkbox from `[ ]` to `[x]`\n- **Add output**: Create detailed blockquote on new line after task\n- **Document tool calls**: For EVERY tool call (MCP, Bash, Edit, etc.), include:\n - Tool name\n - COMPLETE, VERBATIM parameters (do not summarize), EXCEPTION: do summarize parameters containing file contents\n - Use markdown code blocks for multi-line string parameters (e.g. prompts)\n - Summary of tool output\n- **Include every step in the task**: Document every tool call needed to complete the task\n- **Use separators**: Add `---` and a newline between multiple tool calls in same task\n- **Include full journey**: Document the complete process, including diagnostics and debugging:\n - ALL problems encountered with specific details\n - Each fix attempt and rationale\n - Every diagnostic tool used (exact tool name, summary of parameters and output)\n - Summary of outcome, including initial state (e.g., "7 tests failed out of 12") and final state (e.g., "All 11 tests passing")\n- **Always link to project files**: Include markdown links to any created/read/update/deleted project files:\n - link text: file path relative to the project root\n - link href: file path relative to the plan file\n\n### 2. Plan Updates\n- Modify the plan and plan file as needed when requirements change\n- Add new tasks or remove irrelevant ones\n- Document reasons for significant changes\n\n### 3. User Task Handling\nFor tasks marked with `{ @user }`:\n\n- **Stop immediately**: Present task to user exactly as written\n- **Wait for response**: Act on any instructions in user responses\n- **Don\'t assume**: Only complete user tasks when explicitly told the task is done\n- **Document accurately**:\n - Record only what actually happened\n - NEVER add details about what the user did unless they explicitly provide those details\n\n## Best Practices\n1. Tasks should be:\n - **Specific**: Clear, actionable completion criteria\n - **Atomic**: One logical unit of work per task\n - **Logically Ordered**: Arrange in execution sequence\n - **Well Sized**: Break down complex goals into incremental atomic tasks\n\n2. Add `{ @user }` tasks strategically to:\n - Delegate tasks requiring user action\n - Get feedback at critical decision points\n\n## Example\n\n````markdown\n# Plan: Implement User Authentication\n\nAdd secure user authentication with email/password login.\n\n## Tasks\n\n- [x] Create user model spec with email, password hash, and timestamps\n > **MCP** `tessl - create`\n > - spec: specs/models/user.spec.md\n > - prompt:\n > ```\n > Create a User model with the following fields:\n > - id: string (UUID)\n > - email: string (unique, required)\n > - passwordHash: string (required)\n > - createdAt: Date\n > - updatedAt: Date\n >\n > Include methods for:\n > - Password hashing and verification using bcrypt\n > - Email validation\n > - Safe JSON serialization (excludes passwordHash)\n > ```\n >\n > Created [specs/models/user.spec.md](../specs/models/user.spec.md)\n > Model spec created successfully with all required fields and methods.\n\n- [x] Build user model from spec\n > **MCP** `tessl - build`\n > - spec: ["specs/models/user.spec.md"]\n >\n > Generated:\n > - [src/models/user.ts](../src/models/user.ts)\n >\n > Build completed successfully, no errors.\n > ---\n >\n > **Bash** `npm run build`\n > Build failed with TypeScript errors: missing import extensions\n > ---\n >\n > **Edit** `src/models/user.ts`\n > - old_string: import { SomeType } from \'./types\'\n > - new_string: import { SomeType } from \'./types.js\'\n >\n > Updated [src/models/user.ts](../src/models/user.ts).\n > Fixed import to include .js extension for ESM compatibility.\n > ---\n >\n > **MCP** `tessl - document`\n > - spec: specs/models/user.spec.md\n > - includeImplDetails: true\n >\n > Synced [code](../src/models/user.ts) behavior to [spec](../specs/models/user.spec.md)\n\n- [ ] Add database migration for users table\n- [ ] Create authentication service spec\n- [ ] Implement login endpoint\n- [ ] Add session management\n- [ ] Test authentication flow { @user }\n````\n',content$1="\n# Tessl\n\nTessl is a spec driven development framework and toolkit.\n\nAlways use [Spec Driven Development](./docs/spec-driven-development.md) when executing tasks.\n",content="\n# Using the Knowledge Index\n\nRequired dependencies for this projects are documented in the Knowledge Index: `./KNOWLEDGE.md`\n\nBefore starting any work, review the contents of `./KNOWLEDGE.md` to discover the expectations on what dependencies (and which versions) and processes you must follow.\n\nBecause the index can link to a large amount of content, use this workflow to read relevant content:\n\n1. Review `./KNOWLEDGE.md` and check if there any relevant files.\n2. If so, spawn a research subagent with information about your task and a pointer to the files, and ask it to return a relevant summary of context for you to use (but not to do the task). This will prevent you from getting overwhelmed by too much information.\n3. Use the information in your task!\n\nClarify by interviewing the user if the content is not what you expect:\n\n- There's documentation for a dependency you could use, but it isn't the obvious choice. Check if you are expected to use it for the task you are doing.\n- If you are not sure whether to use the version of the dependency from the docs, for example, if you discover that there's a more up to date version of the package.\n- If there's documentation that appears to be missing that would help.\n\nREPEAT this workflow for every new task. The Knowledge Index is updated frequently, so make sure to review it for changes.\n\n# Using the Tessl Spec Registry\n\nDocumentation can be added to the Knowledge Index using the Tessl `registry` tools:\n\n- Search Tessl's Spec Registry for dependency documentation using `search`\n- Install relevant docs into the Knowledge Index using `install`\n\nConsult the Spec Registry when deciding which dependencies to install into a project. Likewise, install the documentation for a given dependency after installing it.\n",FRAMEWORK_FILES={
3452
- "agents.md":content$6,"bootstrap.md":content$5,"plan-files.md":content$2,"tessl-system-prompt.md":content$1,"docs/spec-driven-development.md":content$4,"docs/spec-format.md":content$3},KNOWLEDGE_ONLY_FILES={"usage-specs.md":content};function installFullFrameworkFiles(e){return installFrameworkFiles(e,FRAMEWORK_FILES)}function installKnowledgeFrameworkFiles(e){return installFrameworkFiles(e,KNOWLEDGE_ONLY_FILES)}function installFrameworkFiles(e,t){const r=path__default.resolve(e,DEFAULT_TESSL_DIRS.frameworkDirectory);fs$4.existsSync(r)&&fs$4.rmSync(r,{recursive:!0});const n=[];for(const[i,s]of Object.entries(t)){const t=path__default.join(r,i);fs$4.existsSync(path__default.dirname(t))||fs$4.mkdirSync(path__default.dirname(t),{recursive:!0}),fs$4.writeFileSync(t,s.trim());const o=path__default.relative(e,t);n.push(o)}return n}const DEFAULT_KNOWLEDGE_MD_CONTENT="# Knowledge Index\n\n";function ensureKnowledgeMd(e){const t=path__default.resolve(e,KNOWLEDGE_MD_FILENAME$1)
3453
- ;if(!fs$4.existsSync(t)){fs$4.writeFileSync(t,DEFAULT_KNOWLEDGE_MD_CONTENT);return[path__default.relative(e,t)]}return[]}class Initializer{#wi;constructor(e){this.#wi=e}addTesslFiles(){const e=[],t=process.cwd(),r=ensureTesslJsonSync(t,{name:path__default.basename(t)});r&&e.push(r);const n=path__default.resolve(t,CONFIG_DIR_NAME);fs__default.mkdirSync(n,{recursive:!0});const i=path__default.resolve(n,".gitignore"),s=path__default.relative(n,DEFAULT_TESSL_DIRS.tmpDirectory);fs__default.writeFileSync(i,`${s}/${EOL}${USAGE_SPEC_DIR_NAME}/${EOL}`),e.push(`${CONFIG_DIR_NAME}/.gitignore`),removeHooks(t,KNOWLEDGE_ONLY_HOOKS);const o=installFullFrameworkFiles(t);e.push(...o);const a=ensureAgentsMd(t);e.push(...a);const c=ensureAgentsMdHooks(t);e.push(...c);const u=ensureKnowledgeMd(t);return e.push(...u),[...new Set(e)]}initializeProject(e,t){const r=Date.now();let n=0,i=!0;try{const e=this.addTesslFiles();return n=Date.now()-r,{filesCreated:e,durationMs:n}}catch(e){throw n=Date.now()-r,i=!1,e
3454
- }finally{this.#wi.init({success:i,isReinitializing:e,type:"full",...t?{previousType:t}:{}})}}}class KnowledgeInitializer{#wi;constructor(e){this.#wi=e}addTesslFiles(){const e=[],t=process.cwd(),r=ensureTesslJsonSync(t,{name:path__default.basename(t)});r&&e.push(r);const n=path__default.resolve(t,CONFIG_DIR_NAME);fs__default.mkdirSync(n,{recursive:!0});const i=path__default.resolve(n,".gitignore"),s=path__default.relative(n,DEFAULT_TESSL_DIRS.tmpDirectory);fs__default.writeFileSync(i,`${s}/${EOL}${USAGE_SPEC_DIR_NAME}/${EOL}`),e.push(`${CONFIG_DIR_NAME}/.gitignore`),removeHooks(t,DEFAULT_HOOKS);const o=installKnowledgeFrameworkFiles(t);e.push(...o);const a=ensureAgentsMd(t);e.push(...a);const c=ensureAgentsMdHooks(t,KNOWLEDGE_ONLY_HOOKS);e.push(...c);const u=ensureKnowledgeMd(t);return e.push(...u),[...new Set(e)]}initializeProject(e,t){const r=Date.now();let n=0,i=!0;try{const e=this.addTesslFiles();return n=Date.now()-r,{filesCreated:e,durationMs:n}}catch(e){throw n=Date.now()-r,i=!1,
3455
- e}finally{this.#wi.init({success:i,isReinitializing:e,type:"spec-registry",...t?{previousType:t}:{}})}}}function formatDuration(e){if(e<1e3)return`${e} ms`;const t=e/1e3;if(t<60)return`${t.toFixed(1)} sec`;const r=Math.floor(t/60),n=Math.round(t%60);return`${r} min${n>0?` ${n} sec`:""}`}function FilesCreated({base:e,filepaths:t}){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:t.map(t=>jsxRuntimeExports.jsxs(Text,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"+"})," ",e&&jsxRuntimeExports.jsxs(Text,{dimColor:!0,children:["/"!==e?e:"","/"]}),t]},t))})}function Indicator({isSelected:e=!1}){return React.createElement(Box,{marginRight:1},e?React.createElement(Text,{color:"blue"},figures.pointer):React.createElement(Text,null," "))}function Item({isSelected:e=!1,label:t}){return reactExports.createElement(Text,{color:e?"blue":void 0},t)}function toRotated(e,t){if(!Array.isArray(e))throw new TypeError(`Expected an array, got \`${typeof e}\`.`)
3456
- ;if(!Number.isSafeInteger(t))throw new TypeError(`The \`steps\` parameter must be an integer, got ${t}.`);const{length:r}=e;if(0===r)return[...e];const n=(t%r+r)%r;return 0===n?[...e]:[...e.slice(-n),...e.slice(0,-n)]}function SelectInput({items:e=[],isFocused:t=!0,initialIndex:r=0,indicatorComponent:n=Indicator,itemComponent:i=Item,limit:s,onSelect:o,onHighlight:a}){const c="number"==typeof s&&e.length>s,u=c?Math.min(s,e.length):e.length,l=u-1,[d,p]=reactExports.useState(r>l?l-r:0),[h,A]=reactExports.useState(r?r>l?l:r:0),f=reactExports.useRef(e);reactExports.useEffect(()=>{isDeepStrictEqual(f.current.map(e=>e.value),e.map(e=>e.value))||(p(0),A(0)),f.current=e},[e]),useInput(reactExports.useCallback((t,r)=>{if("k"===t||r.upArrow){const t=(c?u:e.length)-1,r=0===h,n=r?d+1:d,i=r?c?h:t:h-1;p(n),A(i);const s=c?toRotated(e,n).slice(0,u):e;"function"==typeof a&&a(s[i])}if("j"===t||r.downArrow){const t=h===(c?u:e.length)-1,r=t?d-1:d,n=t?c?h:0:h+1;p(r),A(n)
3457
- ;const i=c?toRotated(e,r).slice(0,u):e;"function"==typeof a&&a(i[n])}if(/^[1-9]$/.test(t)){const r=Number.parseInt(t,10)-1,n=c?toRotated(e,d).slice(0,u):e;if(r>=0&&r<n.length){const e=n[r];e&&o?.(e)}}if(r.return){const t=c?toRotated(e,d).slice(0,u):e;"function"==typeof o&&o(t[h])}},[c,u,d,h,e,o,a]),{isActive:t});const g=c?toRotated(e,d).slice(0,u):e;return React.createElement(Box,{flexDirection:"column"},g.map((e,t)=>{const r=t===h;return React.createElement(Box,{key:e.key??e.value},React.createElement(n,{isSelected:r}),React.createElement(i,{...e,isSelected:r}))}))}function _optionalChain$p(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function SelectItem({items:e,selectColor:t,onSelect:r}){return jsxRuntimeExports.jsx(SelectInput,{items:e,onSelect:r,
3458
- indicatorComponent:({isSelected:e})=>jsxRuntimeExports.jsx(Box,{marginRight:1,children:e?jsxRuntimeExports.jsx(Text,{color:t,children:figures.pointer}):jsxRuntimeExports.jsx(Text,{children:" "})}),itemComponent:({label:r,isSelected:n})=>{const i=_optionalChain$p([e,"access",e=>e.find,"call",e=>e(e=>e.label===r),"optionalAccess",e=>e.description]);return jsxRuntimeExports.jsxs(Box,{gap:1,children:[jsxRuntimeExports.jsx(Text,{underline:n,color:n?t:void 0,children:r}),n&&!!i&&jsxRuntimeExports.jsxs(Text,{dimColor:!0,children:["(",i,")"]})]})}})}function SpiffyBox({children:e,marginTop:t=1,borderColor:r="white",borderDimColor:n=!0}){return jsxRuntimeExports.jsx(Box,{flexDirection:"column",gap:1,borderStyle:"round",borderColor:r,borderDimColor:n,paddingX:1,paddingY:1,width:84,marginTop:t,children:e})}function ReinitPrompt({onSubmit:e}){const{exit:t}=useApp();return jsxRuntimeExports.jsxs(SpiffyBox,{marginTop:0,borderColor:"yellow",children:[jsxRuntimeExports.jsxs(Box,{paddingLeft:2,
3459
- flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Tessl is already initialized in this directory. Reinitialize?"}),jsxRuntimeExports.jsx(Text,{children:"This will overwrite your existing config, update Spec Authoring files, and add Tessl references to AGENTS.md."})]}),jsxRuntimeExports.jsx(SelectItem,{items:[{label:"Reinitialize",value:!0},{label:"Cancel",value:!1}],onSelect:r=>{e(r.value),t()},selectColor:"yellow"})]})}function UpgradeToFullFrameworkPrompt({onSubmit:e}){const{exit:t}=useApp();return jsxRuntimeExports.jsxs(SpiffyBox,{marginTop:0,borderColor:"blue",children:[jsxRuntimeExports.jsxs(Box,{paddingLeft:2,flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Continuing will upgrade this project to add Tessl Spec Authoring context"}),jsxRuntimeExports.jsx(Text,{children:"Now that you are logged into Tessl, you have access to Spec Authoring commands, in addition to the Spec Registry."
3460
- }),jsxRuntimeExports.jsx(Text,{children:"Continuing will replace your Tessl framework files and Tessl-managed sections of your AGENTS.md file. Your own content will be preserved."})]}),jsxRuntimeExports.jsx(SelectItem,{items:[{label:"Continue",value:!0},{label:"Cancel",value:!1}],onSelect:r=>{e(r.value),t()},selectColor:"blue"})]})}function DowngradeToKnowledgeOnlyFrameworkPrompt({onSubmit:e}){const{exit:t}=useApp();return jsxRuntimeExports.jsxs(SpiffyBox,{marginTop:0,borderColor:"red",children:[jsxRuntimeExports.jsxs(Box,{paddingLeft:2,flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Continuing will downgrade this project by removing Tessl Spec Authoring context"}),jsxRuntimeExports.jsx(Text,{children:"Because you are not currently logged into Tessl, if you continue your project will remain able to use the Spec Registry, but Spec Authoring commands may not behave as expected upon logging back in."}),jsxRuntimeExports.jsxs(Text,{
3461
- children:["To refresh the Spec Authoring context, first re-authenticate with"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl login"})," before running"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl init"}),"."]}),jsxRuntimeExports.jsx(Text,{children:"Continuing now will replace your Tessl framework files and Tessl-managed sections of your AGENTS.md file. Your own content will be preserved."})]}),jsxRuntimeExports.jsx(SelectItem,{items:[{label:"Continue",value:!0},{label:"Cancel",value:!1}],onSelect:r=>{e(r.value),t()},selectColor:"red"})]})}function BigTessl(){return jsxRuntimeExports.jsx(Text,{children:"\n ______ ______ ______ ______ __\n /\\__ _\\/\\ ___\\ /\\ ___\\ /\\ ___\\ /\\ \\\n \\/_/\\ \\/\\ \\ __\\ \\ \\___ \\\\ \\___ \\\\ \\ \\____\n \\ \\_\\ \\ \\_____\\\\/\\_____\\\\/\\_____\\\\ \\_____\\\n \\/_/ \\/_____/ \\/_____/ \\/_____/ \\/_____/\n"})}const initCommand=new Command$1({name:"init",
3462
- summary:"Initialize Tessl in the current directory. Sets up Tessl context and provides a default AI agent integration via AGENTS.md.",requiresConfig:!1,requiresLogin:!1,flags:{force:{type:Boolean,short:"f",description:"Automatically accept the reinitialization prompt"}},handler:async({monitoring:{analytics:e},args:t,isInteractive:r,globalConfigDir:n})=>{const{force:i}=t,s=process.cwd();return await isAuthed({basePath:n})?fullInit(s,i,r,e):knowledgeOnlyInit(s,i,r,e)}});function getExistingFrameworkType(e){return hasHooks(e,DEFAULT_HOOKS)?"full":hasHooks(e,KNOWLEDGE_ONLY_HOOKS)?"spec-registry":void 0}async function fullInit(e,t,r,n){const i=await hasTesslJson(e),s=path__default.join(DEFAULT_TESSL_DIRS.frameworkDirectory,"usage-specs.md"),o=fs$4.existsSync(s);if(i&&!t){let e=!1;if(!r)throw new ExpectedError("Tessl is already initialized in this directory. Re-run with --force if you want to initialize anyway in non-interactive mode.");if(o){
3463
- const{clear:t,waitUntilExit:r}=render(jsxRuntimeExports.jsx(UpgradeToFullFrameworkPrompt,{onSubmit:r=>{e=r,t()}}));await r()}else{const{clear:t,waitUntilExit:r}=render(jsxRuntimeExports.jsx(ReinitPrompt,{onSubmit:r=>{e=r,t()}}));await r()}if(!e)throw new ExpectedError("Initialization cancelled.")}const a=new Initializer(n);return await render(jsxRuntimeExports.jsx(Init,{initializer:a,isReinitializing:i,existingFramework:getExistingFrameworkType(e),nextSteps:jsxRuntimeExports.jsx(NextSteps,{})})).waitUntilExit(),SUCCESS}async function knowledgeOnlyInit(e,t,r,n){const i=await hasTesslJson(e),s=path__default.join(DEFAULT_TESSL_DIRS.frameworkDirectory,"agents.md"),o=fs$4.existsSync(s);if(i&&!t){let e=!1;if(!r)throw new ExpectedError("Tessl is already initialized in this directory. Re-run with --force if you want to initialize anyway in non-interactive mode.");if(o){const{clear:t,waitUntilExit:r}=render(jsxRuntimeExports.jsx(DowngradeToKnowledgeOnlyFrameworkPrompt,{onSubmit:r=>{e=r,t()}}))
3464
- ;await r()}else{const{clear:t,waitUntilExit:r}=render(jsxRuntimeExports.jsx(ReinitPrompt,{onSubmit:r=>{e=r,t()}}));await r()}if(!e)throw new ExpectedError("Initialization cancelled.")}const a=new KnowledgeInitializer(n);return await render(jsxRuntimeExports.jsx(Init,{initializer:a,isReinitializing:i,existingFramework:getExistingFrameworkType(e),nextSteps:jsxRuntimeExports.jsx(KnowledgeOnlyNextSteps,{})})).waitUntilExit(),SUCCESS}function Init({initializer:e,isReinitializing:t,existingFramework:r,nextSteps:n}){const{exit:i}=useApp(),[s,o]=reactExports.useState([]),[a,c]=reactExports.useState();return reactExports.useEffect(()=>{try{const{filesCreated:n,durationMs:s}=e.initializeProject(t,r);o(n),c(s),setTimeout(i,100)}catch(e){throw new Error("Failed to initialize a new project.")}},[i,e,o,t,r]),jsxRuntimeExports.jsxs(Box,{flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(BigTessl,{}),jsxRuntimeExports.jsxs(Box,{flexDirection:"column",children:[jsxRuntimeExports.jsx(Text,{
3465
- children:"Initializing Tessl..."}),s.length>0&&jsxRuntimeExports.jsx(FilesCreated,{base:process.cwd(),filepaths:s})]}),void 0!==a&&jsxRuntimeExports.jsxs(Box,{flexDirection:"row",gap:1,children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"Project initialized"}),jsxRuntimeExports.jsx(Text,{color:"green",bold:!0,children:figures.tick}),jsxRuntimeExports.jsx(Text,{dimColor:!0,children:formatDuration(a)})]}),n]})}function NextSteps(){return jsxRuntimeExports.jsxs(Box,{flexDirection:"column",marginBottom:2,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Next steps"}),jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"Wondering what to do next? Here's some tips:"}),jsxRuntimeExports.jsxs(Text,{children:["• Auto-configure your preferred coding agent to use Tessl with"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl setup agent"})]}),jsxRuntimeExports.jsxs(Text,{children:["• Review the quickstart guide with ",jsxRuntimeExports.jsx(CommandText,{children:"tessl help"})]
3466
- }),jsxRuntimeExports.jsxs(Text,{children:["• Create a spec with ",jsxRuntimeExports.jsx(CommandText,{children:"tessl create"})]})]})}function KnowledgeOnlyNextSteps(){return jsxRuntimeExports.jsxs(Box,{flexDirection:"column",marginBottom:2,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Next steps"}),jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"Wondering what to do next? Here's some tips:"}),jsxRuntimeExports.jsxs(Text,{children:["• Auto-configure your preferred coding agent to use Tessl with"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl setup agent"})]}),jsxRuntimeExports.jsxs(Text,{children:["• Review the quickstart guide with ",jsxRuntimeExports.jsx(CommandText,{children:"tessl help"})]}),jsxRuntimeExports.jsxs(Text,{children:["• Use ",jsxRuntimeExports.jsx(CommandText,{children:"tessl registry search"})," to find usage specs for your project, and"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl registry install"})," to add them"]})]})}
3467
- var tail={},hasRequiredTail;function requireTail(){if(hasRequiredTail)return tail;hasRequiredTail=1;let e=require$$0$g,t=fs$4,r=path__default;class n{info(){}error(){}}class i extends e.EventEmitter{constructor(i,s={}){super(),this.filename=i,this.absPath=r.dirname(this.filename),this.separator=void 0!==s.separator?s.separator:/[\r]{0,1}\n/,this.fsWatchOptions=s.fsWatchOptions||{},this.follow=null==s.follow||s.follow,this.logger=s.logger||new n,this.useWatchFile=s.useWatchFile||!1,this.flushAtEOF=s.flushAtEOF||!1,this.encoding=s.encoding||"utf-8";const o=s.fromBeginning||!1;this.nLines=s.nLines||void 0,this.logger.info("Tail starting..."),this.logger.info(`filename: ${this.filename}`),this.logger.info(`encoding: ${this.encoding}`);try{t.accessSync(this.filename,t.constants.F_OK)}catch(e){if("ENOENT"==e.code)throw e}let a;if(this.buffer="",this.internalDispatcher=new e.EventEmitter,this.queue=[],this.isWatching=!1,this.pos=0,this.internalDispatcher.on("next",()=>{this.readBlock()}),
3468
- this.logger.info(`fromBeginning: ${o}`),a=o||this.nLines<=0?0:void 0!==this.nLines?this.getPositionAtNthLine(this.nLines):this.latestPosition(),void 0===a)throw new Error("Tail can't initialize.");const c=o||null!=this.nLines;try{this.watch(a,c)}catch(e){this.logger.error(`watch for ${this.filename} failed: ${e}`),this.emit("error",`watch for ${this.filename} failed: ${e}`)}}getIndexOfLastLine(e){const t=(e,t)=>{const r=e.match(t);if(null!==r)return r[r.length-1]},r=t(e,this.separator);if(!r)return null;const n=e.lastIndexOf(r);let i;if(e.endsWith(r)){const s=e.substring(0,n),o=t(s,this.separator);if(!o)return null;const a=s.lastIndexOf(o);i=e.substring(a+o.length,n+r.length)}else i=e.substring(n+r.length);return e.lastIndexOf(i)}getPositionAtNthLine(e){const{size:r}=t.statSync(this.filename);if(0===r)return 0;const n=t.openSync(this.filename,"r");let i=r;const s=Math.min(1024,r),o=[];let a="";for(;o.length<e;){if(i-=s,i<0)return 0
3469
- ;const r=Buffer.alloc(s),c=t.readSync(n,r,0,s,i),u=r.subarray(0,c);a=Buffer.from(u).toString(this.encoding)+a;let l=this.getIndexOfLastLine(a);for(;null!==l&&o.length<e;){const e=a.substring(l);o.push(Buffer.byteLength(e)),a=a.substring(0,l),l=this.getIndexOfLastLine(a)}}return t.closeSync(n),r-o.reduce((e,t)=>e+t,0)}latestPosition(){try{return t.statSync(this.filename).size}catch(e){throw this.logger.error(`size check for ${this.filename} failed: ${e}`),this.emit("error",`size check for ${this.filename} failed: ${e}`),e}}readBlock(){if(this.queue.length>=1){const e=this.queue[0];if(e.end>e.start){let r=t.createReadStream(this.filename,{start:e.start,end:e.end-1,encoding:this.encoding});r.on("error",e=>{this.logger.error(`Tail error: ${e}`),this.emit("error",e)}),r.on("end",()=>{this.queue.shift(),this.queue.length>0&&this.internalDispatcher.emit("next"),this.flushAtEOF&&this.buffer.length>0&&(this.emit("line",this.buffer),this.buffer="")}),r.on("data",e=>{
3470
- if(null===this.separator)this.emit("line",e);else{this.buffer+=e;let t=this.buffer.split(this.separator);this.buffer=t.pop();for(const e of t)this.emit("line",e)}})}}}change(){let e=this.latestPosition();e<this.currentCursorPos?this.currentCursorPos=e:e>this.currentCursorPos&&(this.queue.push({start:this.currentCursorPos,end:e}),this.currentCursorPos=e,1==this.queue.length&&this.internalDispatcher.emit("next"))}watch(e,r){this.isWatching||(this.logger.info(`filesystem.watch present? ${null!=t.watch}`),this.logger.info(`useWatchFile: ${this.useWatchFile}`),this.isWatching=!0,this.currentCursorPos=e,r&&this.change(),!this.useWatchFile&&t.watch?(this.logger.info("watch strategy: watch"),this.watcher=t.watch(this.filename,this.fsWatchOptions,(e,t)=>{this.watchEvent(e,t)})):(this.logger.info("watch strategy: watchFile"),t.watchFile(this.filename,this.fsWatchOptions,(e,t)=>{this.watchFileEvent(e,t)})))}rename(e){void 0!==e&&e===this.filename||(this.unwatch(),
3471
- this.follow?(this.filename=r.join(this.absPath,e),this.rewatchId=setTimeout(()=>{try{this.watch(this.currentCursorPos)}catch(e){this.logger.error(`'rename' event for ${this.filename}. File not available anymore.`),this.emit("error",e)}},1e3)):(this.logger.error(`'rename' event for ${this.filename}. File not available anymore.`),this.emit("error",`'rename' event for ${this.filename}. File not available anymore.`)))}watchEvent(e,t){try{"change"===e?this.change():"rename"===e&&this.rename(t)}catch(e){this.logger.error(`watchEvent for ${this.filename} failed: ${e}`),this.emit("error",`watchEvent for ${this.filename} failed: ${e}`)}}watchFileEvent(e,t){e.size>t.size&&(this.currentCursorPos=e.size,this.queue.push({start:t.size,end:e.size}),1==this.queue.length&&this.internalDispatcher.emit("next"))}unwatch(){this.watcher?this.watcher.close():t.unwatchFile(this.filename),this.rewatchId&&(clearTimeout(this.rewatchId),this.rewatchId=void 0),this.isWatching=!1,this.queue=[],
3472
- this.logger&&this.logger.info(`Unwatch ${this.filename}`)}}return tail.Tail=i,tail}var tailExports=requireTail(),lib$4={},assert$2={exports:{}},assertError,hasRequiredAssertError,stringify$1,hasRequiredStringify$1,hasRequiredAssert,reach,hasRequiredReach;function requireAssertError(){return hasRequiredAssertError?assertError:(hasRequiredAssertError=1,assertError=class extends Error{name="AssertError";constructor(e,t){super(e||"Unknown error"),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,t)}})}function requireStringify$1(){return hasRequiredStringify$1||(hasRequiredStringify$1=1,stringify$1=function(...e){try{return JSON.stringify(...e)}catch(e){return"[Cannot display object: "+e.message+"]"}}),stringify$1}function requireAssert(){if(hasRequiredAssert)return assert$2.exports;hasRequiredAssert=1;const e=requireAssertError(),t=requireStringify$1(),r=assert$2.exports=function(n,...i){if(n)return;if(1===i.length&&i[0]instanceof Error)throw i[0]
3473
- ;const s=i.filter(e=>""!==e).map(e=>"string"==typeof e?e:e instanceof Error?e.message:t(e));throw new e(s.join(" "),r)};return assert$2.exports}function requireReach(){if(hasRequiredReach)return reach;hasRequiredReach=1;const e=requireAssert(),t={};return reach=function(r,n,i){if(!1===n||null==n)return r;"string"==typeof(i=i||{})&&(i={separator:i});const s=Array.isArray(n);e(!s||!i.separator,"Separator option is not valid for array-based chain");const o=s?n:n.split(i.separator||".");let a=r;for(let r=0;r<o.length;++r){let s=o[r];const c=i.iterables&&t.iterables(a);if(Array.isArray(a)||"set"===c){const e=Number(s);Number.isInteger(e)&&(s=e<0?a.length+e:e)}if(!a||"function"==typeof a&&!1===i.functions||!c&&void 0===a[s]){e(!i.strict||r+1===o.length,"Missing segment",s,"in reach path ",n),e("object"==typeof a||!0===i.functions||"function"!=typeof a,"Invalid segment",s,"in reach path ",n),a=i.default;break}a=c?"set"===c?[...a][s]:a.get(s):a[s]}return a},t.iterables=function(e){
3474
- return e instanceof Set?"set":e instanceof Map?"map":void 0},reach}var types$1={exports:{}},hasRequiredTypes$1;function requireTypes$1(){return hasRequiredTypes$1||(hasRequiredTypes$1=1,function(e,t){const r={};t=e.exports={array:Array.prototype,buffer:Buffer&&Buffer.prototype,date:Date.prototype,error:Error.prototype,generic:Object.prototype,map:Map.prototype,promise:Promise.prototype,regex:RegExp.prototype,set:Set.prototype,url:URL.prototype,weakMap:WeakMap.prototype,weakSet:WeakSet.prototype},r.typeMap=new Map([["[object Error]",t.error],["[object Map]",t.map],["[object Promise]",t.promise],["[object Set]",t.set],["[object URL]",t.url],["[object WeakMap]",t.weakMap],["[object WeakSet]",t.weakSet]]),t.getInternalProto=function(e){if(Array.isArray(e))return t.array;if(Buffer&&e instanceof Buffer)return t.buffer;if(e instanceof Date)return t.date;if(e instanceof RegExp)return t.regex;if(e instanceof Error)return t.error;const n=Object.prototype.toString.call(e)
3475
- ;return r.typeMap.get(n)||t.generic}}(types$1,types$1.exports)),types$1.exports}var utils$1={},hasRequiredUtils$1,clone,hasRequiredClone,merge$2,hasRequiredMerge$2,applyToDefaults,hasRequiredApplyToDefaults,bench,hasRequiredBench,ignore,hasRequiredIgnore,block,hasRequiredBlock,deepEqual,hasRequiredDeepEqual,escapeRegex$1,hasRequiredEscapeRegex,contain,hasRequiredContain,escapeHeaderAttribute,hasRequiredEscapeHeaderAttribute,escapeHtml,hasRequiredEscapeHtml,escapeJson,hasRequiredEscapeJson,flatten,hasRequiredFlatten,intersect,hasRequiredIntersect,isPromise$1,hasRequiredIsPromise$1,once,hasRequiredOnce,reachTemplate,hasRequiredReachTemplate,wait,hasRequiredWait,hasRequiredLib$4;function requireUtils$1(){return hasRequiredUtils$1||(hasRequiredUtils$1=1,utils$1.keys=function(e,t={}){return!1!==t.symbols?Reflect.ownKeys(e):Object.getOwnPropertyNames(e)}),utils$1}function requireClone(){if(hasRequiredClone)return clone;hasRequiredClone=1
3476
- ;const e=requireReach(),t=requireTypes$1(),r=requireUtils$1(),n={needsProtoHack:new Set([t.set,t.map,t.weakSet,t.weakMap]),structuredCloneExists:"function"==typeof structuredClone};return clone=n.clone=function(e,i={},s=null){if("object"!=typeof e||null===e)return e;let o=n.clone,a=s;if(i.shallow){if(!0!==i.shallow)return n.cloneWithShallow(e,i);o=e=>e}else if(a){const t=a.get(e);if(t)return t}else a=new Map;const c=t.getInternalProto(e);switch(c){case t.buffer:return Buffer?.from(e);case t.date:return new Date(e.getTime());case t.regex:case t.url:return new c.constructor(e)}const u=n.base(e,c,i);if(u===e)return e;if(a&&a.set(e,u),c===t.set)for(const t of e)u.add(o(t,i,a));else if(c===t.map)for(const[t,r]of e)u.set(t,o(r,i,a));const l=r.keys(e,i);for(const r of l){if("__proto__"===r)continue;if(c===t.array&&"length"===r){u.length=e.length;continue}if(n.structuredCloneExists&&c===t.error&&"stack"===r)continue;const s=Object.getOwnPropertyDescriptor(e,r)
3477
- ;s?s.get||s.set?Object.defineProperty(u,r,s):s.enumerable?u[r]=o(e[r],i,a):Object.defineProperty(u,r,{enumerable:!1,writable:!0,configurable:!0,value:o(e[r],i,a)}):Object.defineProperty(u,r,{enumerable:!0,writable:!0,configurable:!0,value:o(e[r],i,a)})}return u},n.cloneWithShallow=function(t,r){const i=r.shallow;(r=Object.assign({},r)).shallow=!1;const s=new Map;for(const r of i){const n=e(t,r);"object"!=typeof n&&"function"!=typeof n||s.set(n,n)}return n.clone(t,r,s)},n.base=function(e,r,i){if(!1===i.prototype)return n.needsProtoHack.has(r)?new r.constructor:r===t.array?[]:{};const s=Object.getPrototypeOf(e);if(s&&s.isImmutable)return e;if(r===t.array){const e=[];return s!==r&&Object.setPrototypeOf(e,s),e}if(r===t.error&&n.structuredCloneExists&&(s===r||Error.isPrototypeOf(s.constructor))){const t=structuredClone(e);return Object.getPrototypeOf(t)!==s&&Object.setPrototypeOf(t,s),t}if(n.needsProtoHack.has(r)){const e=new s.constructor;return s!==r&&Object.setPrototypeOf(e,s),e}
3478
- return Object.create(s)},clone}function requireMerge$2(){if(hasRequiredMerge$2)return merge$2;hasRequiredMerge$2=1;const e=requireAssert(),t=requireClone(),r=requireUtils$1(),n={};return merge$2=n.merge=function(i,s,o){if(e(i&&"object"==typeof i,"Invalid target value: must be an object"),e(null==s||"object"==typeof s,"Invalid source value: must be null, undefined, or an object"),!s)return i;if(o=Object.assign({nullOverride:!0,mergeArrays:!0},o),Array.isArray(s)){e(Array.isArray(i),"Cannot merge array onto an object"),o.mergeArrays||(i.length=0);for(let e=0;e<s.length;++e)i.push(t(s[e],{symbols:o.symbols}));return i}const a=r.keys(s,o);for(let e=0;e<a.length;++e){const r=a[e];if("__proto__"===r||!Object.prototype.propertyIsEnumerable.call(s,r))continue;const c=s[r];if(c&&"object"==typeof c){if(i[r]===c)continue;!i[r]||"object"!=typeof i[r]||Array.isArray(i[r])!==Array.isArray(c)||c instanceof Date||Buffer&&Buffer.isBuffer(c)||c instanceof RegExp?i[r]=t(c,{symbols:o.symbols
3479
- }):n.merge(i[r],c,o)}else(null!=c||o.nullOverride)&&(i[r]=c)}return i},merge$2}function requireApplyToDefaults(){if(hasRequiredApplyToDefaults)return applyToDefaults;hasRequiredApplyToDefaults=1;const e=requireAssert(),t=requireClone(),r=requireMerge$2(),n=requireReach(),i={};return applyToDefaults=function(n,s,o={}){if(e(n&&"object"==typeof n,"Invalid defaults value: must be an object"),e(!s||!0===s||"object"==typeof s,"Invalid source value: must be true, falsy or an object"),e("object"==typeof o,"Invalid options: must be an object"),!s)return null;if(o.shallow)return i.applyToDefaultsWithShallow(n,s,o);const a=t(n);if(!0===s)return a;const c=void 0!==o.nullOverride&&o.nullOverride;return r(a,s,{nullOverride:c,mergeArrays:!1})},i.applyToDefaultsWithShallow=function(s,o,a){const c=a.shallow;e(Array.isArray(c),"Invalid keys");const u=new Map,l=!0===o?null:new Set;for(let e of c){e=Array.isArray(e)?e:e.split(".");const t=n(s,e);t&&"object"==typeof t?u.set(t,l&&n(o,e)||t):l&&l.add(e)}
3480
- const d=t(s,{},u);if(!l)return d;for(const e of l)i.reachCopy(d,o,e);const p=void 0!==a.nullOverride&&a.nullOverride;return r(d,o,{nullOverride:p,mergeArrays:!1})},i.reachCopy=function(e,t,r){for(const e of r){if(!(e in t))return;const r=t[e];if("object"!=typeof r||null===r)return;t=r}const n=t;let i=e;for(let e=0;e<r.length-1;++e){const t=r[e];"object"!=typeof i[t]&&(i[t]={}),i=i[t]}i[r[r.length-1]]=n},applyToDefaults}function requireBench(){if(hasRequiredBench)return bench;hasRequiredBench=1;const e={};return bench=e.Bench=class{constructor(){this.ts=0,this.reset()}reset(){this.ts=e.Bench.now()}elapsed(){return e.Bench.now()-this.ts}static now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}}}function requireIgnore(){return hasRequiredIgnore?ignore:(hasRequiredIgnore=1,ignore=function(){})}function requireBlock(){if(hasRequiredBlock)return block;hasRequiredBlock=1;const e=requireIgnore();return block=function(){return new Promise(e)}}function requireDeepEqual(){
3481
- if(hasRequiredDeepEqual)return deepEqual;hasRequiredDeepEqual=1;const e=requireTypes$1(),t={mismatched:null};return deepEqual=function(e,r,n){return n=Object.assign({prototype:!0},n),!!t.isDeepEqual(e,r,n,[])},t.isDeepEqual=function(r,n,i,s){if(r===n)return 0!==r||1/r==1/n;const o=typeof r;if(o!==typeof n)return!1;if(null===r||null===n)return!1;if("function"===o){if(!i.deepFunction||r.toString()!==n.toString())return!1}else if("object"!==o)return r!=r&&n!=n;const a=t.getSharedType(r,n,!!i.prototype);switch(a){case e.buffer:return Buffer&&Buffer.prototype.equals.call(r,n);case e.promise:return r===n;case e.regex:case e.url:return r.toString()===n.toString();case t.mismatched:return!1}for(let e=s.length-1;e>=0;--e)if(s[e].isSame(r,n))return!0;s.push(new t.SeenEntry(r,n));try{return!!t.isDeepEqualObj(a,r,n,i,s)}finally{s.pop()}},t.getSharedType=function(r,n,i){if(i)return Object.getPrototypeOf(r)!==Object.getPrototypeOf(n)?t.mismatched:e.getInternalProto(r);const s=e.getInternalProto(r)
3482
- ;return s!==e.getInternalProto(n)?t.mismatched:s},t.valueOf=function(e){const t=e.valueOf;if(void 0===t)return e;try{return t.call(e)}catch(e){return e}},t.hasOwnEnumerableProperty=function(e,t){return Object.prototype.propertyIsEnumerable.call(e,t)},t.isSetSimpleEqual=function(e,t){for(const r of Set.prototype.values.call(e))if(!Set.prototype.has.call(t,r))return!1;return!0},t.isDeepEqualObj=function(r,n,i,s,o){const{isDeepEqual:a,valueOf:c,hasOwnEnumerableProperty:u}=t,{keys:l,getOwnPropertySymbols:d}=Object;if(r===e.array){if(!s.part){if(n.length!==i.length)return!1;for(let e=0;e<n.length;++e)if(!a(n[e],i[e],s,o))return!1;return!0}for(const e of n)for(const t of i)if(a(e,t,s,o))return!0}else if(r===e.set){if(n.size!==i.size)return!1;if(!t.isSetSimpleEqual(n,i)){const e=new Set(Set.prototype.values.call(i));for(const t of Set.prototype.values.call(n)){if(e.delete(t))continue;let r=!1;for(const n of e)if(a(t,n,s,o)){e.delete(n),r=!0;break}if(!r)return!1}}}else if(r===e.map){
3483
- if(n.size!==i.size)return!1;for(const[e,t]of Map.prototype.entries.call(n)){if(void 0===t&&!Map.prototype.has.call(i,e))return!1;if(!a(t,Map.prototype.get.call(i,e),s,o))return!1}}else if(r===e.error&&(n.name!==i.name||n.message!==i.message))return!1;const p=c(n),h=c(i);if((n!==p||i!==h)&&!a(p,h,s,o))return!1;const A=l(n);if(!s.part&&A.length!==l(i).length&&!s.skip)return!1;let f=0;for(const e of A)if(s.skip&&s.skip.includes(e))void 0===i[e]&&++f;else{if(!u(i,e))return!1;if(!a(n[e],i[e],s,o))return!1}if(!s.part&&A.length-f!==l(i).length)return!1;if(!1!==s.symbols){const e=d(n),t=new Set(d(i));for(const r of e){if(!s.skip?.includes(r))if(u(n,r)){if(!u(i,r))return!1;if(!a(n[r],i[r],s,o))return!1}else if(u(i,r))return!1;t.delete(r)}for(const e of t)if(u(i,e))return!1}return!0},t.SeenEntry=class{constructor(e,t){this.obj=e,this.ref=t}isSame(e,t){return this.obj===e&&this.ref===t}},deepEqual}function requireEscapeRegex(){return hasRequiredEscapeRegex||(hasRequiredEscapeRegex=1,
3484
- escapeRegex$1=function(e){return e.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g,"\\$&")}),escapeRegex$1}function requireContain(){if(hasRequiredContain)return contain;hasRequiredContain=1;const e=requireAssert(),t=requireDeepEqual(),r=requireEscapeRegex(),n=requireUtils$1(),i={};return contain=function(t,r,n={}){return"object"!=typeof r&&(r=[r]),e(!Array.isArray(r)||r.length,"Values array cannot be empty"),"string"==typeof t?i.string(t,r,n):Array.isArray(t)?i.array(t,r,n):(e("object"==typeof t,"Reference must be string or an object"),i.object(t,r,n))},i.array=function(e,t,r){if(Array.isArray(t)||(t=[t]),!e.length)return!1;if(r.only&&r.once&&e.length!==t.length)return!1;let n;const s=new Map;for(const e of t)if(r.deep&&e&&"object"==typeof e){n=n??i.compare(r);let t=!1;for(const[r,i]of s.entries())if(n(r,e)){++i.allowed,t=!0;break}t||s.set(e,{allowed:1,hits:0})}else{const t=s.get(e);t?++t.allowed:s.set(e,{allowed:1,hits:0})}let o=0;for(const t of e){let e
3485
- ;if(r.deep&&t&&"object"==typeof t){n=n??i.compare(r);for(const[r,i]of s.entries())if(n(r,t)){e=i;break}}else e=s.get(t);if(e&&(++e.hits,++o,r.once&&e.hits>e.allowed))return!1}if(r.only&&o!==e.length)return!1;for(const e of s.values())if(e.hits!==e.allowed&&e.hits<e.allowed&&!r.part)return!1;return!!o},i.object=function(t,r,s){e(void 0===s.once,"Cannot use option once with object");const o=n.keys(t,s);if(!o.length)return!1;if(Array.isArray(r))return i.array(o,r,s);const a=Object.getOwnPropertySymbols(r).filter(e=>r.propertyIsEnumerable(e)),c=[...Object.keys(r),...a],u=i.compare(s),l=new Set(c);for(const e of o)if(l.has(e)){if(!u(r[e],t[e]))return!1;l.delete(e)}else if(s.only)return!1;return!l.size||!!s.part&&l.size<c.length},i.string=function(t,n,i){if(""===t)return 1===n.length&&""===n[0]||!i.once&&!n.some(e=>""!==e);const s=new Map,o=[];for(const t of n)if(e("string"==typeof t,"Cannot compare string reference to non-string value"),t){const e=s.get(t);e?++e.allowed:(s.set(t,{allowed:1,
3486
- hits:0}),o.push(r(t)))}else if(i.once||i.only)return!1;if(!o.length)return!0;const a=new RegExp(`(${o.join("|")})`,"g"),c=t.replace(a,(e,t)=>(++s.get(t).hits,""));if(i.only&&c)return!1;let u=!1;for(const e of s.values())if(e.hits&&(u=!0),e.hits!==e.allowed){if(e.hits<e.allowed&&!i.part)return!1;if(i.once)return!1}return!!u},i.compare=function(e){if(!e.deep)return i.shallow;const r=void 0!==e.only,n=void 0!==e.part,s={prototype:r?e.only:!!n&&!e.part,part:r?!e.only:!!n&&e.part};return(e,r)=>t(e,r,s)},i.shallow=function(e,t){return e===t},contain}function requireEscapeHeaderAttribute(){if(hasRequiredEscapeHeaderAttribute)return escapeHeaderAttribute;hasRequiredEscapeHeaderAttribute=1;const e=requireAssert();return escapeHeaderAttribute=function(t){return e(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(t),"Bad attribute value ("+t+")"),t.replace(/\\/g,"\\\\").replace(/\"/g,'\\"')},escapeHeaderAttribute}function requireEscapeHtml(){
3487
- if(hasRequiredEscapeHtml)return escapeHtml;hasRequiredEscapeHtml=1;const e={};return escapeHtml=function(t){if(!t)return"";let r="";for(let n=0;n<t.length;++n){const i=t.charCodeAt(n);e.isSafe(i)?r+=t[n]:r+=e.escapeHtmlChar(i)}return r},e.escapeHtmlChar=function(t){const r=e.namedHtml.get(t);if(r)return r;if(t>=256)return"&#"+t+";";return`&#x${t.toString(16).padStart(2,"0")};`},e.isSafe=function(t){return e.safeCharCodes.has(t)},e.namedHtml=new Map([[38,"&amp;"],[60,"&lt;"],[62,"&gt;"],[34,"&quot;"],[160,"&nbsp;"],[162,"&cent;"],[163,"&pound;"],[164,"&curren;"],[169,"&copy;"],[174,"&reg;"]]),e.safeCharCodes=function(){const e=new Set;for(let t=32;t<123;++t)(t>=97||t>=65&&t<=90||t>=48&&t<=57||32===t||46===t||44===t||45===t||58===t||95===t)&&e.add(t);return e}(),escapeHtml}function requireEscapeJson(){if(hasRequiredEscapeJson)return escapeJson;hasRequiredEscapeJson=1;const e={};return escapeJson=function(t){return t?t.replace(/[<>&\u2028\u2029]/g,e.escape):""},e.escape=function(t){
3488
- return e.replacements.get(t)},e.replacements=new Map([["<","\\u003c"],[">","\\u003e"],["&","\\u0026"],["\u2028","\\u2028"],["\u2029","\\u2029"]]),escapeJson}function requireFlatten(){if(hasRequiredFlatten)return flatten;hasRequiredFlatten=1;const e={};return flatten=e.flatten=function(t,r){const n=r||[];for(const r of t)Array.isArray(r)?e.flatten(r,n):n.push(r);return n},flatten}function requireIntersect(){if(hasRequiredIntersect)return intersect;hasRequiredIntersect=1;const e={};return intersect=function(t,r,n={}){if(!t||!r)return n.first?null:[];const i=[],s=Array.isArray(t)?new Set(t):t,o=new Set;for(const t of r)if(e.has(s,t)&&!o.has(t)){if(n.first)return t;i.push(t),o.add(t)}return n.first?null:i},e.has=function(e,t){return"function"==typeof e.has?e.has(t):void 0!==e[t]},intersect}function requireIsPromise$1(){return hasRequiredIsPromise$1?isPromise$1:(hasRequiredIsPromise$1=1,isPromise$1=function(e){return"function"==typeof e?.then})}function requireOnce(){
3489
- if(hasRequiredOnce)return once;hasRequiredOnce=1;const e=Symbol("wrapped");return once=function(t){if(t[e])return t;let r=!1;const n=function(...e){r||(r=!0,t(...e))};return n[e]=!0,n},once}function requireReachTemplate(){if(hasRequiredReachTemplate)return reachTemplate;hasRequiredReachTemplate=1;const e=requireReach();return reachTemplate=function(t,r,n){return r.replace(/{([^{}]+)}/g,(r,i)=>e(t,i,n)??"")},reachTemplate}function requireWait(){if(hasRequiredWait)return wait;hasRequiredWait=1;const e=2**31-1;return wait=function(t,r,n){if("bigint"==typeof t&&(t=Number(t)),t>=Number.MAX_SAFE_INTEGER&&(t=1/0),"number"!=typeof t&&void 0!==t)throw new TypeError("Timeout must be a number or bigint");return new Promise(i=>{const s=n?n.setTimeout:setTimeout,o=()=>{const n=Math.min(t,e);t-=n,s(()=>t>0?o():i(r),n)};t!==1/0&&o()})},wait}function requireLib$4(){return hasRequiredLib$4||(hasRequiredLib$4=1,lib$4.applyToDefaults=requireApplyToDefaults(),lib$4.assert=requireAssert(),
3490
- lib$4.AssertError=requireAssertError(),lib$4.Bench=requireBench(),lib$4.block=requireBlock(),lib$4.clone=requireClone(),lib$4.contain=requireContain(),lib$4.deepEqual=requireDeepEqual(),lib$4.escapeHeaderAttribute=requireEscapeHeaderAttribute(),lib$4.escapeHtml=requireEscapeHtml(),lib$4.escapeJson=requireEscapeJson(),lib$4.escapeRegex=requireEscapeRegex(),lib$4.flatten=requireFlatten(),lib$4.ignore=requireIgnore(),lib$4.intersect=requireIntersect(),lib$4.isPromise=requireIsPromise$1(),lib$4.merge=requireMerge$2(),lib$4.once=requireOnce(),lib$4.reach=requireReach(),lib$4.reachTemplate=requireReachTemplate(),lib$4.stringify=requireStringify$1(),lib$4.wait=requireWait()),lib$4}var cache={},common={},version$1="18.0.1",require$$1$1={version:version$1},schemas={},hasRequiredSchemas;function requireSchemas(){if(hasRequiredSchemas)return schemas;hasRequiredSchemas=1;const e=requireLib(),t={};return t.wrap=e.string().min(1).max(2).allow(!1),schemas.preferences=e.object({
3491
- allowUnknown:e.boolean(),abortEarly:e.boolean(),artifacts:e.boolean(),cache:e.boolean(),context:e.object(),convert:e.boolean(),dateFormat:e.valid("date","iso","string","time","utc"),debug:e.boolean(),errors:{escapeHtml:e.boolean(),label:e.valid("path","key",!1),language:[e.string(),e.object().ref()],render:e.boolean(),stack:e.boolean(),wrap:{label:t.wrap,array:t.wrap,string:t.wrap}},externals:e.boolean(),messages:e.object(),noDefaults:e.boolean(),nonEnumerables:e.boolean(),presence:e.valid("required","optional","forbidden"),skipFunctions:e.boolean(),stripUnknown:e.object({arrays:e.boolean(),objects:e.boolean()}).or("arrays","objects").allow(!0,!1),warnings:e.boolean()}).strict(),t.nameRx=/^[a-zA-Z0-9]\w*$/,t.rule=e.object({alias:e.array().items(e.string().pattern(t.nameRx)).single(),args:e.array().items(e.string(),e.object({name:e.string().pattern(t.nameRx).required(),ref:e.boolean(),assert:e.alternatives([e.function(),e.object().schema()]).conditional("ref",{is:!0,then:e.required()}),
3492
- normalize:e.function(),message:e.string().when("assert",{is:e.function(),then:e.required()})})),convert:e.boolean(),manifest:e.boolean(),method:e.function().allow(!1),multi:e.boolean(),validate:e.function()}),schemas.extension=e.object({type:e.alternatives([e.string(),e.object().regex()]).required(),args:e.function(),cast:e.object().pattern(t.nameRx,e.object({from:e.function().maxArity(1).required(),to:e.function().minArity(1).maxArity(2).required()})),base:e.object().schema().when("type",{is:e.object().regex(),then:e.forbidden()}),coerce:[e.function().maxArity(3),e.object({method:e.function().maxArity(3).required(),from:e.array().items(e.string()).single()})],flags:e.object().pattern(t.nameRx,e.object({setter:e.string(),default:e.any()})),manifest:{build:e.function().arity(2)},messages:[e.object(),e.string()],modifiers:e.object().pattern(t.nameRx,e.function().minArity(1).maxArity(2)),overrides:e.object().pattern(t.nameRx,e.function()),prepare:e.function().maxArity(3),
3493
- rebuild:e.function().arity(1),rules:e.object().pattern(t.nameRx,t.rule),terms:e.object().pattern(t.nameRx,e.object({init:e.array().allow(null).required(),manifest:e.object().pattern(/.+/,[e.valid("schema","single"),e.object({mapped:e.object({from:e.string().required(),to:e.string().required()}).required()})])})),validate:e.function().maxArity(3)}).strict(),schemas.extensions=e.array().items(e.object(),e.function().arity(1)).strict(),t.desc={buffer:e.object({buffer:e.string()}),func:e.object({function:e.function().required(),options:{literal:!0}}),override:e.object({override:!0}),ref:e.object({ref:e.object({type:e.valid("value","global","local"),path:e.array().required(),separator:e.string().length(1).allow(!1),ancestor:e.number().min(0).integer().allow("root"),map:e.array().items(e.array().length(2)).min(1),adjust:e.function(),iterables:e.boolean(),in:e.boolean(),render:e.boolean()}).required()}),regex:e.object({regex:e.string().min(3)}),special:e.object({
3494
- special:e.valid("deep").required()}),template:e.object({template:e.string().required(),options:e.object()}),value:e.object({value:e.alternatives([e.object(),e.array()]).required()})},t.desc.entity=e.alternatives([e.array().items(e.link("...")),e.boolean(),e.function(),e.number(),e.string(),t.desc.buffer,t.desc.func,t.desc.ref,t.desc.regex,t.desc.special,t.desc.template,t.desc.value,e.link("/")]),t.desc.values=e.array().items(null,e.boolean(),e.function(),e.number().allow(1/0,-1/0),e.string().allow(""),e.symbol(),t.desc.buffer,t.desc.func,t.desc.override,t.desc.ref,t.desc.regex,t.desc.template,t.desc.value),t.desc.messages=e.object().pattern(/.+/,[e.string(),t.desc.template,e.object().pattern(/.+/,[e.string(),t.desc.template])]),schemas.description=e.object({type:e.string().required(),flags:e.object({cast:e.string(),default:e.any(),description:e.string(),empty:e.link("/"),failover:t.desc.entity,id:e.string(),label:e.string(),only:!0,presence:["optional","required","forbidden"],
3495
- result:["raw","strip"],strip:e.boolean(),unit:e.string()}).unknown(),preferences:{allowUnknown:e.boolean(),abortEarly:e.boolean(),artifacts:e.boolean(),cache:e.boolean(),convert:e.boolean(),dateFormat:["date","iso","string","time","utc"],errors:{escapeHtml:e.boolean(),label:["path","key"],language:[e.string(),t.desc.ref],wrap:{label:t.wrap,array:t.wrap}},externals:e.boolean(),messages:t.desc.messages,noDefaults:e.boolean(),nonEnumerables:e.boolean(),presence:["required","optional","forbidden"],skipFunctions:e.boolean(),stripUnknown:e.object({arrays:e.boolean(),objects:e.boolean()}).or("arrays","objects").allow(!0,!1),warnings:e.boolean()},allow:t.desc.values,invalid:t.desc.values,rules:e.array().min(1).items({name:e.string().required(),args:e.object().min(1),keep:e.boolean(),message:[e.string(),t.desc.messages],warn:e.boolean()}),keys:e.object().pattern(/.*/,e.link("/")),link:t.desc.ref}).pattern(/^[a-z]\w*$/,e.any()),schemas}var messages={},template$1={exports:{}
3496
- },lib$3={},hasRequiredLib$3;function requireLib$3(){return hasRequiredLib$3||(hasRequiredLib$3=1,function(e){const t={operators:["!","^","*","/","%","+","-","<","<=",">",">=","==","!=","&&","||","??"],operatorCharacters:["!","^","*","/","%","+","-","<","=",">","&","|","?"],operatorsOrder:[["^"],["*","/","%"],["+","-"],["<","<=",">",">="],["==","!="],["&&"],["||","??"]],operatorsPrefix:["!","n"],literals:{'"':'"',"`":"`","'":"'","[":"]"},numberRx:/^(?:[0-9]*(\.[0-9]*)?){1}$/,tokenRx:/^[\w\$\#\.\@\:\{\}]+$/,symbol:Symbol("formula"),settings:Symbol("settings")};e.Parser=class{constructor(e,r={}){if(!r[t.settings]&&r.constants)for(const e in r.constants){const t=r.constants[e];if(null!==t&&!["boolean","number","string"].includes(typeof t))throw new Error(`Formula constant ${e} contains invalid ${typeof t} value type`)}this.settings=r[t.settings]?r:Object.assign({[t.settings]:!0,constants:{},functions:{}},r),this.single=null,this._parts=null,this._parse(e)}_parse(r){let n=[],i="",s=0,o=!1
3497
- ;const a=r=>{if(s)throw new Error("Formula missing closing parenthesis");const a=n.length?n[n.length-1]:null;if(o||i||r){if(a&&"reference"===a.type&&")"===r)return a.type="function",a.value=this._subFormula(i,a.value),void(i="");if(")"===r){const t=new e.Parser(i,this.settings);n.push({type:"segment",value:t})}else if(o){if("]"===o)return n.push({type:"reference",value:i}),void(i="");n.push({type:"literal",value:i})}else if(t.operatorCharacters.includes(i))a&&"operator"===a.type&&t.operators.includes(a.value+i)?a.value+=i:n.push({type:"operator",value:i});else if(i.match(t.numberRx))n.push({type:"constant",value:parseFloat(i)});else if(void 0!==this.settings.constants[i])n.push({type:"constant",value:this.settings.constants[i]});else{if(!i.match(t.tokenRx))throw new Error(`Formula contains invalid token: ${i}`);n.push({type:"reference",value:i})}i=""}};for(const e of r)o?e===o?(a(),o=!1):i+=e:s?"("===e?(i+=e,++s):")"===e?(--s,
3498
- s?i+=e:a(e)):i+=e:e in t.literals?o=t.literals[e]:"("===e?(a(),++s):t.operatorCharacters.includes(e)?(a(),i=e,a()):" "!==e?i+=e:a();a(),n=n.map((e,t)=>"operator"!==e.type||"-"!==e.value||t&&"operator"!==n[t-1].type?e:{type:"operator",value:"n"});let c=!1;for(const e of n){if("operator"===e.type){if(t.operatorsPrefix.includes(e.value))continue;if(!c)throw new Error("Formula contains an operator in invalid position");if(!t.operators.includes(e.value))throw new Error(`Formula contains an unknown operator ${e.value}`)}else if(c)throw new Error("Formula missing expected operator");c=!c}if(!c)throw new Error("Formula contains invalid trailing operator");1===n.length&&["reference","literal","constant"].includes(n[0].type)&&(this.single={type:"reference"===n[0].type?"reference":"value",value:n[0].value}),this._parts=n.map(e=>{if("operator"===e.type)return t.operatorsPrefix.includes(e.value)?e:e.value;if("reference"!==e.type)return e.value
3499
- ;if(this.settings.tokenRx&&!this.settings.tokenRx.test(e.value))throw new Error(`Formula contains invalid reference ${e.value}`);return this.settings.reference?this.settings.reference(e.value):t.reference(e.value)})}_subFormula(r,n){const i=this.settings.functions[n];if("function"!=typeof i)throw new Error(`Formula contains unknown function ${n}`);let s=[];if(r){let e="",i=0,o=!1;const a=()=>{if(!e)throw new Error(`Formula contains function ${n} with invalid arguments ${r}`);s.push(e),e=""};for(let n=0;n<r.length;++n){const s=r[n];o?(e+=s,s===o&&(o=!1)):s in t.literals&&!i?(e+=s,o=t.literals[s]):","!==s||i?(e+=s,"("===s?++i:")"===s&&--i):a()}a()}return s=s.map(t=>new e.Parser(t,this.settings)),function(e){const t=[];for(const r of s)t.push(r.evaluate(e));return i.call(e,...t)}}evaluate(e){const r=this._parts.slice();for(let n=r.length-2;n>=0;--n){const i=r[n];if(i&&"operator"===i.type){const s=r[n+1];r.splice(n+1,1);const o=t.evaluate(s,e);r[n]=t.single(i.value,o)}}
3500
- return t.operatorsOrder.forEach(n=>{for(let i=1;i<r.length-1;)if(n.includes(r[i])){const n=r[i],s=t.evaluate(r[i-1],e),o=t.evaluate(r[i+1],e);r.splice(i,2);const a=t.calculate(n,s,o);r[i-1]=0===a?0:a}else i+=2}),t.evaluate(r[0],e)}},e.Parser.prototype[t.symbol]=!0,t.reference=function(e){return function(t){return t&&void 0!==t[e]?t[e]:null}},t.evaluate=function(e,r){return null===e?null:"function"==typeof e?e(r):e[t.symbol]?e.evaluate(r):e},t.single=function(e,t){if("!"===e)return!t;const r=-t;return 0===r?0:r},t.calculate=function(e,r,n){if("??"===e)return t.exists(r)?r:n;if("string"==typeof r||"string"==typeof n){if("+"===e)return(r=t.exists(r)?r:"")+(n=t.exists(n)?n:"")}else switch(e){case"^":return Math.pow(r,n);case"*":return r*n;case"/":return r/n;case"%":return r%n;case"+":return r+n;case"-":return r-n}switch(e){case"<":return r<n;case"<=":return r<=n;case">":return r>n;case">=":return r>=n;case"==":return r===n;case"!=":return r!==n;case"&&":return r&&n;case"||":return r||n}
3501
- return null},t.exists=function(e){return null!=e}}(lib$3)),lib$3}var errors$1={},annotate={},hasRequiredAnnotate,hasRequiredErrors$1;function requireAnnotate(){if(hasRequiredAnnotate)return annotate;hasRequiredAnnotate=1;const{clone:e}=requireLib$4(),t=requireCommon(),r={annotations:Symbol("annotations")};return annotate.error=function(n){if(!this._original||"object"!=typeof this._original)return this.details[0].message;const i=n?"":"",s=n?"":"",o=n?"":"",a=e(this._original);for(let e=this.details.length-1;e>=0;--e){const n=e+1,i=this.details[e],s=i.path;let o=a;for(let e=0;;++e){const a=s[e];if(t.isSchema(o)&&(o=o.clone()),!(e+1<s.length&&"string"!=typeof o[a])){const e=o[r.annotations]||{errors:{},missing:{}};o[r.annotations]=e;const t=a||i.context.key;void 0!==o[a]?(e.errors[t]=e.errors[t]||[],e.errors[t].push(n)):e.missing[t]=n;break}o=o[a]}}
3502
- const c=/_\$key\$_([, \d]+)_\$end\$_"/g,u=/"_\$miss\$_([^|]+)\|(\d+)_\$end\$_": "__missing__"/g,l=/\s*"_\$idx\$_([, \d]+)_\$end\$_",?\n(.*)/g,d=/"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)]"/g;let p=r.safeStringify(a,2).replace(c,(e,t)=>`" ${i}[${t}]${o}`).replace(u,(e,t,r)=>`${s}"${t}"${o}${i} [${r}]: -- missing --${o}`).replace(l,(e,t,r)=>`\n${r} ${i}[${t}]${o}`).replace(d,(e,t)=>t);p=`${p}\n${i}`;for(let e=0;e<this.details.length;++e){p=`${p}\n[${e+1}] ${this.details[e].message}`}return p+=o,p},r.safeStringify=function(e,t){return JSON.stringify(e,r.serializer(),t)},r.serializer=function(){const e=[],t=[],n=(r,n)=>t[0]===n?"[Circular ~]":"[Circular ~."+e.slice(0,t.indexOf(n)).join(".")+"]";return function(i,s){if(t.length>0){const r=t.indexOf(this);~r?(t.length=r+1,e.length=r+1,e[r]=i):(t.push(this),e.push(i)),~t.indexOf(s)&&(s=n.call(this,i,s))}else t.push(s);if(s){const e=s[r.annotations];if(e){if(Array.isArray(s)){const t=[]
3503
- ;for(let r=0;r<s.length;++r)e.errors[r]&&t.push(`_$idx$_${e.errors[r].sort().join(", ")}_$end$_`),t.push(s[r]);s=t}else{for(const t in e.errors)s[`${t}_$key$_${e.errors[t].sort().join(", ")}_$end$_`]=s[t],s[t]=void 0;for(const t in e.missing)s[`_$miss$_${t}|${e.missing[t]}_$end$_`]="__missing__"}return s}}return s===1/0||s===-1/0||Number.isNaN(s)||"function"==typeof s||"symbol"==typeof s?"["+s.toString()+"]":s}},annotate}function requireErrors$1(){return hasRequiredErrors$1||(hasRequiredErrors$1=1,function(e){const t=requireAnnotate(),r=requireCommon(),n=requireTemplate();e.Report=class{constructor(t,r,n,i,s,o,a){if(this.code=t,this.flags=i,this.messages=s,this.path=o.path,this.prefs=a,this.state=o,this.value=r,this.message=null,this.template=null,this.local=n||{},this.local.label=e.label(this.flags,this.state,this.prefs,this.messages),void 0===this.value||this.local.hasOwnProperty("value")||(this.local.value=this.value),this.path.length){const e=this.path[this.path.length-1]
3504
- ;"object"!=typeof e&&(this.local.key=e)}}_setTemplate(e){if(this.template=e,!this.flags.label&&0===this.path.length){const e=this._template(this.template,"root");e&&(this.local.label=e)}}toString(){if(this.message)return this.message;const e=this.code;if(!this.prefs.errors.render)return this.code;const t=this._template(this.template)||this._template(this.prefs.messages)||this._template(this.messages);return void 0===t?`Error code "${e}" is not defined, your custom type is missing the correct messages definition`:(this.message=t.render(this.value,this.state,this.prefs,this.local,{errors:this.prefs.errors,messages:[this.prefs.messages,this.messages]}),this.prefs.errors.label||(this.message=this.message.replace(/^"" /,"").trim()),this.message)}_template(t,r){return e.template(this.value,t,r||this.code,this.state,this.prefs)}},e.path=function(e){let t="";for(const r of e)"object"!=typeof r&&("string"==typeof r?(t&&(t+="."),t+=r):t+=`[${r}]`);return t},e.template=function(e,t,i,s,o){
3505
- if(!t)return;if(n.isTemplate(t))return"root"!==i?t:null;let a=o.errors.language;if(r.isResolvable(a)&&(a=a.resolve(e,s,o)),a&&t[a]){if(void 0!==t[a][i])return t[a][i];if(void 0!==t[a]["*"])return t[a]["*"]}return t[i]?t[i]:t["*"]},e.label=function(t,r,n,i){if(!n.errors.label)return"";if(t.label)return t.label;let s=r.path;"key"===n.errors.label&&r.path.length>1&&(s=r.path.slice(-1));const o=e.path(s);return o||(e.template(null,n.messages,"root",r,n)||i&&e.template(null,i,"root",r,n)||"value")},e.process=function(t,r,n){if(!t)return null;const{override:i,message:s,details:o}=e.details(t);if(i)return i;if(n.errors.stack)return new e.ValidationError(s,o,r);const a=Error.stackTraceLimit;Error.stackTraceLimit=0;const c=new e.ValidationError(s,o,r);return Error.stackTraceLimit=a,c},e.details=function(e,t={}){let r=[];const n=[];for(const i of e){if(i instanceof Error){if(!1!==t.override)return{override:i};const e=i.toString();r.push(e),n.push({message:e,type:"override",context:{error:i}})
3506
- ;continue}const e=i.toString();r.push(e),n.push({message:e,path:i.path.filter(e=>"object"!=typeof e),type:i.code,context:i.local})}return r.length>1&&(r=[...new Set(r)]),{message:r.join(". "),details:n}},e.ValidationError=class extends Error{constructor(e,t,r){super(e),this._original=r,this.details=t}static isError(t){return t instanceof e.ValidationError}},e.ValidationError.prototype.isJoi=!0,e.ValidationError.prototype.name="ValidationError",e.ValidationError.prototype.annotate=t.error}(errors$1)),errors$1}var ref$2={},hasRequiredRef$1,hasRequiredTemplate,hasRequiredMessages,hasRequiredCommon,hasRequiredCache;function requireRef$1(){return hasRequiredRef$1||(hasRequiredRef$1=1,function(e){const{assert:t,clone:r,reach:n}=requireLib$4(),i=requireCommon();let s;const o={symbol:Symbol("ref"),defaults:{adjust:null,in:!1,iterables:null,map:null,separator:".",type:"value"}};e.create=function(e,r={}){t("string"==typeof e,"Invalid reference key:",e),
3507
- i.assertOptions(r,["adjust","ancestor","in","iterables","map","prefix","render","separator"]),t(!r.prefix||"object"==typeof r.prefix,"options.prefix must be of type object");const n=Object.assign({},o.defaults,r);delete n.prefix;const s=n.separator,a=o.context(e,s,r.prefix);if(n.type=a.type,e=a.key,"value"===n.type)if(a.root&&(t(!s||e[0]!==s,"Cannot specify relative path with root prefix"),n.ancestor="root",e||(e=null)),s&&s===e)e=null,n.ancestor=0;else if(void 0!==n.ancestor)t(!s||!e||e[0]!==s,"Cannot combine prefix with ancestor option");else{const[t,r]=o.ancestor(e,s);r&&""===(e=e.slice(r))&&(e=null),n.ancestor=t}return n.path=s?null===e?[]:e.split(s):[e],new o.Ref(n)},e.in=function(t,r={}){return e.create(t,{...r,in:!0})},e.isRef=function(e){return!!e&&!!e[i.symbols.ref]},o.Ref=class{constructor(e){t("object"==typeof e,"Invalid reference construction"),i.assertOptions(e,["adjust","ancestor","in","iterables","map","path","render","separator","type","depth","key","root","display"]),
3508
- t([!1,void 0].includes(e.separator)||"string"==typeof e.separator&&1===e.separator.length,"Invalid separator"),t(!e.adjust||"function"==typeof e.adjust,"options.adjust must be a function"),t(!e.map||Array.isArray(e.map),"options.map must be an array"),t(!e.map||!e.adjust,"Cannot set both map and adjust options"),Object.assign(this,o.defaults,e),t("value"===this.type||void 0===this.ancestor,"Non-value references cannot reference ancestors"),Array.isArray(this.map)&&(this.map=new Map(this.map)),this.depth=this.path.length,this.key=this.path.length?this.path.join(this.separator):null,this.root=this.path[0],this.updateDisplay()}resolve(e,r,n,i,s={}){return t(!this.in||s.in,"Invalid in() reference usage"),"global"===this.type?this._resolve(n.context,r,s):"local"===this.type?this._resolve(i,r,s):this.ancestor?"root"===this.ancestor?this._resolve(r.ancestors[r.ancestors.length-1],r,s):(t(this.ancestor<=r.ancestors.length,"Invalid reference exceeds the schema root:",this.display),
3509
- this._resolve(r.ancestors[this.ancestor-1],r,s)):this._resolve(e,r,s)}_resolve(e,t,r){let i;if("value"===this.type&&t.mainstay.shadow&&!1!==r.shadow&&(i=t.mainstay.shadow.get(this.absolute(t))),void 0===i&&(i=n(e,this.path,{iterables:this.iterables,functions:!0})),this.adjust&&(i=this.adjust(i)),this.map){const e=this.map.get(i);void 0!==e&&(i=e)}return t.mainstay&&t.mainstay.tracer.resolve(t,this,i),i}toString(){return this.display}absolute(e){return[...e.path.slice(0,-this.ancestor),...this.path]}clone(){return new o.Ref(this)}describe(){const e={path:this.path};"value"!==this.type&&(e.type=this.type),"."!==this.separator&&(e.separator=this.separator),"value"===this.type&&1!==this.ancestor&&(e.ancestor=this.ancestor),this.map&&(e.map=[...this.map]);for(const t of["adjust","iterables","render"])null!==this[t]&&void 0!==this[t]&&(e[t]=this[t]);return!1!==this.in&&(e.in=!0),{ref:e}}updateDisplay(){const e=null!==this.key?this.key:""
3510
- ;if("value"!==this.type)return void(this.display=`ref:${this.type}:${e}`);if(!this.separator)return void(this.display=`ref:${e}`);if(!this.ancestor)return void(this.display=`ref:${this.separator}${e}`);if("root"===this.ancestor)return void(this.display=`ref:root:${e}`);if(1===this.ancestor)return void(this.display=`ref:${e||".."}`);const t=new Array(this.ancestor+1).fill(this.separator).join("");this.display=`ref:${t}${e||""}`}},o.Ref.prototype[i.symbols.ref]=!0,e.build=function(e){return"value"===(e=Object.assign({},o.defaults,e)).type&&void 0===e.ancestor&&(e.ancestor=1),new o.Ref(e)},o.context=function(e,t,r={}){if(e=e.trim(),r){const n=void 0===r.global?"$":r.global;if(n!==t&&e.startsWith(n))return{key:e.slice(n.length),type:"global"};const i=void 0===r.local?"#":r.local;if(i!==t&&e.startsWith(i))return{key:e.slice(i.length),type:"local"};const s=void 0===r.root?"/":r.root;if(s!==t&&e.startsWith(s))return{key:e.slice(s.length),type:"value",root:!0}}return{key:e,type:"value"}},
3511
- o.ancestor=function(e,t){if(!t)return[1,0];if(e[0]!==t)return[1,0];if(e[1]!==t)return[0,1];let r=2;for(;e[r]===t;)++r;return[r-1,r]},e.toSibling=0,e.toParent=1,e.Manager=class{constructor(){this.refs=[]}register(t,r){if(t)if(r=void 0===r?e.toParent:r,Array.isArray(t))for(const e of t)this.register(e,r);else if(i.isSchema(t))for(const e of t._refs.refs)e.ancestor-r>=0&&this.refs.push({ancestor:e.ancestor-r,root:e.root});else e.isRef(t)&&"value"===t.type&&t.ancestor-r>=0&&this.refs.push({ancestor:t.ancestor-r,root:t.root}),s=s||requireTemplate(),s.isTemplate(t)&&this.register(t.refs(),r)}get length(){return this.refs.length}clone(){const t=new e.Manager;return t.refs=r(this.refs),t}reset(){this.refs=[]}roots(){return this.refs.filter(e=>!e.ancestor).map(e=>e.root)}}}(ref$2)),ref$2}function requireTemplate(){return hasRequiredTemplate||(hasRequiredTemplate=1,function(e){
3512
- const{assert:t,clone:r,escapeHtml:n}=requireLib$4(),i=requireLib$3(),s=requireCommon(),o=requireErrors$1(),a=requireRef$1(),c={symbol:Symbol("template"),opens:new Array(1e3).join("\0"),closes:new Array(1e3).join(""),dateFormat:{date:Date.prototype.toDateString,iso:Date.prototype.toISOString,string:Date.prototype.toString,time:Date.prototype.toTimeString,utc:Date.prototype.toUTCString}};e.exports=c.Template=class{constructor(e,n){if(t("string"==typeof e,"Template source must be a string"),t(!e.includes("\0")&&!e.includes(""),"Template source cannot contain reserved control characters"),this.source=e,this.rendered=e,this._template=null,n){const{functions:e,...i}=n;this._settings=Object.keys(i).length?r(i):void 0,this._functions=e,this._functions&&(t(Object.keys(this._functions).every(e=>"string"==typeof e),"Functions keys must be strings"),t(Object.values(this._functions).every(e=>"function"==typeof e),"Functions values must be functions"))}else this._settings=void 0,
3513
- this._functions=void 0;this._parse()}_parse(){if(!this.source.includes("{"))return;const e=c.encode(this.source),t=c.split(e);let r=!1;const n=[],i=t.shift();i&&n.push(i);for(const e of t){const t="{"!==e[0],i=t?"}":"}}",s=e.indexOf(i);if(-1===s||"{"===e[1]){n.push(`{${c.decode(e)}`);continue}let o=e.slice(t?0:1,s);const a=":"===o[0];a&&(o=o.slice(1));const u=this._ref(c.decode(o),{raw:t,wrapped:a});n.push(u),"string"!=typeof u&&(r=!0);const l=e.slice(s+i.length);l&&n.push(c.decode(l))}r?this._template=n:this.rendered=n.join("")}static date(e,t){return c.dateFormat[t.dateFormat].call(e)}describe(e={}){if(!this._settings&&e.compact)return this.source;const t={template:this.source};return this._settings&&(t.options=this._settings),this._functions&&(t.functions=this._functions),t}static build(e){return new c.Template(e.template,e.options||e.functions?{...e.options,functions:e.functions}:void 0)}isDynamic(){return!!this._template}static isTemplate(e){return!!e&&!!e[s.symbols.template]}
3514
- refs(){if(!this._template)return;const e=[];for(const t of this._template)"string"!=typeof t&&e.push(...t.refs);return e}resolve(e,t,r,n){return this._template&&1===this._template.length?this._part(this._template[0],e,t,r,n,{}):this.render(e,t,r,n)}_part(e,...t){return e.ref?e.ref.resolve(...t):e.formula.evaluate(t)}render(e,t,r,i,s={}){if(!this.isDynamic())return this.rendered;const o=[];for(const a of this._template)if("string"==typeof a)o.push(a);else{const u=this._part(a,e,t,r,i,s),l=c.stringify(u,e,t,r,i,s);if(void 0!==l){const e=a.raw||!1===(s.errors&&s.errors.escapeHtml)?l:n(l);o.push(c.wrap(e,a.wrapped&&r.errors.wrap.label))}}return o.join("")}_ref(e,{raw:t,wrapped:r}){const n=[],s=e=>{const t=a.create(e,this._settings);return n.push(t),e=>{const r=t.resolve(...e);return void 0!==r?r:null}};try{const t=this._functions?{...c.functions,...this._functions}:c.functions;var o=new i.Parser(e,{reference:s,functions:t,constants:c.constants})}catch(t){
3515
- throw t.message=`Invalid template variable "${e}" fails due to: ${t.message}`,t}if(o.single){if("reference"===o.single.type){const e=n[0];return{ref:e,raw:t,refs:n,wrapped:r||"local"===e.type&&"label"===e.key}}return c.stringify(o.single.value)}return{formula:o,raw:t,refs:n}}toString(){return this.source}},c.Template.prototype[s.symbols.template]=!0,c.Template.prototype.isImmutable=!0,c.encode=function(e){return e.replace(/\\(\{+)/g,(e,t)=>c.opens.slice(0,t.length)).replace(/\\(\}+)/g,(e,t)=>c.closes.slice(0,t.length))},c.decode=function(e){return e.replace(/\u0000/g,"{").replace(/\u0001/g,"}")},c.split=function(e){const t=[];let r="";for(let n=0;n<e.length;++n){const i=e[n];if("{"===i){let i="";for(;n+1<e.length&&"{"===e[n+1];)i+="{",++n;t.push(r),r=i}else r+=i}return t.push(r),t},c.wrap=function(e,t){return t?1===t.length?`${t}${e}${t}`:`${t[0]}${e}${t[1]}`:e},c.stringify=function(e,t,r,n,i,s={}){const o=typeof e,u=n&&n.errors&&n.errors.wrap||{};let l=!1
3516
- ;if(a.isRef(e)&&e.render&&(l=e.in,e=e.resolve(t,r,n,i,{in:e.in,...s})),null===e)return"null";if("string"===o)return c.wrap(e,s.arrayItems&&u.string);if("number"===o||"function"===o||"symbol"===o)return e.toString();if("object"!==o)return JSON.stringify(e);if(e instanceof Date)return c.Template.date(e,n);if(e instanceof Map){const t=[];for(const[r,n]of e.entries())t.push(`${r.toString()} -> ${n.toString()}`);e=t}if(!Array.isArray(e))return e.toString();const d=[];for(const o of e)d.push(c.stringify(o,t,r,n,i,{arrayItems:!0,...s}));return c.wrap(d.join(", "),!l&&u.array)},c.constants={true:!0,false:!1,null:null,second:1e3,minute:6e4,hour:36e5,day:864e5},c.functions={if:(e,t,r)=>e?t:r,length:e=>"string"==typeof e?e.length:e&&"object"==typeof e?Array.isArray(e)?e.length:Object.keys(e).length:null,msg(e){const[t,r,n,i,s]=this,a=s.messages;if(!a)return"";const c=o.template(t,a[0],e,r,n)||o.template(t,a[1],e,r,n);return c?c.render(t,r,n,i,s):""},
3517
- number:e=>"number"==typeof e?e:"string"==typeof e?parseFloat(e):"boolean"==typeof e?e?1:0:e instanceof Date?e.getTime():null}}(template$1)),template$1.exports}function requireMessages(){return hasRequiredMessages||(hasRequiredMessages=1,function(e){const{assert:t,clone:r}=requireLib$4(),n=requireTemplate();e.compile=function(e,i){if("string"==typeof e)return t(!i,"Cannot set single message string"),new n(e);if(n.isTemplate(e))return t(!i,"Cannot set single message template"),e;t("object"==typeof e&&!Array.isArray(e),"Invalid message options"),i=i?r(i):{};for(let r in e){const s=e[r];if("root"===r||n.isTemplate(s)){i[r]=s;continue}if("string"==typeof s){i[r]=new n(s);continue}t("object"==typeof s&&!Array.isArray(s),"Invalid message for",r);const o=r;for(r in i[o]=i[o]||{},s){const e=s[r];"root"===r||n.isTemplate(e)?i[o][r]=e:(t("string"==typeof e,"Invalid message for",r,"in",o),i[o][r]=new n(e))}}return i},e.decompile=function(e){const t={};for(let r in e){const i=e[r];if("root"===r){
3518
- t.root=i;continue}if(n.isTemplate(i)){t[r]=i.describe({compact:!0});continue}const s=r;for(r in t[s]={},i){const e=i[r];"root"!==r?t[s][r]=e.describe({compact:!0}):t[s].root=e}}return t},e.merge=function(i,s){if(!i)return e.compile(s);if(!s)return i;if("string"==typeof s)return new n(s);if(n.isTemplate(s))return s;const o=r(i);for(let e in s){const r=s[e];if("root"===e||n.isTemplate(r)){o[e]=r;continue}if("string"==typeof r){o[e]=new n(r);continue}t("object"==typeof r&&!Array.isArray(r),"Invalid message for",e);const i=e;for(e in o[i]=o[i]||{},r){const s=r[e];"root"===e||n.isTemplate(s)?o[i][e]=s:(t("string"==typeof s,"Invalid message for",e,"in",i),o[i][e]=new n(s))}}return o}}(messages)),messages}function requireCommon(){return hasRequiredCommon||(hasRequiredCommon=1,function(e){const{assert:t,AssertError:r}=requireLib$4(),n=require$$1$1;let i,s;const o={
3519
- isoDate:/^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/};e.version=n.version,e.defaults={abortEarly:!0,allowUnknown:!1,artifacts:!1,cache:!0,context:null,convert:!0,dateFormat:"iso",errors:{escapeHtml:!1,label:"path",language:null,render:!0,stack:!1,wrap:{label:'"',array:"[]"}},externals:!0,messages:{},nonEnumerables:!1,noDefaults:!1,presence:"optional",skipFunctions:!1,stripUnknown:!1,warnings:!1},e.symbols={any:Symbol.for("@hapi/joi/schema"),arraySingle:Symbol("arraySingle"),deepDefault:Symbol("deepDefault"),errors:Symbol("errors"),literal:Symbol("literal"),override:Symbol("override"),parent:Symbol("parent"),prefs:Symbol("prefs"),ref:Symbol("ref"),template:Symbol("template"),
3520
- values:Symbol("values")},e.assertOptions=function(e,r,n="Options"){t(e&&"object"==typeof e&&!Array.isArray(e),"Options must be of type object");const i=Object.keys(e).filter(e=>!r.includes(e));t(0===i.length,`${n} contain unknown keys: ${i}`)},e.checkPreferences=function(e){s=s||requireSchemas();const t=s.preferences.validate(e);if(t.error)throw new r([t.error.details[0].message])},e.compare=function(e,t,r){switch(r){case"=":return e===t;case">":return e>t;case"<":return e<t;case">=":return e>=t;case"<=":return e<=t}},e.default=function(e,t){return void 0===e?t:e},e.isIsoDate=function(e){return o.isoDate.test(e)},e.isNumber=function(e){return"number"==typeof e&&!isNaN(e)},e.isResolvable=function(t){return!!t&&(t[e.symbols.ref]||t[e.symbols.template])},e.isSchema=function(r,n={}){const i=r&&r[e.symbols.any];return!!i&&(t(n.legacy||i.version===e.version,"Cannot mix different versions of joi schemas"),!0)},e.isValues=function(t){return t[e.symbols.values]},e.limit=function(e){
3521
- return Number.isSafeInteger(e)&&e>=0},e.preferences=function(t,r){i=i||requireMessages(),t=t||{},r=r||{};const n=Object.assign({},t,r);return r.errors&&t.errors&&(n.errors=Object.assign({},t.errors,r.errors),n.errors.wrap=Object.assign({},t.errors.wrap,r.errors.wrap)),r.messages&&(n.messages=i.compile(r.messages,t.messages)),delete n[e.symbols.prefs],n},e.tryWithPath=function(e,t,r={}){try{return e()}catch(e){throw void 0!==e.path?e.path=t+"."+e.path:e.path=t,r.append&&(e.message=`${e.message} (${e.path})`),e}},e.validateArg=function(t,r,{assert:n,message:i}){if(e.isSchema(n)){const e=n.validate(t);if(!e.error)return;return e.error.message}if(!n(t))return r?`${r} ${i}`:i},e.verifyFlat=function(e,r){for(const n of e)t(!Array.isArray(n),"Method no longer accepts array arguments:",r)}}(common)),common}function requireCache(){if(hasRequiredCache)return cache;hasRequiredCache=1;const{assert:e,clone:t}=requireLib$4(),r=requireCommon(),n={max:1e3,
3522
- supported:new Set(["undefined","boolean","number","string"])};return cache.provider={provision:e=>new n.Cache(e)},n.Cache=class{constructor(t={}){r.assertOptions(t,["max"]),e(void 0===t.max||t.max&&t.max>0&&isFinite(t.max),"Invalid max cache size"),this._max=t.max||n.max,this._map=new Map,this._list=new n.List}get length(){return this._map.size}set(e,t){if(null!==e&&!n.supported.has(typeof e))return;let r=this._map.get(e);if(r)return r.value=t,void this._list.first(r);r=this._list.unshift({key:e,value:t}),this._map.set(e,r),this._compact()}get(e){const r=this._map.get(e);if(r)return this._list.first(r),t(r.value)}_compact(){if(this._map.size>this._max){const e=this._list.pop();this._map.delete(e.key)}}},n.List=class{constructor(){this.tail=null,this.head=null}unshift(e){return e.next=null,e.prev=this.head,this.head&&(this.head.next=e),this.head=e,this.tail||(this.tail=e),e}first(e){e!==this.head&&(this._remove(e),this.unshift(e))}pop(){return this._remove(this.tail)}_remove(e){
3523
- const{next:t,prev:r}=e;return t.prev=r,r&&(r.next=t),e===this.tail&&(this.tail=t),e.prev=null,e.next=null,e}},cache}var compile={},hasRequiredCompile;function requireCompile(){return hasRequiredCompile||(hasRequiredCompile=1,function(e){const{assert:t}=requireLib$4(),r=requireCommon(),n=requireRef$1(),i={};e.schema=function(e,t,n={}){r.assertOptions(n,["appendPath","override"]);try{return i.schema(e,t,n)}catch(e){throw n.appendPath&&void 0!==e.path&&(e.message=`${e.message} (${e.path})`),e}},i.schema=function(e,n,s){t(void 0!==n,"Invalid undefined schema"),Array.isArray(n)&&(t(n.length,"Invalid empty array schema"),1===n.length&&(n=n[0]));const o=(t,...r)=>!1!==s.override?t.valid(e.override,...r):t.valid(...r);if(i.simple(n))return o(e,n);if("function"==typeof n)return e.custom(n);if(t("object"==typeof n,"Invalid schema content:",typeof n),r.isResolvable(n))return o(e,n);if(r.isSchema(n))return n;if(Array.isArray(n)){for(const t of n)if(!i.simple(t))return e.alternatives().try(...n)
3524
- ;return o(e,...n)}return n instanceof RegExp?e.string().regex(n):n instanceof Date?o(e.date(),n):(t(Object.getPrototypeOf(n)===Object.getPrototypeOf({}),"Schema can only contain plain objects"),e.object().keys(n))},e.ref=function(e,t){return n.isRef(e)?e:n.create(e,t)},e.compile=function(n,s,o={}){r.assertOptions(o,["legacy"]);const a=s&&s[r.symbols.any];if(a)return t(o.legacy||a.version===r.version,"Cannot mix different versions of joi schemas:",a.version,r.version),s;if("object"!=typeof s||!o.legacy)return e.schema(n,s,{appendPath:!0});const c=i.walk(s);return c?c.compile(c.root,s):e.schema(n,s,{appendPath:!0})},i.walk=function(e){if("object"!=typeof e)return null;if(Array.isArray(e)){for(const t of e){const e=i.walk(t);if(e)return e}return null}const n=e[r.symbols.any];if(n)return{root:e[n.root],compile:n.compile};t(Object.getPrototypeOf(e)===Object.getPrototypeOf({}),"Schema can only contain plain objects");for(const t in e){const r=i.walk(e[t]);if(r)return r}return null},
3525
- i.simple=function(e){return null===e||["boolean","string","number"].includes(typeof e)},e.when=function(s,o,a){if(void 0===a&&(t(o&&"object"==typeof o,"Missing options"),a=o,o=n.create(".")),Array.isArray(a)&&(a={switch:a}),r.assertOptions(a,["is","not","then","otherwise","switch","break"]),r.isSchema(o))return t(void 0===a.is,'"is" can not be used with a schema condition'),t(void 0===a.not,'"not" can not be used with a schema condition'),t(void 0===a.switch,'"switch" can not be used with a schema condition'),i.condition(s,{is:o,then:a.then,otherwise:a.otherwise,break:a.break});if(t(n.isRef(o)||"string"==typeof o,"Invalid condition:",o),t(void 0===a.not||void 0===a.is,'Cannot combine "is" with "not"'),void 0===a.switch){let c=a;void 0!==a.not&&(c={is:a.not,then:a.otherwise,otherwise:a.then,break:a.break});let u=void 0!==c.is?s.$_compile(c.is):s.$_root.invalid(null,!1,0,"").required()
3526
- ;return t(void 0!==c.then||void 0!==c.otherwise,'options must have at least one of "then", "otherwise", or "switch"'),t(void 0===c.break||void 0===c.then||void 0===c.otherwise,"Cannot specify then, otherwise, and break all together"),void 0===a.is||n.isRef(a.is)||r.isSchema(a.is)||(u=u.required()),i.condition(s,{ref:e.ref(o),is:u,then:c.then,otherwise:c.otherwise,break:c.break})}t(Array.isArray(a.switch),'"switch" must be an array'),t(void 0===a.is,'Cannot combine "switch" with "is"'),t(void 0===a.not,'Cannot combine "switch" with "not"'),t(void 0===a.then,'Cannot combine "switch" with "then"');const c={ref:e.ref(o),switch:[],break:a.break};for(let e=0;e<a.switch.length;++e){const i=a.switch[e],o=e===a.switch.length-1;r.assertOptions(i,o?["is","then","otherwise"]:["is","then"]),t(void 0!==i.is,'Switch statement missing "is"'),t(void 0!==i.then,'Switch statement missing "then"');const u={is:s.$_compile(i.is),then:s.$_compile(i.then)}
3527
- ;if(n.isRef(i.is)||r.isSchema(i.is)||(u.is=u.is.required()),o){t(void 0===a.otherwise||void 0===i.otherwise,'Cannot specify "otherwise" inside and outside a "switch"');const e=void 0!==a.otherwise?a.otherwise:i.otherwise;void 0!==e&&(t(void 0===c.break,"Cannot specify both otherwise and break"),u.otherwise=s.$_compile(e))}c.switch.push(u)}return c},i.condition=function(e,t){for(const r of["then","otherwise"])void 0===t[r]?delete t[r]:t[r]=e.$_compile(t[r]);return t}}(compile)),compile}var extend={},hasRequiredExtend;function requireExtend(){if(hasRequiredExtend)return extend;hasRequiredExtend=1;const{assert:e,clone:t}=requireLib$4(),r=requireCommon(),n=requireMessages(),i={};return extend.type=function(s,o){const a=Object.getPrototypeOf(s),c=t(a),u=s._assign(Object.create(c)),l=Object.assign({},o);delete l.base,c._definition=l;const d=a._definition||{};l.messages=n.merge(d.messages,l.messages),l.properties=Object.assign({},d.properties,l.properties),u.type=l.type,
3528
- l.flags=Object.assign({},d.flags,l.flags);const p=Object.assign({},d.terms);if(l.terms)for(const t in l.terms){const r=l.terms[t];e(void 0===u.$_terms[t],"Invalid term override for",l.type,t),u.$_terms[t]=r.init,p[t]=r}l.terms=p,l.args||(l.args=d.args),l.prepare=i.prepare(l.prepare,d.prepare),l.coerce&&("function"==typeof l.coerce&&(l.coerce={method:l.coerce}),l.coerce.from&&!Array.isArray(l.coerce.from)&&(l.coerce={method:l.coerce.method,from:[].concat(l.coerce.from)})),l.coerce=i.coerce(l.coerce,d.coerce),l.validate=i.validate(l.validate,d.validate);const h=Object.assign({},d.rules);if(l.rules)for(const t in l.rules){const n=l.rules[t];e("object"==typeof n,"Invalid rule definition for",l.type,t);let i=n.method;if(void 0===i&&(i=function(){return this.$_addRule(t)}),i&&(e(!c[t],"Rule conflict in",l.type,t),c[t]=i),e(!h[t],"Rule conflict in",l.type,t),h[t]=n,n.alias){const e=[].concat(n.alias);for(const t of e)c[t]=n.method}n.args&&(n.argsByName=new Map,
3529
- n.args=n.args.map(t=>("string"==typeof t&&(t={name:t}),e(!n.argsByName.has(t.name),"Duplicated argument name",t.name),r.isSchema(t.assert)&&(t.assert=t.assert.strict().label(t.name)),n.argsByName.set(t.name,t),t)))}l.rules=h;const A=Object.assign({},d.modifiers);if(l.modifiers)for(const t in l.modifiers){e(!c[t],"Rule conflict in",l.type,t);const r=l.modifiers[t];e("function"==typeof r,"Invalid modifier definition for",l.type,t);const n=function(e){return this.rule({[t]:e})};c[t]=n,A[t]=r}if(l.modifiers=A,l.overrides){c._super=a,u.$_super={};for(const t in l.overrides)e(a[t],"Cannot override missing",t),l.overrides[t][r.symbols.parent]=a[t],u.$_super[t]=a[t].bind(u);Object.assign(c,l.overrides)}l.cast=Object.assign({},d.cast,l.cast);const f=Object.assign({},d.manifest,l.manifest);return f.build=i.build(l.manifest&&l.manifest.build,d.manifest&&d.manifest.build),l.manifest=f,l.rebuild=i.rebuild(l.rebuild,d.rebuild),u},i.build=function(e,t){return e&&t?function(r,n){return t(e(r,n),n)
3530
- }:e||t},i.coerce=function(e,t){return e&&t?{from:e.from&&t.from?[...new Set([...e.from,...t.from])]:null,method(r,n){let i;if((!t.from||t.from.includes(typeof r))&&(i=t.method(r,n),i)){if(i.errors||void 0===i.value)return i;r=i.value}if(!e.from||e.from.includes(typeof r)){const t=e.method(r,n);if(t)return t}return i}}:e||t},i.prepare=function(e,t){return e&&t?function(r,n){const i=e(r,n);if(i){if(i.errors||void 0===i.value)return i;r=i.value}return t(r,n)||i}:e||t},i.rebuild=function(e,t){return e&&t?function(r){t(r),e(r)}:e||t},i.validate=function(e,t){return e&&t?function(r,n){const i=t(r,n);if(i){if(i.errors&&(!Array.isArray(i.errors)||i.errors.length))return i;r=i.value}return e(r,n)||i}:e||t},extend}var manifest={},hasRequiredManifest;function requireManifest(){if(hasRequiredManifest)return manifest;hasRequiredManifest=1;const{assert:e,clone:t}=requireLib$4(),r=requireCommon(),n=requireMessages(),i=requireRef$1(),s=requireTemplate();let o;const a={}
3531
- ;return manifest.describe=function(i){const s=i._definition,o={type:i.type,flags:{},rules:[]};for(const e in i._flags)"_"!==e[0]&&(o.flags[e]=a.describe(i._flags[e]));Object.keys(o.flags).length||delete o.flags,i._preferences&&(o.preferences=t(i._preferences,{shallow:["messages"]}),delete o.preferences[r.symbols.prefs],o.preferences.messages&&(o.preferences.messages=n.decompile(o.preferences.messages))),i._valids&&(o.allow=i._valids.describe()),i._invalids&&(o.invalid=i._invalids.describe());for(const e of i._rules){if(!1===s.rules[e.name].manifest)continue;const t={name:e.name};for(const r in s.modifiers)void 0!==e[r]&&(t[r]=a.describe(e[r]));if(e.args){t.args={};for(const r in e.args){const n=e.args[r];("options"!==r||Object.keys(n).length)&&(t.args[r]=a.describe(n,{assign:r}))}Object.keys(t.args).length||delete t.args}o.rules.push(t)}o.rules.length||delete o.rules;for(const t in i.$_terms){if("_"===t[0])continue;e(!o[t],"Cannot describe schema due to internal name conflict with",t)
3532
- ;const n=i.$_terms[t];if(!n)continue;if(n instanceof Map){n.size&&(o[t]=[...n.entries()]);continue}if(r.isValues(n)){o[t]=n.describe();continue}e(s.terms[t],"Term",t,"missing configuration");const c=s.terms[t].manifest,u="object"==typeof c;if(!n.length&&!u)continue;const l=[];for(const e of n)l.push(a.describe(e));if(u){const{from:e,to:r}=c.mapped;o[t]={};for(const n of l)o[t][n[r]]=n[e];continue}"single"!==c?o[t]=l:(e(1===l.length,"Term",t,"contains more than one item"),o[t]=l[0])}return a.validate(i.$_root,o),o},a.describe=function(e,n={}){if(Array.isArray(e))return e.map(a.describe);if(e===r.symbols.deepDefault)return{special:"deep"};if("object"!=typeof e||null===e)return e;if("options"===n.assign)return t(e);if(Buffer&&Buffer.isBuffer(e))return{buffer:e.toString("binary")};if(e instanceof Date)return e.toISOString();if(e instanceof Error)return e;if(e instanceof RegExp)return"regex"===n.assign?e.toString():{regex:e.toString()};if(e[r.symbols.literal])return{function:e.literal}
3533
- ;if("function"==typeof e.describe)return"ref"===n.assign?e.describe().ref:e.describe();const i={};for(const t in e){const r=e[t];void 0!==r&&(i[t]=a.describe(r,{assign:t}))}return i},manifest.build=function(e,t){return new a.Builder(e).parse(t)},a.Builder=class{constructor(e){this.joi=e}parse(t){a.validate(this.joi,t);let r=this.joi[t.type]()._bare();const n=r._definition;if(t.flags)for(const i in t.flags){const s=n.flags[i]&&n.flags[i].setter||i;e("function"==typeof r[s],"Invalid flag",i,"for type",t.type),r=r[s](this.build(t.flags[i]))}if(t.preferences&&(r=r.preferences(this.build(t.preferences))),t.allow&&(r=r.allow(...this.build(t.allow))),t.invalid&&(r=r.invalid(...this.build(t.invalid))),t.rules)for(const i of t.rules){e("function"==typeof r[i.name],"Invalid rule",i.name,"for type",t.type);const s=[];if(i.args){const r={};for(const e in i.args)r[e]=this.build(i.args[e],{assign:e});const o=Object.keys(r),a=n.rules[i.name].args;if(a){
3534
- e(o.length<=a.length,"Invalid number of arguments for",t.type,i.name,"(expected up to",a.length,", found",o.length,")");for(const{name:e}of a)s.push(r[e])}else e(1===o.length,"Invalid number of arguments for",t.type,i.name,"(expected up to 1, found",o.length,")"),s.push(r[o[0]])}r=r[i.name](...s);const o={};for(const e in n.modifiers)void 0!==i[e]&&(o[e]=this.build(i[e]));Object.keys(o).length&&(r=r.rule(o))}const i={};for(const r in t){if(["allow","flags","invalid","whens","preferences","rules","type"].includes(r))continue;e(n.terms[r],"Term",r,"missing configuration");const s=n.terms[r].manifest;if("schema"!==s)if("values"!==s)if("single"!==s)if("object"!=typeof s)i[r]=this.build(t[r]);else{i[r]={};for(const e in t[r]){const n=t[r][e];i[r][e]=this.parse(n)}}else i[r]=this.build(t[r]);else i[r]=t[r].map(e=>this.build(e));else i[r]=t[r].map(e=>this.parse(e))}return t.whens&&(i.whens=t.whens.map(e=>this.build(e))),r=n.manifest.build(r,i),r.$_temp.ruleset=!1,r}build(n,o={}){
3535
- if(null===n)return null;if(Array.isArray(n))return n.map(e=>this.build(e));if(n instanceof Error)return n;if("options"===o.assign)return t(n);if("regex"===o.assign)return a.regex(n);if("ref"===o.assign)return i.build(n);if("object"!=typeof n)return n;if(1===Object.keys(n).length){if(n.buffer)return e(Buffer,"Buffers are not supported"),Buffer&&Buffer.from(n.buffer,"binary");if(n.function)return{[r.symbols.literal]:!0,literal:n.function};if(n.override)return r.symbols.override;if(n.ref)return i.build(n.ref);if(n.regex)return a.regex(n.regex);if(n.special)return e(["deep"].includes(n.special),"Unknown special value",n.special),r.symbols.deepDefault;if(n.value)return t(n.value)}if(n.type)return this.parse(n);if(n.template)return s.build(n);const c={};for(const e in n)c[e]=this.build(n[e],{assign:e});return c}},a.regex=function(e){const t=e.lastIndexOf("/"),r=e.slice(1,t),n=e.slice(t+1);return new RegExp(r,n)},a.validate=function(e,t){o=o||requireSchemas(),e.assert(t,o.description)},
3536
- manifest}var trace={},lib$2={},hasRequiredLib$2,hasRequiredTrace;function requireLib$2(){return hasRequiredLib$2||(hasRequiredLib$2=1,lib$2.location=function(e=0){const t=Error.prepareStackTrace;Error.prepareStackTrace=(e,t)=>t;const r={};Error.captureStackTrace(r,this);const n=r.stack[e+1];return Error.prepareStackTrace=t,{filename:n.getFileName(),line:n.getLineNumber()}}),lib$2}function requireTrace(){if(hasRequiredTrace)return trace;hasRequiredTrace=1;const{deepEqual:e}=requireLib$4(),t=requireLib$2(),r=requireErrors$1(),n={codes:{error:1,pass:2,full:3},labels:{0:"never used",1:"always error",2:"always pass"}};return trace.setup=function(e){const t=function(){return e._tracer=e._tracer||new n.Tracer,e._tracer};e.trace=t,e[Symbol.for("@hapi/lab/coverage/initialize")]=t,e.untrace=()=>{e._tracer=null}},trace.location=function(e){return e.$_setFlag("_tracerLocation",t.location(2))},n.Tracer=class{constructor(){this.name="Joi",this._schemas=new Map}_register(e){
3537
- const r=this._schemas.get(e);if(r)return r.store;const i=new n.Store(e),{filename:s,line:o}=e._flags._tracerLocation||t.location(5);return this._schemas.set(e,{filename:s,line:o,store:i}),i}_combine(e,t){for(const{store:r}of this._schemas.values())r._combine(e,t)}report(e){const t=[];for(const{filename:r,line:i,store:s}of this._schemas.values()){if(e&&e!==r)continue;const o=[],a=[];for(const[e,t]of s._sources.entries()){if(n.sub(t.paths,a))continue;if(!t.entry){o.push({status:"never reached",paths:[...t.paths]}),a.push(...t.paths);continue}for(const r of["valid","invalid"]){const n=e[`_${r}s`];if(!n)continue;const i=new Set(n._values),s=new Set(n._refs);for(const{value:e,ref:n}of t[r])i.delete(e),s.delete(n);(i.size||s.size)&&o.push({status:[...i,...[...s].map(e=>e.display)],rule:`${r}s`})}const r=e._rules.map(e=>e.name);for(const t of["default","failover"])void 0!==e._flags[t]&&r.push(t);for(const e of r){const r=n.labels[t.rule[e]||0];if(r){const n={rule:e,status:r}
3538
- ;t.paths.size&&(n.paths=[...t.paths]),o.push(n)}}}o.length&&t.push({filename:r,line:i,missing:o,severity:"error",message:`Schema missing tests for ${o.map(n.message).join(", ")}`})}return t.length?t:null}},n.Store=class{constructor(e){this.active=!0,this._sources=new Map,this._combos=new Map,this._scan(e)}debug(e,t,r,n){e.mainstay.debug&&e.mainstay.debug.push({type:t,name:r,result:n,path:e.path})}entry(e,t){n.debug(t,{type:"entry"}),this._record(e,e=>{e.entry=!0})}filter(e,t,r,i){n.debug(t,{type:r,...i}),this._record(e,e=>{e[r].add(i)})}log(e,t,r,i,s){n.debug(t,{type:r,name:i,result:"full"===s?"pass":s}),this._record(e,e=>{e[r][i]=e[r][i]||0,e[r][i]|=n.codes[s]})}resolve(e,t,r){if(!e.mainstay.debug)return;const n={type:"resolve",ref:t.display,to:r,path:e.path};e.mainstay.debug.push(n)}value(t,r,n,i,s){if(!t.mainstay.debug||e(n,i))return;const o={type:"value",by:r,from:n,to:i,path:t.path};s&&(o.name=s),t.mainstay.debug.push(o)}_record(e,t){const r=this._sources.get(e)
3539
- ;if(r)return void t(r);const n=this._combos.get(e);for(const e of n)this._record(e,t)}_scan(e,t){const r=t||[];let i=this._sources.get(e);i||(i={paths:new Set,entry:!1,rule:{},valid:new Set,invalid:new Set},this._sources.set(e,i)),r.length&&i.paths.add(r);e.$_modify({each:(e,t)=>{const i=n.id(e,t);this._scan(e,r.concat(i))},ref:!1})}_combine(e,t){this._combos.set(e,t)}},n.message=function(e){return`${e.paths?r.path(e.paths[0])+(e.rule?":":""):""}${e.rule||""} (${e.status})`},n.id=function(e,{source:t,name:r,path:n,key:i}){return e._flags.id?e._flags.id:i||(r=`@${r}`,"terms"===t?[r,n[Math.min(n.length-1,1)]]:r)},n.sub=function(t,r){for(const n of t)for(const t of r)if(e(n.slice(0,t.length),t))return!0;return!1},n.debug=function(e,t){e.mainstay.debug&&(t.path=e.debug?[...e.path,e.debug]:e.path,e.mainstay.debug.push(t))},trace}var modify={},hasRequiredModify;function requireModify(){return hasRequiredModify||(hasRequiredModify=1,function(e){
3540
- const{assert:t}=requireLib$4(),r=requireCommon(),n=requireRef$1(),i={};e.Ids=i.Ids=class{constructor(){this._byId=new Map,this._byKey=new Map,this._schemaChain=!1}clone(){const e=new i.Ids;return e._byId=new Map(this._byId),e._byKey=new Map(this._byKey),e._schemaChain=this._schemaChain,e}concat(e){e._schemaChain&&(this._schemaChain=!0);for(const[r,n]of e._byId.entries())t(!this._byKey.has(r),"Schema id conflicts with existing key:",r),this._byId.set(r,n);for(const[r,n]of e._byKey.entries())t(!this._byId.has(r),"Schema key conflicts with existing id:",r),this._byKey.set(r,n)}fork(e,n,s){const o=this._collect(e);o.push({schema:s});const a=o.shift();let c={id:a.id,schema:n(a.schema)};t(r.isSchema(c.schema),"adjuster function failed to return a joi schema type");for(const e of o)c={id:e.id,schema:i.fork(e.schema,c.id,c.schema)};return c.schema}labels(e,t=[]){const r=e[0],n=this._get(r);if(!n)return[...t,...e].join(".");const i=e.slice(1);return t=[...t,n.schema._flags.label||r],
3541
- i.length?n.schema._ids.labels(i,t):t.join(".")}reach(e,r=[]){const n=e[0],i=this._get(n);t(i,"Schema does not contain path",[...r,...e].join("."));const s=e.slice(1);return s.length?i.schema._ids.reach(s,[...r,n]):i.schema}register(e,{key:n}={}){if(!e||!r.isSchema(e))return;(e.$_property("schemaChain")||e._ids._schemaChain)&&(this._schemaChain=!0);const i=e._flags.id;if(i){const r=this._byId.get(i);t(!r||r.schema===e,"Cannot add different schemas with the same id:",i),t(!this._byKey.has(i),"Schema id conflicts with existing key:",i),this._byId.set(i,{schema:e,id:i})}n&&(t(!this._byKey.has(n),"Schema already contains key:",n),t(!this._byId.has(n),"Schema key conflicts with existing id:",n),this._byKey.set(n,{schema:e,id:n}))}reset(){this._byId=new Map,this._byKey=new Map,this._schemaChain=!1}_collect(e,r=[],n=[]){const i=e[0],s=this._get(i);t(s,"Schema does not contain path",[...r,...e].join(".")),n=[s,...n];const o=e.slice(1);return o.length?s.schema._ids._collect(o,[...r,i],n):n}
3542
- _get(e){return this._byId.get(e)||this._byKey.get(e)}},i.fork=function(t,r,n){const i=e.schema(t,{each:(e,{key:t})=>{if(r===(e._flags.id||t))return n},ref:!1});return i?i.$_mutateRebuild():t},e.schema=function(e,t){let r;for(const n in e._flags){if("_"===n[0])continue;const s=i.scan(e._flags[n],{source:"flags",name:n},t);void 0!==s&&(r=r||e.clone(),r._flags[n]=s)}for(let n=0;n<e._rules.length;++n){const s=e._rules[n],o=i.scan(s.args,{source:"rules",name:s.name},t);if(void 0!==o){r=r||e.clone();const t=Object.assign({},s);t.args=o,r._rules[n]=t;r._singleRules.get(s.name)===s&&r._singleRules.set(s.name,t)}}for(const n in e.$_terms){if("_"===n[0])continue;const s=i.scan(e.$_terms[n],{source:"terms",name:n},t);void 0!==s&&(r=r||e.clone(),r.$_terms[n]=s)}return r},i.scan=function(e,t,s,o,a){const c=o||[];if(null===e||"object"!=typeof e)return;let u;if(Array.isArray(e)){for(let r=0;r<e.length;++r){const n="terms"===t.source&&"keys"===t.name&&e[r].key,o=i.scan(e[r],t,s,[r,...c],n)
3543
- ;void 0!==o&&(u=u||e.slice(),u[r]=o)}return u}if(!1!==s.schema&&r.isSchema(e)||!1!==s.ref&&n.isRef(e)){const r=s.each(e,{...t,path:c,key:a});if(r===e)return;return r}for(const r in e){if("_"===r[0])continue;const n=i.scan(e[r],t,s,[r,...c],a);void 0!==n&&(u=u||Object.assign({},e),u[r]=n)}return u}}(modify)),modify}var validator={},state$1,hasRequiredState$2,hasRequiredValidator,values,hasRequiredValues,base,hasRequiredBase,any,hasRequiredAny,alternatives,hasRequiredAlternatives,array,hasRequiredArray,boolean,hasRequiredBoolean,date,hasRequiredDate;function requireState$2(){if(hasRequiredState$2)return state$1;hasRequiredState$2=1;const{clone:e,reach:t}=requireLib$4(),r=requireCommon(),n={value:Symbol("value")};return state$1=n.State=class{constructor(e,t,r){this.path=e,this.ancestors=t,this.mainstay=r.mainstay,this.schemas=r.schemas,this.debug=null}localize(e,t=null,r=null){const i=new n.State(e,t,this);return r&&i.schemas&&(i.schemas=[n.schemas(r),...i.schemas]),i}nest(e,t){
3544
- const r=new n.State(this.path,this.ancestors,this);return r.schemas=r.schemas&&[n.schemas(e),...r.schemas],r.debug=t,r}shadow(e,t){this.mainstay.shadow=this.mainstay.shadow||new n.Shadow,this.mainstay.shadow.set(this.path,e,t)}snapshot(){this.mainstay.shadow&&(this._snapshot=e(this.mainstay.shadow.node(this.path))),this.mainstay.snapshot()}restore(){this.mainstay.shadow&&(this.mainstay.shadow.override(this.path,this._snapshot),this._snapshot=void 0),this.mainstay.restore()}commit(){this.mainstay.shadow&&(this.mainstay.shadow.override(this.path,this._snapshot),this._snapshot=void 0),this.mainstay.commit()}},n.schemas=function(e){return r.isSchema(e)?{schema:e}:e},n.Shadow=class{constructor(){this._values=null}set(e,t,r){if(!e.length)return;if("strip"===r&&"number"==typeof e[e.length-1])return;this._values=this._values||new Map;let i=this._values;for(let t=0;t<e.length;++t){const r=e[t];let n=i.get(r);n||(n=new Map,i.set(r,n)),i=n}i[n.value]=t}get(e){const t=this.node(e)
3545
- ;if(t)return t[n.value]}node(e){if(this._values)return t(this._values,e,{iterables:!0})}override(e,r){if(!this._values)return;const n=e.slice(0,-1),i=e[e.length-1],s=t(this._values,n,{iterables:!0});r?s.set(i,r):s&&s.delete(i)}},state$1}function requireValidator(){return hasRequiredValidator||(hasRequiredValidator=1,function(e){const{assert:t,clone:r,ignore:n,reach:i}=requireLib$4(),s=requireCommon(),o=requireErrors$1(),a=requireState$2(),c={result:Symbol("result")};e.entry=function(e,r,n){let i=s.defaults;n&&(t(void 0===n.warnings,"Cannot override warnings preference in synchronous validation"),t(void 0===n.artifacts,"Cannot override artifacts preference in synchronous validation"),i=s.preferences(s.defaults,n));const a=c.entry(e,r,i);t(!a.mainstay.externals.length,"Schema with external rules must use validateAsync()");const u={value:a.value};return a.error&&(u.error=a.error),a.mainstay.warnings.length&&(u.warning=o.details(a.mainstay.warnings)),
3546
- a.mainstay.debug&&(u.debug=a.mainstay.debug),a.mainstay.artifacts&&(u.artifacts=a.mainstay.artifacts),u},e.entryAsync=async function(e,t,r){let n=s.defaults;r&&(n=s.preferences(s.defaults,r));const a=c.entry(e,t,n),u=a.mainstay;if(a.error)throw u.debug&&(a.error.debug=u.debug),a.error;if(u.externals.length){let t=a.value;const l=[];for(const a of u.externals){const d=a.state.path,p="link"===a.schema.type?u.links.get(a.schema):null;let h,A,f=t;const g=d.length?[t]:[],m=d.length?i(e,d):e;if(d.length){h=d[d.length-1];let e=t;for(const t of d.slice(0,-1))e=e[t],g.unshift(e);A=g[0],f=A[h]}try{const e=(e,t)=>(p||a.schema).$_createError(e,f,t,a.state,n),i=await a.method(f,{schema:a.schema,linked:p,state:a.state,prefs:r,original:m,error:e,errorsArray:c.errorsArray,warn:(e,t)=>u.warnings.push((p||a.schema).$_createError(e,f,t,a.state,n)),message:(e,t)=>(p||a.schema).$_createError("external",f,t,a.state,n,{messages:e})});if(void 0===i||i===f)continue;if(i instanceof o.Report){
3547
- if(u.tracer.log(a.schema,a.state,"rule","external","error"),l.push(i),n.abortEarly)break;continue}if(Array.isArray(i)&&i[s.symbols.errors]){if(u.tracer.log(a.schema,a.state,"rule","external","error"),l.push(...i),n.abortEarly)break;continue}A?(u.tracer.value(a.state,"rule",f,i,"external"),A[h]=i):(u.tracer.value(a.state,"rule",t,i,"external"),t=i)}catch(e){throw n.errors.label&&(e.message+=` (${a.label})`),e}}if(a.value=t,l.length)throw a.error=o.process(l,e,n),u.debug&&(a.error.debug=u.debug),a.error}if(!n.warnings&&!n.debug&&!n.artifacts)return a.value;const l={value:a.value};return u.warnings.length&&(l.warning=o.details(u.warnings)),u.debug&&(l.debug=u.debug),u.artifacts&&(l.artifacts=u.artifacts),l},e.standard=function(t,r){return r.isAsync()?e.entryAsync(t,r):e.entry(t,r)},c.Mainstay=class{constructor(e,t,r){this.externals=[],this.warnings=[],this.tracer=e,this.debug=t,this.links=r,this.shadow=null,this.artifacts=null,this._snapshots=[]}snapshot(){this._snapshots.push({
3548
- externals:this.externals.slice(),warnings:this.warnings.slice()})}restore(){const e=this._snapshots.pop();this.externals=e.externals,this.warnings=e.warnings}commit(){this._snapshots.pop()}},c.entry=function(t,r,n){const{tracer:i,cleanup:s}=c.tracer(r,n),u=n.debug?[]:null,l=r._ids._schemaChain?new Map:null,d=new c.Mainstay(i,u,l),p=r._ids._schemaChain?[{schema:r}]:null,h=new a([],[],{mainstay:d,schemas:p}),A=e.validate(t,r,h,n);s&&r.$_root.untrace();const f=o.process(A.errors,t,n);return{value:A.value,error:f,mainstay:d}},c.tracer=function(e,r){return e.$_root._tracer?{tracer:e.$_root._tracer._register(e)}:r.debug?(t(e.$_root.trace,"Debug mode not supported"),{tracer:e.$_root.trace()._register(e),cleanup:!0}):{tracer:c.ignore}},e.validate=function(e,t,r,n,i={}){if(t.$_terms.whens&&(t=t._generate(e,r,n).schema),t._preferences&&(n=c.prefs(t,n)),t._cache&&n.cache){const n=t._cache.get(e);if(r.mainstay.tracer.debug(r,"validate","cached",!!n),n)return n}
3549
- const o=(i,s,o)=>t.$_createError(i,e,s,o||r,n),a={original:e,prefs:n,schema:t,state:r,error:o,errorsArray:c.errorsArray,warn:(e,t,n)=>r.mainstay.warnings.push(o(e,t,n)),message:(i,s)=>t.$_createError("custom",e,s,r,n,{messages:i})};r.mainstay.tracer.entry(t,r);const u=t._definition;if(u.prepare&&void 0!==e&&n.convert){const t=u.prepare(e,a);if(t){if(r.mainstay.tracer.value(r,"prepare",e,t.value),t.errors)return c.finalize(t.value,[].concat(t.errors),a);e=t.value}}if(u.coerce&&void 0!==e&&n.convert&&(!u.coerce.from||u.coerce.from.includes(typeof e))){const t=u.coerce.method(e,a);if(t){if(r.mainstay.tracer.value(r,"coerced",e,t.value),t.errors)return c.finalize(t.value,[].concat(t.errors),a);e=t.value}}const l=t._flags.empty;l&&l.$_match(c.trim(e,t),r.nest(l),s.defaults)&&(r.mainstay.tracer.value(r,"empty",e,void 0),e=void 0);const d=i.presence||t._flags.presence||(t._flags._endedSwitch?null:n.presence);if(void 0===e){if("forbidden"===d)return c.finalize(e,null,a)
3550
- ;if("required"===d)return c.finalize(e,[t.$_createError("any.required",e,null,r,n)],a);if("optional"===d){if(t._flags.default!==s.symbols.deepDefault)return c.finalize(e,null,a);r.mainstay.tracer.value(r,"default",e,{}),e={}}}else if("forbidden"===d)return c.finalize(e,[t.$_createError("any.unknown",e,null,r,n)],a);const p=[];if(t._valids){const i=t._valids.get(e,r,n,t._flags.insensitive);if(i)return n.convert&&(r.mainstay.tracer.value(r,"valids",e,i.value),e=i.value),r.mainstay.tracer.filter(t,r,"valid",i),c.finalize(e,null,a);if(t._flags.only){const i=t.$_createError("any.only",e,{valids:t._valids.values({display:!0})},r,n);if(n.abortEarly)return c.finalize(e,[i],a);p.push(i)}}if(t._invalids){const i=t._invalids.get(e,r,n,t._flags.insensitive);if(i){r.mainstay.tracer.filter(t,r,"invalid",i);const s=t.$_createError("any.invalid",e,{invalids:t._invalids.values({display:!0})},r,n);if(n.abortEarly)return c.finalize(e,[s],a);p.push(s)}}if(u.validate){const t=u.validate(e,a)
3551
- ;if(t&&(r.mainstay.tracer.value(r,"base",e,t.value),e=t.value,t.errors)){if(!Array.isArray(t.errors))return p.push(t.errors),c.finalize(e,p,a);if(t.errors.length)return p.push(...t.errors),c.finalize(e,p,a)}}return t._rules.length?c.rules(e,p,a):c.finalize(e,p,a)},c.rules=function(e,t,r){const{schema:n,state:i,prefs:o}=r;for(const a of n._rules){const u=n._definition.rules[a.method];if(u.convert&&o.convert){i.mainstay.tracer.log(n,i,"rule",a.name,"full");continue}let l,d=a.args;if(a._resolve.length){d=Object.assign({},d);for(const t of a._resolve){const r=u.argsByName.get(t),a=d[t].resolve(e,i,o),c=r.normalize?r.normalize(a):a,p=s.validateArg(c,null,r);if(p){l=n.$_createError("any.ref",a,{arg:t,ref:d[t],reason:p},i,o);break}d[t]=c}}l=l||u.validate(e,r,d,a);const p=c.rule(l,a);if(p.errors){if(i.mainstay.tracer.log(n,i,"rule",a.name,"error"),a.warn){i.mainstay.warnings.push(...p.errors);continue}if(o.abortEarly)return c.finalize(e,p.errors,r);t.push(...p.errors)
3552
- }else i.mainstay.tracer.log(n,i,"rule",a.name,"pass"),i.mainstay.tracer.value(i,"rule",e,p.value,a.name),e=p.value}return c.finalize(e,t,r)},c.rule=function(e,t){return e instanceof o.Report?(c.error(e,t),{errors:[e],value:null}):Array.isArray(e)&&e[s.symbols.errors]?(e.forEach(e=>c.error(e,t)),{errors:e,value:null}):{errors:null,value:e}},c.error=function(e,t){return t.message&&e._setTemplate(t.message),e},c.finalize=function(e,r,n){r=r||[];const{schema:i,state:s,prefs:a}=n;if(r.length){const t=c.default("failover",void 0,r,n);void 0!==t&&(s.mainstay.tracer.value(s,"failover",e,t),e=t,r=[])}if(r.length&&i._flags.error)if("function"==typeof i._flags.error){r=i._flags.error(r),Array.isArray(r)||(r=[r]);for(const e of r)t(e instanceof Error||e instanceof o.Report,"error() must return an Error object")}else r=[i._flags.error];if(void 0===e){const t=c.default("default",e,r,n);s.mainstay.tracer.value(s,"default",e,t),e=t}if(i._flags.cast&&void 0!==e){
3553
- const t=i._definition.cast[i._flags.cast];if(t.from(e)){const r=t.to(e,n);s.mainstay.tracer.value(s,"cast",e,r,i._flags.cast),e=r}}if(i.$_terms.externals&&a.externals&&!1!==a._externals)for(const{method:e}of i.$_terms.externals)s.mainstay.externals.push({method:e,schema:i,state:s,label:o.label(i._flags,s,a)});const u={value:e,errors:r.length?r:null};return i._flags.result&&(u.value="strip"===i._flags.result?void 0:n.original,s.mainstay.tracer.value(s,i._flags.result,e,u.value),s.shadow(e,i._flags.result)),i._cache&&!1!==a.cache&&!i._refs.length&&i._cache.set(n.original,u),void 0===e||u.errors||void 0===i._flags.artifact||(s.mainstay.artifacts=s.mainstay.artifacts||new Map,s.mainstay.artifacts.has(i._flags.artifact)||s.mainstay.artifacts.set(i._flags.artifact,[]),s.mainstay.artifacts.get(i._flags.artifact).push(s.path)),u},c.prefs=function(e,t){const r=t===s.defaults;return r&&e._preferences[s.symbols.prefs]?e._preferences[s.symbols.prefs]:(t=s.preferences(t,e._preferences),
3554
- r&&(e._preferences[s.symbols.prefs]=t),t)},c.default=function(e,t,n,i){const{schema:o,state:a,prefs:c}=i,u=o._flags[e];if(c.noDefaults||void 0===u)return t;if(a.mainstay.tracer.log(o,a,"rule",e,"full"),!u)return u;if("function"==typeof u){const t=u.length?[r(a.ancestors[0]),i]:[];try{return u(...t)}catch(t){return void n.push(o.$_createError(`any.${e}`,null,{error:t},a,c))}}return"object"!=typeof u?u:u[s.symbols.literal]?u.literal:s.isResolvable(u)?u.resolve(t,a,c):r(u)},c.trim=function(e,t){if("string"!=typeof e)return e;const r=t.$_getRule("trim");return r&&r.args.enabled?e.trim():e},c.ignore={active:!1,debug:n,entry:n,filter:n,log:n,resolve:n,value:n},c.errorsArray=function(){const e=[];return e[s.symbols.errors]=!0,e}}(validator)),validator}function requireValues(){if(hasRequiredValues)return values;hasRequiredValues=1;const{assert:e,deepEqual:t}=requireLib$4(),r=requireCommon(),n={};return values=n.Values=class{constructor(e,t){this._values=new Set(e),this._refs=new Set(t),
3555
- this._lowercase=n.lowercases(e),this._override=!1}get length(){return this._values.size+this._refs.size}add(e,t){r.isResolvable(e)?this._refs.has(e)||(this._refs.add(e),t&&t.register(e)):this.has(e,null,null,!1)||(this._values.add(e),"string"==typeof e&&this._lowercase.set(e.toLowerCase(),e))}static merge(e,t,r){if(e=e||new n.Values,t){if(t._override)return t.clone();for(const r of[...t._values,...t._refs])e.add(r)}if(r)for(const t of[...r._values,...r._refs])e.remove(t);return e.length?e:null}remove(e){r.isResolvable(e)?this._refs.delete(e):(this._values.delete(e),"string"==typeof e&&this._lowercase.delete(e.toLowerCase()))}has(e,t,r,n){return!!this.get(e,t,r,n)}get(e,r,n,i){if(!this.length)return!1;if(this._values.has(e))return{value:e};if("string"==typeof e&&e&&i){const t=this._lowercase.get(e.toLowerCase());if(t)return{value:t}}if(!this._refs.size&&"object"!=typeof e)return!1;if("object"==typeof e)for(const r of this._values)if(t(r,e))return{value:r}
3556
- ;if(r)for(const s of this._refs){const o=s.resolve(e,r,n,null,{in:!0});if(void 0===o)continue;const a=s.in&&"object"==typeof o?Array.isArray(o)?o:Object.keys(o):[o];for(const r of a)if(typeof r==typeof e)if(i&&e&&"string"==typeof e){if(r.toLowerCase()===e.toLowerCase())return{value:r,ref:s}}else if(t(r,e))return{value:r,ref:s}}return!1}override(){this._override=!0}values(e){if(e&&e.display){const e=[];for(const t of[...this._values,...this._refs])void 0!==t&&e.push(t);return e}return Array.from([...this._values,...this._refs])}clone(){const e=new n.Values(this._values,this._refs);return e._override=this._override,e}concat(t){e(!t._override,"Cannot concat override set of values");const r=new n.Values([...this._values,...t._values],[...this._refs,...t._refs]);return r._override=this._override,r}describe(){const e=[];this._override&&e.push({override:!0});for(const t of this._values.values())e.push(t&&"object"==typeof t?{value:t}:t);for(const t of this._refs.values())e.push(t.describe())
3557
- ;return e}},n.Values.prototype[r.symbols.values]=!0,n.Values.prototype.slice=n.Values.prototype.clone,n.lowercases=function(e){const t=new Map;if(e)for(const r of e)"string"==typeof r&&t.set(r.toLowerCase(),r);return t},values}function requireBase(){if(hasRequiredBase)return base;hasRequiredBase=1;const{assert:e,clone:t,deepEqual:r,merge:n}=requireLib$4(),i=requireCache(),s=requireCommon(),o=requireCompile(),a=requireErrors$1(),c=requireExtend(),u=requireManifest(),l=requireMessages(),d=requireModify(),p=requireRef$1(),h=requireTrace(),A=requireValidator(),f=requireValues(),g={Base:class{constructor(e){this.type=e,this.$_root=null,this._definition={},this._reset()}_reset(){this._ids=new d.Ids,this._preferences=null,this._refs=new p.Manager,this._cache=null,this._valids=null,this._invalids=null,this._flags={},this._rules=[],this._singleRules=new Map,this.$_terms={},this.$_temp={ruleset:null,whens:{}}}describe(){return e("function"==typeof u.describe,"Manifest functionality disabled"),
3558
- u.describe(this)}allow(...e){return s.verifyFlat(e,"allow"),this._values(e,"_valids")}alter(t){e(t&&"object"==typeof t&&!Array.isArray(t),"Invalid targets argument"),e(!this._inRuleset(),"Cannot set alterations inside a ruleset");const r=this.clone();r.$_terms.alterations=r.$_terms.alterations||[];for(const n in t){const i=t[n];e("function"==typeof i,"Alteration adjuster for",n,"must be a function"),r.$_terms.alterations.push({target:n,adjuster:i})}return r.$_temp.ruleset=!1,r}artifact(t){return e(void 0!==t,"Artifact cannot be undefined"),e(!this._cache,"Cannot set an artifact with a rule cache"),this.$_setFlag("artifact",t)}cast(t){return e(!1===t||"string"==typeof t,"Invalid to value"),e(!1===t||this._definition.cast[t],"Type",this.type,"does not support casting to",t),this.$_setFlag("cast",!1===t?void 0:t)}default(e,t){return this._default("default",e,t)}description(t){return e(t&&"string"==typeof t,"Description must be a non-empty string"),this.$_setFlag("description",t)}empty(e){
3559
- const t=this.clone();return void 0!==e&&(e=t.$_compile(e,{override:!1})),t.$_setFlag("empty",e,{clone:!1})}error(t){return e(t,"Missing error"),e(t instanceof Error||"function"==typeof t,"Must provide a valid Error object or a function"),this.$_setFlag("error",t)}example(t,r={}){return e(void 0!==t,"Missing example"),s.assertOptions(r,["override"]),this._inner("examples",t,{single:!0,override:r.override})}external(t,r){return"object"==typeof t&&(e(!r,"Cannot combine options with description"),r=t.description,t=t.method),e("function"==typeof t,"Method must be a function"),e(void 0===r||r&&"string"==typeof r,"Description must be a non-empty string"),this._inner("externals",{method:t,description:r},{single:!0})}failover(e,t){return this._default("failover",e,t)}forbidden(){return this.presence("forbidden")}id(t){return t?(e("string"==typeof t,"id must be a non-empty string"),e(/^[^\.]+$/.test(t),"id cannot contain period character"),this.$_setFlag("id",t)):this.$_setFlag("id",void 0)}
3560
- invalid(...e){return this._values(e,"_invalids")}label(t){return e(t&&"string"==typeof t,"Label name must be a non-empty string"),this.$_setFlag("label",t)}meta(t){return e(void 0!==t,"Meta cannot be undefined"),this._inner("metas",t,{single:!0})}note(...t){e(t.length,"Missing notes");for(const r of t)e(r&&"string"==typeof r,"Notes must be non-empty strings");return this._inner("notes",t)}only(t=!0){return e("boolean"==typeof t,"Invalid mode:",t),this.$_setFlag("only",t)}optional(){return this.presence("optional")}prefs(t){e(t,"Missing preferences"),e(void 0===t.context,"Cannot override context"),e(void 0===t.externals,"Cannot override externals"),e(void 0===t.warnings,"Cannot override warnings"),e(void 0===t.debug,"Cannot override debug"),s.checkPreferences(t);const r=this.clone();return r._preferences=s.preferences(r._preferences,t),r}presence(t){return e(["optional","required","forbidden"].includes(t),"Unknown presence mode",t),this.$_setFlag("presence",t)}raw(e=!0){
3561
- return this.$_setFlag("result",e?"raw":void 0)}result(t){return e(["raw","strip"].includes(t),"Unknown result mode",t),this.$_setFlag("result",t)}required(){return this.presence("required")}strict(e){const t=this.clone(),r=void 0!==e&&!e;return t._preferences=s.preferences(t._preferences,{convert:r}),t}strip(e=!0){return this.$_setFlag("result",e?"strip":void 0)}tag(...t){e(t.length,"Missing tags");for(const r of t)e(r&&"string"==typeof r,"Tags must be non-empty strings");return this._inner("tags",t)}unit(t){return e(t&&"string"==typeof t,"Unit name must be a non-empty string"),this.$_setFlag("unit",t)}valid(...e){s.verifyFlat(e,"valid");const t=this.allow(...e);return t.$_setFlag("only",!!t._valids,{clone:!1}),t}when(t,r){const n=this.clone();n.$_terms.whens||(n.$_terms.whens=[]);const i=o.when(n,t,r);if(!["any","link"].includes(n.type)){const t=i.is?[i]:i.switch;for(const r of t)e(!r.then||"any"===r.then.type||r.then.type===n.type,"Cannot combine",n.type,"with",r.then&&r.then.type),
3562
- e(!r.otherwise||"any"===r.otherwise.type||r.otherwise.type===n.type,"Cannot combine",n.type,"with",r.otherwise&&r.otherwise.type)}return n.$_terms.whens.push(i),n.$_mutateRebuild()}cache(t){e(!this._inRuleset(),"Cannot set caching inside a ruleset"),e(!this._cache,"Cannot override schema cache"),e(void 0===this._flags.artifact,"Cannot cache a rule with an artifact");const r=this.clone();return r._cache=t||i.provider.provision(),r.$_temp.ruleset=!1,r}clone(){const e=Object.create(Object.getPrototypeOf(this));return this._assign(e)}concat(t){e(s.isSchema(t),"Invalid schema object"),e("any"===this.type||"any"===t.type||t.type===this.type,"Cannot merge type",this.type,"with another type:",t.type),e(!this._inRuleset(),"Cannot concatenate onto a schema with open ruleset"),e(!t._inRuleset(),"Cannot concatenate a schema with open ruleset");let r=this.clone();if("any"===this.type&&"any"!==t.type){const e=t.clone();for(const t of Object.keys(r))"type"!==t&&(e[t]=r[t]);r=e}r._ids.concat(t._ids),
3563
- r._refs.register(t,p.toSibling),r._preferences=r._preferences?s.preferences(r._preferences,t._preferences):t._preferences,r._valids=f.merge(r._valids,t._valids,t._invalids),r._invalids=f.merge(r._invalids,t._invalids,t._valids);for(const e of t._singleRules.keys())r._singleRules.has(e)&&(r._rules=r._rules.filter(t=>t.keep||t.name!==e),r._singleRules.delete(e));for(const e of t._rules)t._definition.rules[e.method].multi||r._singleRules.set(e.name,e),r._rules.push(e);if(r._flags.empty&&t._flags.empty){r._flags.empty=r._flags.empty.concat(t._flags.empty);const e=Object.assign({},t._flags);delete e.empty,n(r._flags,e)}else if(t._flags.empty){r._flags.empty=t._flags.empty;const e=Object.assign({},t._flags);delete e.empty,n(r._flags,e)}else n(r._flags,t._flags);for(const e in t.$_terms){const n=t.$_terms[e];n?r.$_terms[e]?r.$_terms[e]=r.$_terms[e].concat(n):r.$_terms[e]=n.slice():r.$_terms[e]||(r.$_terms[e]=n)}return this.$_root._tracer&&this.$_root._tracer._combine(r,[this,t]),
3564
- r.$_mutateRebuild()}extend(t){return e(!t.base,"Cannot extend type with another base"),c.type(this,t)}extract(e){return e=Array.isArray(e)?e:e.split("."),this._ids.reach(e)}fork(t,r){e(!this._inRuleset(),"Cannot fork inside a ruleset");let n=this;for(let e of[].concat(t))e=Array.isArray(e)?e:e.split("."),n=n._ids.fork(e,r,n);return n.$_temp.ruleset=!1,n}isAsync(){if(Boolean(this.$_terms.externals?.length))return!0;if(this.$_terms.whens)for(const e of this.$_terms.whens){if(e.then?.isAsync())return!0;if(e.otherwise?.isAsync())return!0;if(e.switch)for(const t of e.switch){if(t.then?.isAsync())return!0;if(t.otherwise?.isAsync())return!0}}return!1}rule(r){const n=this._definition;s.assertOptions(r,Object.keys(n.modifiers)),e(!1!==this.$_temp.ruleset,"Cannot apply rules to empty ruleset or the last rule added does not support rule properties");const i=null===this.$_temp.ruleset?this._rules.length-1:this.$_temp.ruleset;e(i>=0&&i<this._rules.length,"Cannot apply rules to empty ruleset")
3565
- ;const o=this.clone();for(let s=i;s<o._rules.length;++s){const i=o._rules[s],a=t(i);for(const t in r)n.modifiers[t](a,r[t]),e(a.name===i.name,"Cannot change rule name");o._rules[s]=a,o._singleRules.get(a.name)===i&&o._singleRules.set(a.name,a)}return o.$_temp.ruleset=!1,o.$_mutateRebuild()}get ruleset(){e(!this._inRuleset(),"Cannot start a new ruleset without closing the previous one");const t=this.clone();return t.$_temp.ruleset=t._rules.length,t}get $(){return this.ruleset}tailor(t){t=[].concat(t),e(!this._inRuleset(),"Cannot tailor inside a ruleset");let r=this;if(this.$_terms.alterations)for(const{target:n,adjuster:i}of this.$_terms.alterations)t.includes(n)&&(r=i(r),e(s.isSchema(r),"Alteration adjuster for",n,"failed to return a schema object"));return r=r.$_modify({each:e=>e.tailor(t),ref:!1}),r.$_temp.ruleset=!1,r.$_mutateRebuild()}tracer(){return h.location?h.location(this):this}validate(e,t){return A.entry(e,this,t)}validateAsync(e,t){return A.entryAsync(e,this,t)}
3566
- $_addRule(t){"string"==typeof t&&(t={name:t}),e(t&&"object"==typeof t,"Invalid options"),e(t.name&&"string"==typeof t.name,"Invalid rule name");for(const r in t)e("_"!==r[0],"Cannot set private rule properties");const r=Object.assign({},t);r._resolve=[],r.method=r.method||r.name;const n=this._definition.rules[r.method],i=r.args;e(n,"Unknown rule",r.method);const o=this.clone();if(i){e(1===Object.keys(i).length||Object.keys(i).length===this._definition.rules[r.name].args.length,"Invalid rule definition for",this.type,r.name);for(const t in i){let a=i[t];if(n.argsByName){const c=n.argsByName.get(t);if(c.ref&&s.isResolvable(a))r._resolve.push(t),o.$_mutateRegister(a);else if(c.normalize&&(a=c.normalize(a),i[t]=a),c.assert){const r=s.validateArg(a,t,c);e(!r,r,"or reference")}}void 0!==a?i[t]=a:delete i[t]}}return n.multi||(o._ruleRemove(r.name,{clone:!1}),o._singleRules.set(r.name,r)),!1===o.$_temp.ruleset&&(o.$_temp.ruleset=null),n.priority?o._rules.unshift(r):o._rules.push(r),o}
3567
- $_compile(e,t){return o.schema(this.$_root,e,t)}$_createError(e,t,r,n,i,s={}){const o=!1!==s.flags?this._flags:{},c=s.messages?l.merge(this._definition.messages,s.messages):this._definition.messages;return new a.Report(e,t,r,o,c,n,i)}$_getFlag(e){return this._flags[e]}$_getRule(e){return this._singleRules.get(e)}$_mapLabels(e){return e=Array.isArray(e)?e:e.split("."),this._ids.labels(e)}$_match(e,t,r,n){(r=Object.assign({},r)).abortEarly=!0,r._externals=!1,t.snapshot();const i=!A.validate(e,this,t,r,n).errors;return t.restore(),i}$_modify(e){return s.assertOptions(e,["each","once","ref","schema"]),d.schema(this,e)||this}$_mutateRebuild(){e(!this._inRuleset(),"Cannot add this rule inside a ruleset"),this._refs.reset(),this._ids.reset();return this.$_modify({each:(e,{source:t,name:r,path:n,key:i})=>{const s=this._definition[t][r]&&this._definition[t][r].register;!1!==s&&this.$_mutateRegister(e,{family:s,key:i})}}),this._definition.rebuild&&this._definition.rebuild(this),
3568
- this.$_temp.ruleset=!1,this}$_mutateRegister(e,{family:t,key:r}={}){this._refs.register(e,t),this._ids.register(e,{key:r})}$_property(e){return this._definition.properties[e]}$_reach(e){return this._ids.reach(e)}$_rootReferences(){return this._refs.roots()}$_setFlag(t,n,i={}){e("_"===t[0]||!this._inRuleset(),"Cannot set flag inside a ruleset");const s=this._definition.flags[t]||{};if(r(n,s.default)&&(n=void 0),r(n,this._flags[t]))return this;const o=!1!==i.clone?this.clone():this;return void 0!==n?(o._flags[t]=n,o.$_mutateRegister(n)):delete o._flags[t],"_"!==t[0]&&(o.$_temp.ruleset=!1),o}$_parent(e,...t){return this[e][s.symbols.parent].call(this,...t)}$_validate(e,t,r){return A.validate(e,this,t,r)}_assign(e){e.type=this.type,e.$_root=this.$_root,e.$_temp=Object.assign({},this.$_temp),e.$_temp.whens={},e._ids=this._ids.clone(),e._preferences=this._preferences,e._valids=this._valids&&this._valids.clone(),e._invalids=this._invalids&&this._invalids.clone(),e._rules=this._rules.slice(),
3569
- e._singleRules=t(this._singleRules,{shallow:!0}),e._refs=this._refs.clone(),e._flags=Object.assign({},this._flags),e._cache=null,e.$_terms={};for(const t in this.$_terms)e.$_terms[t]=this.$_terms[t]?this.$_terms[t].slice():null;e.$_super={};for(const t in this.$_super)e.$_super[t]=this._super[t].bind(e);return e}_bare(){const e=this.clone();e._reset();const t=e._definition.terms;for(const r in t){const n=t[r];e.$_terms[r]=n.init}return e.$_mutateRebuild()}_default(t,r,n={}){s.assertOptions(n,"literal"),e(void 0!==r,"Missing",t,"value"),e("function"==typeof r||!n.literal,"Only function value supports literal option"),"function"==typeof r&&n.literal&&(r={[s.symbols.literal]:!0,literal:r});return this.$_setFlag(t,r)}_generate(e,t,r){if(!this.$_terms.whens)return{schema:this};const n=[],i=[];for(let s=0;s<this.$_terms.whens.length;++s){const o=this.$_terms.whens[s];if(o.concat){n.push(o.concat),i.push(`${s}.concat`);continue}
3570
- const a=o.ref?o.ref.resolve(e,t,r):e,c=o.is?[o]:o.switch,u=i.length;for(let u=0;u<c.length;++u){const{is:l,then:d,otherwise:p}=c[u],h=`${s}${o.switch?"."+u:""}`;if(l.$_match(a,t.nest(l,`${h}.is`),r)){if(d){const s=t.localize([...t.path,`${h}.then`],t.ancestors,t.schemas),{schema:o,id:a}=d._generate(e,s,r);n.push(o),i.push(`${h}.then${a?`(${a})`:""}`);break}}else if(p){const s=t.localize([...t.path,`${h}.otherwise`],t.ancestors,t.schemas),{schema:o,id:a}=p._generate(e,s,r);n.push(o),i.push(`${h}.otherwise${a?`(${a})`:""}`);break}}if(o.break&&i.length>u)break}const s=i.join(", ");if(t.mainstay.tracer.debug(t,"rule","when",s),!s)return{schema:this};if(!t.mainstay.tracer.active&&this.$_temp.whens[s])return{schema:this.$_temp.whens[s],id:s};let o=this;this._definition.generate&&(o=this._definition.generate(this,e,t,r));for(const e of n)o=o.concat(e);return this.$_root._tracer&&this.$_root._tracer._combine(o,[this,...n]),this.$_temp.whens[s]=o,{schema:o,id:s}}_inner(t,r,n={}){
3571
- e(!this._inRuleset(),`Cannot set ${t} inside a ruleset`);const i=this.clone();return i.$_terms[t]&&!n.override||(i.$_terms[t]=[]),n.single?i.$_terms[t].push(r):i.$_terms[t].push(...r),i.$_temp.ruleset=!1,i}_inRuleset(){return null!==this.$_temp.ruleset&&!1!==this.$_temp.ruleset}_ruleRemove(e,t={}){if(!this._singleRules.has(e))return this;const r=!1!==t.clone?this.clone():this;r._singleRules.delete(e);const n=[];for(let t=0;t<r._rules.length;++t){const i=r._rules[t];i.name!==e||i.keep?n.push(i):r._inRuleset()&&t<r.$_temp.ruleset&&--r.$_temp.ruleset}return r._rules=n,r}_values(t,r){s.verifyFlat(t,r.slice(1,-1));const n=this.clone(),i=t[0]===s.symbols.override;if(i&&(t=t.slice(1)),!n[r]&&t.length?n[r]=new f:i&&(n[r]=t.length?new f:null,n.$_mutateRebuild()),!n[r])return n;i&&n[r].override();for(const i of t){e(void 0!==i,"Cannot call allow/valid/invalid with undefined"),e(i!==s.symbols.override,"Override must be the first value");const t="_invalids"===r?"_valids":"_invalids"
3572
- ;n[t]&&(n[t].remove(i),n[t].length||(e("_valids"===r||!n._flags.only,"Setting invalid value",i,"leaves schema rejecting all values due to previous valid rule"),n[t]=null)),n[r].add(i,n._refs)}return n}get"~standard"(){const e=e=>{let t;return t=a.ValidationError.isError(e)?e.details.map(({message:e,path:t})=>({message:e,path:t})):[{message:e.message}],{issues:t}},t=e=>({value:e});return{version:1,vendor:"joi",validate:r=>{const n=A.standard(r,this);return n instanceof Promise?n.then(t,e):n.error?e(n.error):t(n.value)}}}}};return g.Base.prototype[s.symbols.any]={version:s.version,compile:o.compile,root:"$_root"},g.Base.prototype.isImmutable=!0,g.Base.prototype.deny=g.Base.prototype.invalid,g.Base.prototype.disallow=g.Base.prototype.invalid,g.Base.prototype.equal=g.Base.prototype.valid,g.Base.prototype.exist=g.Base.prototype.required,g.Base.prototype.not=g.Base.prototype.invalid,g.Base.prototype.options=g.Base.prototype.prefs,g.Base.prototype.preferences=g.Base.prototype.prefs,
3573
- base=new g.Base}function requireAny(){if(hasRequiredAny)return any;hasRequiredAny=1;const{assert:e}=requireLib$4(),t=requireBase(),r=requireCommon(),n=requireMessages();return any=t.extend({type:"any",flags:{only:{default:!1}},terms:{alterations:{init:null},examples:{init:null},externals:{init:null},metas:{init:[]},notes:{init:[]},shared:{init:null},tags:{init:[]},whens:{init:null}},rules:{custom:{method(t,r){return e("function"==typeof t,"Method must be a function"),e(void 0===r||r&&"string"==typeof r,"Description must be a non-empty string"),this.$_addRule({name:"custom",args:{method:t,description:r}})},validate(e,t,{method:r}){try{return r(e,t)}catch(e){return t.error("any.custom",{error:e})}},args:["method","description"],multi:!0},messages:{method(e){return this.prefs({messages:e})}},shared:{method(t){e(r.isSchema(t)&&t._flags.id,"Schema must be a schema with an id");const n=this.clone();return n.$_terms.shared=n.$_terms.shared||[],n.$_terms.shared.push(t),n.$_mutateRegister(t),n}
3574
- },warning:{method(t,r){return e(t&&"string"==typeof t,"Invalid warning code"),this.$_addRule({name:"warning",args:{code:t,local:r},warn:!0})},validate:(e,t,{code:r,local:n})=>t.error(r,n),args:["code","local"],multi:!0}},modifiers:{keep(e,t=!0){e.keep=t},message(e,t){e.message=n.compile(t)},warn(e,t=!0){e.warn=t}},manifest:{build(e,t){for(const r in t){const n=t[r];if(["examples","externals","metas","notes","tags"].includes(r))for(const t of n)e=e[r.slice(0,-1)](t);else{if("alterations"===r){const t={};for(const{target:e,adjuster:r}of n)t[e]=r;e=e.alter(t);continue}if("whens"!==r){if("shared"===r)for(const t of n)e=e.shared(t)}else for(const t of n){const{ref:r,is:n,not:i,then:s,otherwise:o,concat:a}=t;e=a?e.concat(a):r?e.when(r,{is:n,not:i,then:s,otherwise:o,switch:t.switch,break:t.break}):e.when(n,{then:s,otherwise:o,break:t.break})}}}return e}},messages:{"any.custom":"{{#label}} failed custom validation because {{#error.message}}",
3575
- "any.default":"{{#label}} threw an error when running default method","any.failover":"{{#label}} threw an error when running failover method","any.invalid":"{{#label}} contains an invalid value","any.only":'{{#label}} must be {if(#valids.length == 1, "", "one of ")}{{#valids}}',"any.ref":"{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}","any.required":"{{#label}} is required","any.unknown":"{{#label}} is not allowed"}}),any}function requireAlternatives(){if(hasRequiredAlternatives)return alternatives;hasRequiredAlternatives=1;const{assert:e,merge:t}=requireLib$4(),r=requireAny(),n=requireCommon(),i=requireCompile(),s=requireErrors$1(),o=requireRef$1(),a={};return alternatives=r.extend({type:"alternatives",flags:{match:{default:"any"}},terms:{matches:{init:[],register:o.toSibling}},args:(e,...t)=>1===t.length&&Array.isArray(t[0])?e.try(...t[0]):e.try(...t),validate(e,r){const{schema:n,error:i,state:o,prefs:c}=r;if(n._flags.match){const r=[],a=[]
3576
- ;for(let t=0;t<n.$_terms.matches.length;++t){const i=n.$_terms.matches[t],s=o.nest(i.schema,`match.${t}`);s.snapshot();const u=i.schema.$_validate(e,s,c);u.errors?(a.push(u.errors),s.restore()):(r.push(u.value),s.commit())}if(0===r.length){return{errors:i("alternatives.any",{details:a.map(e=>s.details(e,{override:!1}))})}}if("one"===n._flags.match)return 1===r.length?{value:r[0]}:{errors:i("alternatives.one")};if(r.length!==n.$_terms.matches.length){return{errors:i("alternatives.all",{details:a.map(e=>s.details(e,{override:!1}))})}}const u=e=>e.$_terms.matches.some(e=>"object"===e.schema.type||"alternatives"===e.schema.type&&u(e.schema));return u(n)?{value:r.reduce((e,r)=>t(e,r,{mergeArrays:!1}))}:{value:r[r.length-1]}}const u=[];for(let t=0;t<n.$_terms.matches.length;++t){const r=n.$_terms.matches[t];if(r.schema){const n=o.nest(r.schema,`match.${t}`);n.snapshot();const i=r.schema.$_validate(e,n,c);if(!i.errors)return n.commit(),i;n.restore(),u.push({schema:r.schema,reports:i.errors})
3577
- ;continue}const i=r.ref?r.ref.resolve(e,o,c):e,s=r.is?[r]:r.switch;for(let n=0;n<s.length;++n){const a=s[n],{is:u,then:l,otherwise:d}=a,p=`match.${t}${r.switch?"."+n:""}`;if(u.$_match(i,o.nest(u,`${p}.is`),c)){if(l)return l.$_validate(e,o.nest(l,`${p}.then`),c)}else if(d)return d.$_validate(e,o.nest(d,`${p}.otherwise`),c)}}return a.errors(u,r)},rules:{conditional:{method(t,r){e(!this._flags._endedSwitch,"Unreachable condition"),e(!this._flags.match,"Cannot combine match mode",this._flags.match,"with conditional rule"),e(void 0===r.break,"Cannot use break option with alternatives conditional");const n=this.clone(),s=i.when(n,t,r),o=s.is?[s]:s.switch;for(const e of o)if(e.then&&e.otherwise){n.$_setFlag("_endedSwitch",!0,{clone:!1});break}return n.$_terms.matches.push(s),n.$_mutateRebuild()}},match:{method(t){if(e(["any","one","all"].includes(t),"Invalid alternatives match mode",t),
3578
- "any"!==t)for(const r of this.$_terms.matches)e(r.schema,"Cannot combine match mode",t,"with conditional rules");return this.$_setFlag("match",t)}},try:{method(...t){e(t.length,"Missing alternative schemas"),n.verifyFlat(t,"try"),e(!this._flags._endedSwitch,"Unreachable condition");const r=this.clone();for(const e of t)r.$_terms.matches.push({schema:r.$_compile(e)});return r.$_mutateRebuild()}}},overrides:{label(e){return this.$_parent("label",e).$_modify({each:(t,r)=>"is"!==r.path[0]&&"string"!=typeof t._flags.label?t.label(e):void 0,ref:!1})},isAsync(){if(this.$_terms.externals?.length)return!0;for(const e of this.$_terms.matches){if(e.schema?.isAsync())return!0;if(e.then?.isAsync())return!0;if(e.otherwise?.isAsync())return!0}return!1}},rebuild(e){e.$_modify({each:t=>{n.isSchema(t)&&"array"===t.type&&e.$_setFlag("_arrayItems",!0,{clone:!1})}})},manifest:{build(e,t){if(t.matches)for(const r of t.matches){const{schema:t,ref:n,is:i,not:s,then:o,otherwise:a}=r
3579
- ;e=t?e.try(t):n?e.conditional(n,{is:i,then:o,not:s,otherwise:a,switch:r.switch}):e.conditional(i,{then:o,otherwise:a})}return e}},messages:{"alternatives.all":"{{#label}} does not match all of the required types","alternatives.any":"{{#label}} does not match any of the allowed types","alternatives.match":"{{#label}} does not match any of the allowed types","alternatives.one":"{{#label}} matches more than one allowed type","alternatives.types":"{{#label}} must be one of {{#types}}"}}),a.errors=function(e,{error:t,state:r}){if(!e.length)return{errors:t("alternatives.any")};if(1===e.length)return{errors:e[0].reports};const n=new Set,i=[];for(const{reports:o,schema:c}of e){if(o.length>1)return a.unmatched(e,t);const u=o[0];if(u instanceof s.Report==!1)return a.unmatched(e,t);if(u.state.path.length!==r.path.length){i.push({type:c.type,report:u});continue}if("any.only"===u.code){for(const e of u.local.valids)n.add(e);continue}const[l,d]=u.code.split(".");"base"!==d?i.push({type:c.type,
3580
- report:u}):"object.base"===u.code?n.add(u.local.type):n.add(l)}return i.length?1===i.length?{errors:i[0].report}:a.unmatched(e,t):{errors:t("alternatives.types",{types:[...n]})}},a.unmatched=function(e,t){const r=[];for(const t of e)r.push(...t.reports);return{errors:t("alternatives.match",s.details(r,{override:!1}))}},alternatives}function requireArray(){if(hasRequiredArray)return array;hasRequiredArray=1;const{assert:e,deepEqual:t,reach:r}=requireLib$4(),n=requireAny(),i=requireCommon(),s=requireCompile(),o={};return array=n.extend({type:"array",flags:{single:{default:!1},sparse:{default:!1}},terms:{items:{init:[],manifest:"schema"},ordered:{init:[],manifest:"schema"},_exclusions:{init:[]},_inclusions:{init:[]},_requireds:{init:[]}},coerce:{from:"object",method(e,{schema:t,state:r,prefs:n}){if(!Array.isArray(e))return;const i=t.$_getRule("sort");return i?o.sort(t,e,i.args.options,r,n):void 0}},validate(e,{schema:t,error:r}){if(!Array.isArray(e)){if(t._flags.single){const t=[e]
3581
- ;return t[i.symbols.arraySingle]=!0,{value:t}}return{errors:r("array.base")}}if(t.$_getRule("items")||t.$_terms.externals)return{value:e.slice()}},rules:{has:{method(e){e=this.$_compile(e,{appendPath:!0});const t=this.$_addRule({name:"has",args:{schema:e}});return t.$_mutateRegister(e),t},validate(e,{state:t,prefs:r,error:n},{schema:i}){const s=[e,...t.ancestors];for(let n=0;n<e.length;++n){const o=t.localize([...t.path,n],s,i);if(i.$_match(e[n],o,r))return e}const o=i._flags.label;return o?n("array.hasKnown",{patternLabel:o}):n("array.hasUnknown",null)},multi:!0},items:{method(...e){i.verifyFlat(e,"items");const t=this.$_addRule("items");for(let r=0;r<e.length;++r){const n=i.tryWithPath(()=>this.$_compile(e[r]),r,{append:!0});t.$_terms.items.push(n)}return t.$_mutateRebuild()},validate(e,{schema:t,error:r,state:n,prefs:s,errorsArray:a}){const c=t.$_terms._requireds.slice(),u=t.$_terms.ordered.slice(),l=[...t.$_terms._inclusions,...c],d=!e[i.symbols.arraySingle]
3582
- ;delete e[i.symbols.arraySingle];const p=a();let h=e.length;for(let i=0;i<h;++i){const a=e[i];let A=!1,f=!1;const g=d?i:new Number(i),m=[...n.path,g];if(!t._flags.sparse&&void 0===a){if(p.push(r("array.sparse",{key:g,path:m,pos:i,value:void 0},n.localize(m))),s.abortEarly)return p;u.shift();continue}const y=[e,...n.ancestors];for(const e of t.$_terms._exclusions)if(e.$_match(a,n.localize(m,y,e),s,{presence:"ignore"})){if(p.push(r("array.excludes",{pos:i,value:a},n.localize(m))),s.abortEarly)return p;A=!0,u.shift();break}if(A)continue;if(t.$_terms.ordered.length){if(u.length){const c=u.shift(),l=c.$_validate(a,n.localize(m,y,c),s);if(l.errors){if(p.push(...l.errors),s.abortEarly)return p}else if("strip"===c._flags.result)o.fastSplice(e,i),--i,--h;else{if(!t._flags.sparse&&void 0===l.value){if(p.push(r("array.sparse",{key:g,path:m,pos:i,value:void 0},n.localize(m))),s.abortEarly)return p;continue}e[i]=l.value}continue}if(!t.$_terms.items.length){if(p.push(r("array.orderedLength",{pos:i,
3583
- limit:t.$_terms.ordered.length})),s.abortEarly)return p;break}}const E=[];let b=c.length;for(let u=0;u<b;++u){const l=n.localize(m,y,c[u]);l.snapshot();const d=c[u].$_validate(a,l,s);if(E[u]=d,!d.errors){if(l.commit(),e[i]=d.value,f=!0,o.fastSplice(c,u),--u,--b,!t._flags.sparse&&void 0===d.value&&(p.push(r("array.sparse",{key:g,path:m,pos:i,value:void 0},n.localize(m))),s.abortEarly))return p;break}l.restore()}if(f)continue;const C=s.stripUnknown&&!!s.stripUnknown.arrays||!1;b=l.length;for(const u of l){let l;const d=c.indexOf(u);if(-1!==d)l=E[d];else{const c=n.localize(m,y,u);if(c.snapshot(),l=u.$_validate(a,c,s),!l.errors){c.commit(),"strip"===u._flags.result?(o.fastSplice(e,i),--i,--h):t._flags.sparse||void 0!==l.value?e[i]=l.value:(p.push(r("array.sparse",{key:g,path:m,pos:i,value:void 0},n.localize(m))),A=!0),f=!0;break}c.restore()}if(1===b){if(C){o.fastSplice(e,i),--i,--h,f=!0;break}if(p.push(...l.errors),s.abortEarly)return p;A=!0;break}}
3584
- if(!A&&((t.$_terms._inclusions.length||t.$_terms._requireds.length)&&!f)){if(C){o.fastSplice(e,i),--i,--h;continue}if(p.push(r("array.includes",{pos:i,value:a},n.localize(m))),s.abortEarly)return p}}return c.length&&o.fillMissedErrors(t,p,c,e,n,s),u.length&&(o.fillOrderedErrors(t,p,u,e,n,s),p.length||o.fillDefault(u,e,n,s)),p.length?p:e},priority:!0,manifest:!1},length:{method(e){return this.$_addRule({name:"length",args:{limit:e},operator:"="})},validate:(e,t,{limit:r},{name:n,operator:s,args:o})=>i.compare(e.length,r,s)?e:t.error("array."+n,{limit:o.limit,value:e}),args:[{name:"limit",ref:!0,assert:i.limit,message:"must be a positive integer"}]},max:{method(e){return this.$_addRule({name:"max",method:"length",args:{limit:e},operator:"<="})}},min:{method(e){return this.$_addRule({name:"min",method:"length",args:{limit:e},operator:">="})}},ordered:{method(...e){i.verifyFlat(e,"ordered");const t=this.$_addRule("items");for(let r=0;r<e.length;++r){
3585
- const n=i.tryWithPath(()=>this.$_compile(e[r]),r,{append:!0});o.validateSingle(n,t),t.$_mutateRegister(n),t.$_terms.ordered.push(n)}return t.$_mutateRebuild()}},single:{method(t){const r=void 0===t||!!t;return e(!r||!this._flags._arrayItems,"Cannot specify single rule when array has array items"),this.$_setFlag("single",r)}},sort:{method(t={}){i.assertOptions(t,["by","order"]);const r={order:t.order||"ascending"};return t.by&&(r.by=s.ref(t.by,{ancestor:0}),e(!r.by.ancestor,"Cannot sort by ancestor")),this.$_addRule({name:"sort",args:{options:r}})},validate(e,{error:t,state:r,prefs:n,schema:i},{options:s}){const{value:a,errors:c}=o.sort(i,e,s,r,n);if(c)return c;for(let r=0;r<e.length;++r)if(e[r]!==a[r])return t("array.sort",{order:s.order,by:s.by?s.by.key:"value"});return e},convert:!0},sparse:{method(e){const t=void 0===e||!!e;if(this._flags.sparse===t)return this;return(t?this.clone():this.$_addRule("items")).$_setFlag("sparse",t,{clone:!1})}},unique:{method(t,r={}){
3586
- e(!t||"function"==typeof t||"string"==typeof t,"comparator must be a function or a string"),i.assertOptions(r,["ignoreUndefined","separator"]);const n={name:"unique",args:{options:r,comparator:t}};if(t)if("string"==typeof t){const e=i.default(r.separator,".");n.path=e?t.split(e):[t]}else n.comparator=t;return this.$_addRule(n)},validate(n,{state:i,error:s,schema:o},{comparator:a,options:c},{comparator:u,path:l}){const d={string:Object.create(null),number:Object.create(null),undefined:Object.create(null),boolean:Object.create(null),bigint:Object.create(null),object:new Map,function:new Map,custom:new Map},p=u||t,h=c.ignoreUndefined;for(let t=0;t<n.length;++t){const o=l?r(n[t],l):n[t],c=u?d.custom:d[typeof o];if(e(c,"Failed to find unique map container for type",typeof o),c instanceof Map){const e=c.entries();let r;for(;!(r=e.next()).done;)if(p(r.value[0],o)){const e=i.localize([...i.path,t],[n,...i.ancestors]),o={pos:t,value:n[t],dupePos:r.value[1],dupeValue:n[r.value[1]]}
3587
- ;return l&&(o.path=a),s("array.unique",o,e)}c.set(o,t)}else{if((!h||void 0!==o)&&void 0!==c[o]){const e={pos:t,value:n[t],dupePos:c[o],dupeValue:n[c[o]]};l&&(e.path=a);return s("array.unique",e,i.localize([...i.path,t],[n,...i.ancestors]))}c[o]=t}}return n},args:["comparator","options"],multi:!0}},overrides:{isAsync(){if(this.$_terms.externals?.length)return!0;for(const e of this.$_terms.items)if(e.isAsync())return!0;for(const e of this.$_terms.ordered)if(e.isAsync())return!0;return!1}},cast:{set:{from:Array.isArray,to:(e,t)=>new Set(e)}},rebuild(e){e.$_terms._inclusions=[],e.$_terms._exclusions=[],e.$_terms._requireds=[];for(const t of e.$_terms.items)o.validateSingle(t,e),"required"===t._flags.presence?e.$_terms._requireds.push(t):"forbidden"===t._flags.presence?e.$_terms._exclusions.push(t):e.$_terms._inclusions.push(t);for(const t of e.$_terms.ordered)o.validateSingle(t,e)},manifest:{build:(e,t)=>(t.items&&(e=e.items(...t.items)),t.ordered&&(e=e.ordered(...t.ordered)),e)},
3588
- messages:{"array.base":"{{#label}} must be an array","array.excludes":"{{#label}} contains an excluded value","array.hasKnown":"{{#label}} does not contain at least one required match for type {:#patternLabel}","array.hasUnknown":"{{#label}} does not contain at least one required match","array.includes":"{{#label}} does not match any of the allowed types","array.includesRequiredBoth":"{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)","array.includesRequiredKnowns":"{{#label}} does not contain {{#knownMisses}}","array.includesRequiredUnknowns":"{{#label}} does not contain {{#unknownMisses}} required value(s)","array.length":"{{#label}} must contain {{#limit}} items","array.max":"{{#label}} must contain less than or equal to {{#limit}} items","array.min":"{{#label}} must contain at least {{#limit}} items","array.orderedLength":"{{#label}} must contain at most {{#limit}} items",
3589
- "array.sort":"{{#label}} must be sorted in {#order} order by {{#by}}","array.sort.mismatching":"{{#label}} cannot be sorted due to mismatching types","array.sort.unsupported":"{{#label}} cannot be sorted due to unsupported type {#type}","array.sparse":"{{#label}} must not be a sparse array item","array.unique":"{{#label}} contains a duplicate value"}}),o.fillMissedErrors=function(e,t,r,n,i,s){const o=[];let a=0;for(const e of r){const t=e._flags.label;t?o.push(t):++a}o.length?a?t.push(e.$_createError("array.includesRequiredBoth",n,{knownMisses:o,unknownMisses:a},i,s)):t.push(e.$_createError("array.includesRequiredKnowns",n,{knownMisses:o},i,s)):t.push(e.$_createError("array.includesRequiredUnknowns",n,{unknownMisses:a},i,s))},o.fillOrderedErrors=function(e,t,r,n,i,s){const a=[];for(const e of r)"required"===e._flags.presence&&a.push(e);a.length&&o.fillMissedErrors(e,t,a,n,i,s)},o.fillDefault=function(e,t,r,n){const i=[];let s=!0;for(let o=e.length-1;o>=0;--o){
3590
- const a=e[o],c=[t,...r.ancestors],u=a.$_validate(void 0,r.localize(r.path,c,a),n).value;if(s){if(void 0===u)continue;s=!1}i.unshift(u)}i.length&&t.push(...i)},o.fastSplice=function(e,t){let r=t;for(;r<e.length;)e[r++]=e[r];--e.length},o.validateSingle=function(t,r){("array"===t.type||t._flags._arrayItems)&&(e(!r._flags.single,"Cannot specify array item with single rule enabled"),r.$_setFlag("_arrayItems",!0,{clone:!1}))},o.sort=function(e,t,r,n,i){const s="ascending"===r.order?1:-1,a=-1*s,c=s,u=(u,l)=>{let d=o.compare(u,l,a,c);if(null!==d)return d;if(r.by&&(u=r.by.resolve(u,n,i),l=r.by.resolve(l,n,i)),d=o.compare(u,l,a,c),null!==d)return d;const p=typeof u;if(p!==typeof l)throw e.$_createError("array.sort.mismatching",t,null,n,i);if("number"!==p&&"string"!==p)throw e.$_createError("array.sort.unsupported",t,{type:p},n,i);return"number"===p?(u-l)*s:u<l?a:c};try{return{value:t.slice().sort(u)}}catch(e){return{errors:e}}},o.compare=function(e,t,r,n){
3591
- return e===t?0:void 0===e?1:void 0===t?-1:null===e?n:null===t?r:null},array}function requireBoolean(){if(hasRequiredBoolean)return boolean;hasRequiredBoolean=1;const{assert:e}=requireLib$4(),t=requireAny(),r=requireCommon(),n=requireValues(),i={isBool:function(e){return"boolean"==typeof e}};return boolean=t.extend({type:"boolean",flags:{sensitive:{default:!1}},terms:{falsy:{init:null,manifest:"values"},truthy:{init:null,manifest:"values"}},coerce(e,{schema:t}){if("boolean"!=typeof e){if("string"==typeof e){const r=t._flags.sensitive?e:e.toLowerCase();e="true"===r||"false"!==r&&e}return"boolean"!=typeof e&&(e=t.$_terms.truthy&&t.$_terms.truthy.has(e,null,null,!t._flags.sensitive)||(!t.$_terms.falsy||!t.$_terms.falsy.has(e,null,null,!t._flags.sensitive))&&e),{value:e}}},validate(e,{error:t}){if("boolean"!=typeof e)return{value:e,errors:t("boolean.base")}},rules:{truthy:{method(...t){r.verifyFlat(t,"truthy");const i=this.clone();i.$_terms.truthy=i.$_terms.truthy||new n
3592
- ;for(let r=0;r<t.length;++r){const n=t[r];e(void 0!==n,"Cannot call truthy with undefined"),i.$_terms.truthy.add(n)}return i}},falsy:{method(...t){r.verifyFlat(t,"falsy");const i=this.clone();i.$_terms.falsy=i.$_terms.falsy||new n;for(let r=0;r<t.length;++r){const n=t[r];e(void 0!==n,"Cannot call falsy with undefined"),i.$_terms.falsy.add(n)}return i}},sensitive:{method(e=!0){return this.$_setFlag("sensitive",e)}}},cast:{number:{from:i.isBool,to:(e,t)=>e?1:0},string:{from:i.isBool,to:(e,t)=>e?"true":"false"}},manifest:{build:(e,t)=>(t.truthy&&(e=e.truthy(...t.truthy)),t.falsy&&(e=e.falsy(...t.falsy)),e)},messages:{"boolean.base":"{{#label}} must be a boolean"}}),boolean}function requireDate(){if(hasRequiredDate)return date;hasRequiredDate=1;const{assert:e}=requireLib$4(),t=requireAny(),r=requireCommon(),n=requireTemplate(),i={isDate:function(e){return e instanceof Date}};return date=t.extend({type:"date",coerce:{from:["number","string"],method:(e,{schema:t})=>({
3593
- value:i.parse(e,t._flags.format)||e})},validate(e,{schema:t,error:r,prefs:n}){if(e instanceof Date&&!isNaN(e.getTime()))return;const i=t._flags.format;return n.convert&&i&&"string"==typeof e?{value:e,errors:r("date.format",{format:i})}:{value:e,errors:r("date.base")}},rules:{compare:{method:!1,validate(e,t,{date:n},{name:i,operator:s,args:o}){const a="now"===n?Date.now():n.getTime();return r.compare(e.getTime(),a,s)?e:t.error("date."+i,{limit:o.date,value:e})},args:[{name:"date",ref:!0,normalize:e=>"now"===e?e:i.parse(e),assert:e=>null!==e,message:"must have a valid date format"}]},format:{method(t){return e(["iso","javascript","unix"].includes(t),"Unknown date format",t),this.$_setFlag("format",t)}},greater:{method(e){return this.$_addRule({name:"greater",method:"compare",args:{date:e},operator:">"})}},iso:{method(){return this.format("iso")}},less:{method(e){return this.$_addRule({name:"less",method:"compare",args:{date:e},operator:"<"})}},max:{method(e){return this.$_addRule({
3594
- name:"max",method:"compare",args:{date:e},operator:"<="})}},min:{method(e){return this.$_addRule({name:"min",method:"compare",args:{date:e},operator:">="})}},timestamp:{method(t="javascript"){return e(["javascript","unix"].includes(t),'"type" must be one of "javascript, unix"'),this.format(t)}}},cast:{number:{from:i.isDate,to:(e,t)=>e.getTime()},string:{from:i.isDate,to:(e,{prefs:t})=>n.date(e,t)}},messages:{"date.base":"{{#label}} must be a valid date","date.format":'{{#label}} must be in {msg("date.format." + #format) || #format} format',"date.greater":"{{#label}} must be greater than {{:#limit}}","date.less":"{{#label}} must be less than {{:#limit}}","date.max":"{{#label}} must be less than or equal to {{:#limit}}","date.min":"{{#label}} must be greater than or equal to {{:#limit}}","date.format.iso":"ISO 8601 date","date.format.javascript":"timestamp or number of milliseconds","date.format.unix":"timestamp or number of seconds"}}),i.parse=function(e,t){if(e instanceof Date)return e
3595
- ;if("string"!=typeof e&&(isNaN(e)||!isFinite(e)))return null;if(/^\s*$/.test(e))return null;if("iso"===t)return r.isIsoDate(e)?i.date(e.toString()):null;const n=e;if("string"==typeof e&&/^[+-]?\d+(\.\d+)?$/.test(e)&&(e=parseFloat(e)),t){if("javascript"===t)return i.date(1*e);if("unix"===t)return i.date(1e3*e);if("string"==typeof n)return null}return i.date(e)},i.date=function(e){const t=new Date(e);return isNaN(t.getTime())?null:t},date}var lib$1={},hasRequiredLib$1,keys,hasRequiredKeys,_function,hasRequired_function,link,hasRequiredLink,number,hasRequiredNumber,object,hasRequiredObject;function requireLib$1(){if(hasRequiredLib$1)return lib$1;hasRequiredLib$1=1;const{assert:e}=requireLib$4(),t={};return lib$1.Sorter=class{constructor(){this._items=[],this.nodes=[]}add(t,r){const n=[].concat((r=r??{}).before??[]),i=[].concat(r.after??[]),s=r.group??"?",o=r.sort??0;e(!n.includes(s),`Item cannot come before itself: ${s}`),e(!n.includes("?"),"Item cannot come before unassociated items"),
3596
- e(!i.includes(s),`Item cannot come after itself: ${s}`),e(!i.includes("?"),"Item cannot come after unassociated items"),Array.isArray(t)||(t=[t]);for(const e of t){const t={seq:this._items.length,sort:o,before:n,after:i,group:s,node:e};this._items.push(t)}if(!r.manual){const t=this._sort();e(t,"item","?"!==s?`added into group ${s}`:"","created a dependencies error")}return this.nodes}merge(r){Array.isArray(r)||(r=[r]);for(const e of r)if(e)for(const t of e._items)this._items.push(Object.assign({},t));this._items.sort(t.mergeSort);for(let e=0;e<this._items.length;++e)this._items[e].seq=e;const n=this._sort();return e(n,"merge created a dependencies error"),this.nodes}sort(){const t=this._sort();return e(t,"sort created a dependencies error"),this.nodes}_sort(){const e={},t=Object.create(null),r=Object.create(null);for(const n of this._items){const i=n.seq,s=n.group;r[s]=r[s]??[],r[s].push(i),e[i]=n.before;for(const e of n.after)t[e]=t[e]??[],t[e].push(i)}for(const t in e){const n=[]
3597
- ;for(const i in e[t]){const s=e[t][i];r[s]=r[s]??[],n.push(...r[s])}e[t]=n}for(const n in t)if(r[n])for(const i of r[n])e[i].push(...t[n]);const n={};for(const t in e){const r=e[t];for(const e of r)n[e]=n[e]??[],n[e].push(t)}const i={},s=[];for(let e=0;e<this._items.length;++e){let t=e;if(n[e]){t=null;for(let e=0;e<this._items.length;++e){if(!0===i[e])continue;n[e]||(n[e]=[]);const r=n[e].length;let s=0;for(let t=0;t<r;++t)i[n[e][t]]&&++s;if(s===r){t=e;break}}}null!==t&&(i[t]=!0,s.push(t))}if(s.length!==this._items.length)return!1;const o={};for(const e of this._items)o[e.seq]=e;this._items=[],this.nodes=[];for(const e of s){const t=o[e];this.nodes.push(t.node),this._items.push(t)}return!0}},t.mergeSort=(e,t)=>e.sort===t.sort?0:e.sort<t.sort?-1:1,lib$1}function requireKeys(){if(hasRequiredKeys)return keys;hasRequiredKeys=1
3598
- ;const{applyToDefaults:e,assert:t,clone:r}=requireLib$4(),n=requireLib$1(),i=requireAny(),s=requireCommon(),o=requireCompile(),a=requireErrors$1(),c=requireRef$1(),u=requireTemplate(),l={renameDefaults:{alias:!1,multiple:!1,override:!1}};return keys=i.extend({type:"_keys",properties:{typeof:"object"},flags:{unknown:{default:void 0}},terms:{dependencies:{init:null},keys:{init:null,manifest:{mapped:{from:"schema",to:"key"}}},patterns:{init:null},renames:{init:null}},args:(e,t)=>e.keys(t),validate(e,{schema:t,error:r,state:n,prefs:i}){if(!e||typeof e!==t.$_property("typeof")||Array.isArray(e))return{value:e,errors:r("object.base",{type:t.$_property("typeof")})};if(!(t.$_terms.renames||t.$_terms.dependencies||t.$_terms.keys||t.$_terms.patterns||t.$_terms.externals))return;e=l.clone(e,i);const s=[];if(t.$_terms.renames&&!l.rename(t,e,n,i,s))return{value:e,errors:s};if(!t.$_terms.keys&&!t.$_terms.patterns&&!t.$_terms.dependencies)return{value:e,errors:s};const o=new Set(Object.keys(e))
3599
- ;if(t.$_terms.keys){const r=[e,...n.ancestors];for(const a of t.$_terms.keys){const t=a.key,c=e[t];o.delete(t);const u=n.localize([...n.path,t],r,a),l=a.schema.$_validate(c,u,i);if(l.errors){if(i.abortEarly)return{value:e,errors:l.errors};void 0!==l.value&&(e[t]=l.value),s.push(...l.errors)}else"strip"===a.schema._flags.result||void 0===l.value&&void 0!==c?delete e[t]:void 0!==l.value&&(e[t]=l.value)}}if(o.size||t._flags._hasPatternMatch){const r=l.unknown(t,e,o,s,n,i);if(r)return r}if(t.$_terms.dependencies)for(const r of t.$_terms.dependencies){if(null!==r.key&&!1===l.isPresent(r.options)(r.key.resolve(e,n,i,null,{shadow:!1})))continue;const o=l.dependencies[r.rel](t,r,e,n,i);if(o){const r=t.$_createError(o.code,e,o.context,n,i);if(i.abortEarly)return{value:e,errors:r};s.push(r)}}return{value:e,errors:s}},rules:{and:{method(...e){return s.verifyFlat(e,"and"),l.dependency(this,"and",null,e)}},append:{method(e){return null==e||0===Object.keys(e).length?this:this.keys(e)}},assert:{
3600
- method(e,r,n){u.isTemplate(e)||(e=o.ref(e)),t(void 0===n||"string"==typeof n,"Message must be a string"),r=this.$_compile(r,{appendPath:!0});const i=this.$_addRule({name:"assert",args:{subject:e,schema:r,message:n}});return i.$_mutateRegister(e),i.$_mutateRegister(r),i},validate(e,{error:t,prefs:r,state:n},{subject:i,schema:s,message:o}){const a=i.resolve(e,n,r),u=c.isRef(i)?i.absolute(n):[];return s.$_match(a,n.localize(u,[e,...n.ancestors],s),r)?e:t("object.assert",{subject:i,message:o})},args:["subject","schema","message"],multi:!0},instance:{method(e,r){return t("function"==typeof e,"constructor must be a function"),r=r||e.name,this.$_addRule({name:"instance",args:{constructor:e,name:r}})},validate:(e,t,{constructor:r,name:n})=>e instanceof r?e:t.error("object.instance",{type:n,value:e}),args:["constructor","name"]},keys:{method(e){t(void 0===e||"object"==typeof e,"Object schema must be a valid object"),t(!s.isSchema(e),"Object schema cannot be a joi schema");const r=this.clone()
3601
- ;if(e)if(Object.keys(e).length){r.$_terms.keys=r.$_terms.keys?r.$_terms.keys.filter(t=>!e.hasOwnProperty(t.key)):new l.Keys;for(const t in e)s.tryWithPath(()=>r.$_terms.keys.push({key:t,schema:this.$_compile(e[t])}),t)}else r.$_terms.keys=new l.Keys;else r.$_terms.keys=null;return r.$_mutateRebuild()}},length:{method(e){return this.$_addRule({name:"length",args:{limit:e},operator:"="})},validate:(e,t,{limit:r},{name:n,operator:i,args:o})=>s.compare(Object.keys(e).length,r,i)?e:t.error("object."+n,{limit:o.limit,value:e}),args:[{name:"limit",ref:!0,assert:s.limit,message:"must be a positive integer"}]},max:{method(e){return this.$_addRule({name:"max",method:"length",args:{limit:e},operator:"<="})}},min:{method(e){return this.$_addRule({name:"min",method:"length",args:{limit:e},operator:">="})}},nand:{method(...e){return s.verifyFlat(e,"nand"),l.dependency(this,"nand",null,e)}},or:{method(...e){return s.verifyFlat(e,"or"),l.dependency(this,"or",null,e)}},oxor:{method(...e){
3602
- return l.dependency(this,"oxor",null,e)}},pattern:{method(e,r,n={}){const i=e instanceof RegExp;i||(e=this.$_compile(e,{appendPath:!0})),t(void 0!==r,"Invalid rule"),s.assertOptions(n,["fallthrough","matches"]),i&&t(!e.flags.includes("g")&&!e.flags.includes("y"),"pattern should not use global or sticky mode"),r=this.$_compile(r,{appendPath:!0});const o=this.clone();o.$_terms.patterns=o.$_terms.patterns||[];const a={[i?"regex":"schema"]:e,rule:r};return n.matches&&(a.matches=this.$_compile(n.matches),"array"!==a.matches.type&&(a.matches=a.matches.$_root.array().items(a.matches)),o.$_mutateRegister(a.matches),o.$_setFlag("_hasPatternMatch",!0,{clone:!1})),n.fallthrough&&(a.fallthrough=!0),o.$_terms.patterns.push(a),o.$_mutateRegister(r),o}},ref:{method(){return this.$_addRule("ref")},validate:(e,t)=>c.isRef(e)?e:t.error("object.refType",{value:e})},regex:{method(){return this.$_addRule("regex")},validate:(e,t)=>e instanceof RegExp?e:t.error("object.regex",{value:e})},rename:{
3603
- method(r,n,i={}){t("string"==typeof r||r instanceof RegExp,"Rename missing the from argument"),t("string"==typeof n||n instanceof u,"Invalid rename to argument"),t(n!==r,"Cannot rename key to same name:",r),s.assertOptions(i,["alias","ignoreUndefined","override","multiple"]);const o=this.clone();o.$_terms.renames=o.$_terms.renames||[];for(const e of o.$_terms.renames)t(e.from!==r,"Cannot rename the same key multiple times");return n instanceof u&&o.$_mutateRegister(n),o.$_terms.renames.push({from:r,to:n,options:e(l.renameDefaults,i)}),o}},schema:{method(e="any"){return this.$_addRule({name:"schema",args:{type:e}})},validate:(e,t,{type:r})=>!s.isSchema(e)||"any"!==r&&e.type!==r?t.error("object.schema",{type:r}):e},unknown:{method(e){return this.$_setFlag("unknown",!1!==e)}},with:{method(e,t,r={}){return l.dependency(this,"with",e,t,r)}},without:{method(e,t,r={}){return l.dependency(this,"without",e,t,r)}},xor:{method(...e){return s.verifyFlat(e,"xor"),l.dependency(this,"xor",null,e)}}},
3604
- overrides:{default(e,t){return void 0===e&&(e=s.symbols.deepDefault),this.$_parent("default",e,t)},isAsync(){if(this.$_terms.externals?.length)return!0;if(this.$_terms.keys?.length)for(const e of this.$_terms.keys)if(e.schema.isAsync())return!0;if(this.$_terms.patterns?.length)for(const e of this.$_terms.patterns)if(e.rule.isAsync())return!0;return!1}},rebuild(e){if(e.$_terms.keys){const t=new n.Sorter;for(const r of e.$_terms.keys)s.tryWithPath(()=>t.add(r,{after:r.schema.$_rootReferences(),group:r.key}),r.key);e.$_terms.keys=new l.Keys(...t.nodes)}},manifest:{build(e,t){if(t.keys&&(e=e.keys(t.keys)),t.dependencies)for(const{rel:r,key:n=null,peers:i,options:s}of t.dependencies)e=l.dependency(e,r,n,i,s);if(t.patterns)for(const{regex:r,schema:n,rule:i,fallthrough:s,matches:o}of t.patterns)e=e.pattern(r||n,i,{fallthrough:s,matches:o});if(t.renames)for(const{from:r,to:n,options:i}of t.renames)e=e.rename(r,n,i);return e}},messages:{
3605
- "object.and":"{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}","object.assert":'{{#label}} is invalid because {if(#subject.key, `"` + #subject.key + `" failed to ` + (#message || "pass the assertion test"), #message || "the assertion failed")}',"object.base":"{{#label}} must be of type {{#type}}","object.instance":"{{#label}} must be an instance of {{:#type}}","object.length":'{{#label}} must have {{#limit}} key{if(#limit == 1, "", "s")}',"object.max":'{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, "", "s")}',"object.min":'{{#label}} must have at least {{#limit}} key{if(#limit == 1, "", "s")}',"object.missing":"{{#label}} must contain at least one of {{#peersWithLabels}}","object.nand":"{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}","object.oxor":"{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}",
3606
- "object.pattern.match":"{{#label}} keys failed to match pattern requirements","object.refType":"{{#label}} must be a Joi reference","object.regex":"{{#label}} must be a RegExp object","object.rename.multiple":"{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}","object.rename.override":"{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists","object.schema":"{{#label}} must be a Joi schema of {{#type}} type","object.unknown":"{{#label}} is not allowed","object.with":"{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}","object.without":"{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}","object.xor":"{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}"}}),l.clone=function(e,t){if("object"==typeof e){if(t.nonEnumerables)return r(e,{shallow:!0});const n=Object.create(Object.getPrototypeOf(e));return Object.assign(n,e),n}
3607
- const n=function(...t){return e.apply(this,t)};return n.prototype=r(e.prototype),Object.defineProperty(n,"name",{value:e.name,writable:!1}),Object.defineProperty(n,"length",{value:e.length,writable:!1}),Object.assign(n,e),n},l.dependency=function(e,r,n,i,a){t(null===n||"string"==typeof n,r,"key must be a strings"),a||(a=i.length>1&&"object"==typeof i[i.length-1]?i.pop():{}),s.assertOptions(a,["separator","isPresent"]),i=[].concat(i);const c=s.default(a.separator,"."),u=[];for(const e of i)t("string"==typeof e,r,"peers must be strings"),u.push(o.ref(e,{separator:c,ancestor:0,prefix:!1}));null!==n&&(n=o.ref(n,{separator:c,ancestor:0,prefix:!1}));const d=e.clone();return d.$_terms.dependencies=d.$_terms.dependencies||[],d.$_terms.dependencies.push(new l.Dependency(r,n,u,i,a)),d},l.dependencies={and(e,t,r,n,i){const s=[],o=[],a=t.peers.length,c=l.isPresent(t.options);for(const e of t.peers)!1===c(e.resolve(r,n,i,null,{shadow:!1}))?s.push(e.key):o.push(e.key)
3608
- ;if(s.length!==a&&o.length!==a)return{code:"object.and",context:{present:o,presentWithLabels:l.keysToLabels(e,o),missing:s,missingWithLabels:l.keysToLabels(e,s)}}},nand(e,t,r,n,i){const s=[],o=l.isPresent(t.options);for(const e of t.peers)o(e.resolve(r,n,i,null,{shadow:!1}))&&s.push(e.key);if(s.length!==t.peers.length)return;const a=t.paths[0],c=t.paths.slice(1);return{code:"object.nand",context:{main:a,mainWithLabel:l.keysToLabels(e,a),peers:c,peersWithLabels:l.keysToLabels(e,c)}}},or(e,t,r,n,i){const s=l.isPresent(t.options);for(const e of t.peers)if(s(e.resolve(r,n,i,null,{shadow:!1})))return;return{code:"object.missing",context:{peers:t.paths,peersWithLabels:l.keysToLabels(e,t.paths)}}},oxor(e,t,r,n,i){const s=[],o=l.isPresent(t.options);for(const e of t.peers)o(e.resolve(r,n,i,null,{shadow:!1}))&&s.push(e.key);if(!s.length||1===s.length)return;const a={peers:t.paths,peersWithLabels:l.keysToLabels(e,t.paths)};return a.present=s,a.presentWithLabels=l.keysToLabels(e,s),{
3609
- code:"object.oxor",context:a}},with(e,t,r,n,i){const s=l.isPresent(t.options);for(const o of t.peers)if(!1===s(o.resolve(r,n,i,null,{shadow:!1})))return{code:"object.with",context:{main:t.key.key,mainWithLabel:l.keysToLabels(e,t.key.key),peer:o.key,peerWithLabel:l.keysToLabels(e,o.key)}}},without(e,t,r,n,i){const s=l.isPresent(t.options);for(const o of t.peers)if(s(o.resolve(r,n,i,null,{shadow:!1})))return{code:"object.without",context:{main:t.key.key,mainWithLabel:l.keysToLabels(e,t.key.key),peer:o.key,peerWithLabel:l.keysToLabels(e,o.key)}}},xor(e,t,r,n,i){const s=[],o=l.isPresent(t.options);for(const e of t.peers)o(e.resolve(r,n,i,null,{shadow:!1}))&&s.push(e.key);if(1===s.length)return;const a={peers:t.paths,peersWithLabels:l.keysToLabels(e,t.paths)};return 0===s.length?{code:"object.missing",context:a}:(a.present=s,a.presentWithLabels=l.keysToLabels(e,s),{code:"object.xor",context:a})}},l.keysToLabels=function(e,t){
3610
- return Array.isArray(t)?t.map(t=>e.$_mapLabels(t)):e.$_mapLabels(t)},l.isPresent=function(e){return"function"==typeof e.isPresent?e.isPresent:e=>void 0!==e},l.rename=function(e,t,r,n,i){const s={};for(const o of e.$_terms.renames){const a=[],c="string"!=typeof o.from;if(c)for(const e in t){if(void 0===t[e]&&o.options.ignoreUndefined)continue;if(e===o.to)continue;const r=o.from.exec(e);r&&a.push({from:e,to:o.to,match:r})}else!Object.prototype.hasOwnProperty.call(t,o.from)||void 0===t[o.from]&&o.options.ignoreUndefined||a.push(o);for(const l of a){const a=l.from;let d=l.to;if(d instanceof u&&(d=d.render(t,r,n,l.match)),a!==d){if(!o.options.multiple&&s[d]&&(i.push(e.$_createError("object.rename.multiple",t,{from:a,to:d,pattern:c},r,n)),n.abortEarly))return!1;if(Object.prototype.hasOwnProperty.call(t,d)&&!o.options.override&&!s[d]&&(i.push(e.$_createError("object.rename.override",t,{from:a,to:d,pattern:c},r,n)),n.abortEarly))return!1;void 0===t[a]?delete t[d]:t[d]=t[a],s[d]=!0,
3611
- o.options.alias||delete t[a]}}}return!0},l.unknown=function(e,t,r,n,i,o){if(e.$_terms.patterns){let s=!1;const c=e.$_terms.patterns.map(e=>{if(e.matches)return s=!0,[]}),u=[t,...i.ancestors];for(const s of r){const a=t[s],l=[...i.path,s];for(let d=0;d<e.$_terms.patterns.length;++d){const p=e.$_terms.patterns[d];if(p.regex){const e=p.regex.test(s);if(i.mainstay.tracer.debug(i,"rule",`pattern.${d}`,e?"pass":"error"),!e)continue}else if(!p.schema.$_match(s,i.nest(p.schema,`pattern.${d}`),o))continue;r.delete(s);const h=i.localize(l,u,{schema:p.rule,key:s}),A=p.rule.$_validate(a,h,o);if(A.errors){if(o.abortEarly)return{value:t,errors:A.errors};n.push(...A.errors)}if(p.matches&&c[d].push(s),t[s]=A.value,!p.fallthrough)break}}if(s)for(let r=0;r<c.length;++r){const s=c[r];if(!s)continue;const l=e.$_terms.patterns[r].matches,d=i.localize(i.path,u,l),p=l.$_validate(s,d,o);if(p.errors){const r=a.details(p.errors,{override:!1});r.matches=s;const c=e.$_createError("object.pattern.match",t,r,i,o)
3612
- ;if(o.abortEarly)return{value:t,errors:c};n.push(c)}}}if(!r.size||!e.$_terms.keys&&!e.$_terms.patterns)return;if(o.stripUnknown&&void 0===e._flags.unknown||o.skipFunctions){const e=!!o.stripUnknown&&(!0===o.stripUnknown||!!o.stripUnknown.objects);for(const n of r)e?(delete t[n],r.delete(n)):"function"==typeof t[n]&&r.delete(n)}if(!s.default(e._flags.unknown,o.allowUnknown))for(const s of r){const r=i.localize([...i.path,s],[]),a=e.$_createError("object.unknown",t[s],{child:s},r,o,{flags:!1});if(o.abortEarly)return{value:t,errors:a};n.push(a)}},l.Dependency=class{constructor(e,t,r,n,i){this.rel=e,this.key=t,this.peers=r,this.paths=n,this.options=i}describe(){const e={rel:this.rel,peers:this.paths};return null!==this.key&&(e.key=this.key.key),"."!==this.peers[0].separator&&(e.options={...e.options,separator:this.peers[0].separator}),this.options.isPresent&&(e.options={...e.options,isPresent:this.options.isPresent}),e}},l.Keys=class extends Array{concat(e){const t=this.slice(),r=new Map
3613
- ;for(let e=0;e<t.length;++e)r.set(t[e].key,e);for(const n of e){const e=n.key,i=r.get(e);void 0!==i?t[i]={key:e,schema:t[i].schema.concat(n.schema)}:t.push(n)}return t}},keys}function require_function(){if(hasRequired_function)return _function;hasRequired_function=1;const{assert:e}=requireLib$4(),t=requireKeys();return _function=t.extend({type:"function",properties:{typeof:"function"},rules:{arity:{method(t){return e(Number.isSafeInteger(t)&&t>=0,"n must be a positive integer"),this.$_addRule({name:"arity",args:{n:t}})},validate:(e,t,{n:r})=>e.length===r?e:t.error("function.arity",{n:r})},class:{method(){return this.$_addRule("class")},validate:(e,t)=>/^\s*class\s/.test(e.toString())?e:t.error("function.class",{value:e})},minArity:{method(t){return e(Number.isSafeInteger(t)&&t>0,"n must be a strict positive integer"),this.$_addRule({name:"minArity",args:{n:t}})},validate:(e,t,{n:r})=>e.length>=r?e:t.error("function.minArity",{n:r})},maxArity:{method(t){
3614
- return e(Number.isSafeInteger(t)&&t>=0,"n must be a positive integer"),this.$_addRule({name:"maxArity",args:{n:t}})},validate:(e,t,{n:r})=>e.length<=r?e:t.error("function.maxArity",{n:r})}},messages:{"function.arity":"{{#label}} must have an arity of {{#n}}","function.class":"{{#label}} must be a class","function.maxArity":"{{#label}} must have an arity lesser or equal to {{#n}}","function.minArity":"{{#label}} must have an arity greater or equal to {{#n}}"}}),_function}function requireLink(){if(hasRequiredLink)return link;hasRequiredLink=1;const{assert:e}=requireLib$4(),t=requireAny(),r=requireCommon(),n=requireCompile(),i=requireErrors$1(),s={};return link=t.extend({type:"link",properties:{schemaChain:!0},terms:{link:{init:null,manifest:"single",register:!1}},args:(e,t)=>e.ref(t),validate(t,{schema:r,state:n,prefs:i}){e(r.$_terms.link,"Uninitialized link schema");const o=s.generate(r,t,n,i),a=r.$_terms.link[0].ref;return o.$_validate(t,n.nest(o,`link:${a.display}:${o.type}`),i)},
3615
- generate:(e,t,r,n)=>s.generate(e,t,r,n),rules:{ref:{method(t){e(!this.$_terms.link,"Cannot reinitialize schema"),t=n.ref(t),e("value"===t.type||"local"===t.type,"Invalid reference type:",t.type),e("local"===t.type||"root"===t.ancestor||t.ancestor>0,"Link cannot reference itself");const r=this.clone();return r.$_terms.link=[{ref:t}],r}},relative:{method(e=!0){return this.$_setFlag("relative",e)}}},overrides:{concat(t){e(this.$_terms.link,"Uninitialized link schema"),e(r.isSchema(t),"Invalid schema object"),e("link"!==t.type,"Cannot merge type link with another link");const n=this.clone();return n.$_terms.whens||(n.$_terms.whens=[]),n.$_terms.whens.push({concat:t}),n.$_mutateRebuild()}},manifest:{build:(t,r)=>(e(r.link,"Invalid link description missing link"),t.ref(r.link))}}),s.generate=function(e,t,r,n){let i=r.mainstay.links.get(e);if(i)return i._generate(t,r,n).schema;const o=e.$_terms.link[0].ref,{perspective:a,path:c}=s.perspective(o,r)
3616
- ;s.assert(a,"which is outside of schema boundaries",o,e,r,n);try{i=c.length?a.$_reach(c):a}catch{s.assert(!1,"to non-existing schema",o,e,r,n)}return s.assert("link"!==i.type,"which is another link",o,e,r,n),e._flags.relative||r.mainstay.links.set(e,i),i._generate(t,r,n).schema},s.perspective=function(e,t){if("local"===e.type){for(const{schema:r,key:n}of t.schemas){if((r._flags.id||n)===e.path[0])return{perspective:r,path:e.path.slice(1)};if(r.$_terms.shared)for(const t of r.$_terms.shared)if(t._flags.id===e.path[0])return{perspective:t,path:e.path.slice(1)}}return{perspective:null,path:null}}return"root"===e.ancestor?{perspective:t.schemas[t.schemas.length-1].schema,path:e.path}:{perspective:t.schemas[e.ancestor]&&t.schemas[e.ancestor].schema,path:e.path}},s.assert=function(t,r,n,s,o,a){t||e(!1,`"${i.label(s._flags,o,a)}" contains link reference "${n.display}" ${r}`)},link}function requireNumber(){if(hasRequiredNumber)return number;hasRequiredNumber=1
3617
- ;const{assert:e}=requireLib$4(),t=requireAny(),r=requireCommon(),n={numberRx:/^\s*[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e([+-]?\d+))?\s*$/i,precisionRx:/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/,exponentialPartRegex:/[eE][+-]?\d+$/,leadingSignAndZerosRegex:/^[+-]?(0*)?/,dotRegex:/\./,trailingZerosRegex:/0+$/,decimalPlaces(e){const t=e.toString(),r=t.indexOf("."),n=t.indexOf("e");return(r<0?0:(n<0?t.length:n)-r-1)+(n<0?0:Math.max(0,-parseInt(t.slice(n+1))))}};return number=t.extend({type:"number",flags:{unsafe:{default:!1}},coerce:{from:"string",method(e,{schema:t,error:r}){if(!e.match(n.numberRx))return;e=e.trim();const i={value:parseFloat(e)};if(0===i.value&&(i.value=0),!t._flags.unsafe)if(e.match(/e/i)){if(n.extractSignificantDigits(e)!==n.extractSignificantDigits(String(i.value)))return i.errors=r("number.unsafe"),i}else{const t=i.value.toString();if(t.match(/e/i))return i;if(t!==n.normalizeDecimal(e))return i.errors=r("number.unsafe"),i}return i}},validate(e,{schema:t,error:n,prefs:i}){
3618
- if(e===1/0||e===-1/0)return{value:e,errors:n("number.infinity")};if(!r.isNumber(e))return{value:e,errors:n("number.base")};const s={value:e};if(i.convert){const e=t.$_getRule("precision");if(e){const t=Math.pow(10,e.args.limit);s.value=Math.round(s.value*t)/t}}return 0===s.value&&(s.value=0),!t._flags.unsafe&&(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER)&&(s.errors=n("number.unsafe")),s},rules:{compare:{method:!1,validate:(e,t,{limit:n},{name:i,operator:s,args:o})=>r.compare(e,n,s)?e:t.error("number."+i,{limit:o.limit,value:e}),args:[{name:"limit",ref:!0,assert:r.isNumber,message:"must be a number"}]},greater:{method(e){return this.$_addRule({name:"greater",method:"compare",args:{limit:e},operator:">"})}},integer:{method(){return this.$_addRule("integer")},validate:(e,t)=>Math.trunc(e)-e===0?e:t.error("number.integer")},less:{method(e){return this.$_addRule({name:"less",method:"compare",args:{limit:e},operator:"<"})}},max:{method(e){return this.$_addRule({name:"max",
3619
- method:"compare",args:{limit:e},operator:"<="})}},min:{method(e){return this.$_addRule({name:"min",method:"compare",args:{limit:e},operator:">="})}},multiple:{method(e){const t="number"==typeof e?n.decimalPlaces(e):null,r=Math.pow(10,t);return this.$_addRule({name:"multiple",args:{base:e,baseDecimalPlace:t,pfactor:r}})},validate:(e,t,{base:r,baseDecimalPlace:i,pfactor:s},o)=>n.decimalPlaces(e)>i?t.error("number.multiple",{multiple:o.args.base,value:e}):Math.round(s*e)%Math.round(s*r)===0?e:t.error("number.multiple",{multiple:o.args.base,value:e}),args:[{name:"base",ref:!0,assert:e=>"number"==typeof e&&isFinite(e)&&e>0,message:"must be a positive number"},"baseDecimalPlace","pfactor"],multi:!0},negative:{method(){return this.sign("negative")}},port:{method(){return this.$_addRule("port")},validate:(e,t)=>Number.isSafeInteger(e)&&e>=0&&e<=65535?e:t.error("number.port")},positive:{method(){return this.sign("positive")}},precision:{method(t){
3620
- return e(Number.isSafeInteger(t),"limit must be an integer"),this.$_addRule({name:"precision",args:{limit:t}})},validate(e,t,{limit:r}){const i=e.toString().match(n.precisionRx);return Math.max((i[1]?i[1].length:0)-(i[2]?parseInt(i[2],10):0),0)<=r?e:t.error("number.precision",{limit:r,value:e})},convert:!0},sign:{method(t){return e(["negative","positive"].includes(t),"Invalid sign",t),this.$_addRule({name:"sign",args:{sign:t}})},validate:(e,t,{sign:r})=>"negative"===r&&e<0||"positive"===r&&e>0?e:t.error(`number.${r}`)},unsafe:{method(t=!0){return e("boolean"==typeof t,"enabled must be a boolean"),this.$_setFlag("unsafe",t)}}},cast:{string:{from:e=>"number"==typeof e,to:(e,t)=>e.toString()}},messages:{"number.base":"{{#label}} must be a number","number.greater":"{{#label}} must be greater than {{#limit}}","number.infinity":"{{#label}} cannot be infinity","number.integer":"{{#label}} must be an integer","number.less":"{{#label}} must be less than {{#limit}}",
3621
- "number.max":"{{#label}} must be less than or equal to {{#limit}}","number.min":"{{#label}} must be greater than or equal to {{#limit}}","number.multiple":"{{#label}} must be a multiple of {{#multiple}}","number.negative":"{{#label}} must be a negative number","number.port":"{{#label}} must be a valid port","number.positive":"{{#label}} must be a positive number","number.precision":"{{#label}} must have no more than {{#limit}} decimal places","number.unsafe":"{{#label}} must be a safe number"}}),n.extractSignificantDigits=function(e){return e.replace(n.exponentialPartRegex,"").replace(n.dotRegex,"").replace(n.trailingZerosRegex,"").replace(n.leadingSignAndZerosRegex,"")},n.normalizeDecimal=function(e){return(e=e.replace(/^\+/,"").replace(/\.0*$/,"").replace(/^(-?)\.([^\.]*)$/,"$10.$2").replace(/^(-?)0+([0-9])/,"$1$2")).includes(".")&&e.endsWith("0")&&(e=e.replace(/0+$/,"")),"-0"===e?"0":e},number}function requireObject(){if(hasRequiredObject)return object;hasRequiredObject=1
3622
- ;const e=requireKeys();return object=e.extend({type:"object",cast:{map:{from:e=>e&&"object"==typeof e,to:(e,t)=>new Map(Object.entries(e))}}})}const errorCodes={EMPTY_STRING:"Address must be a non-empty string",FORBIDDEN_UNICODE:"Address contains forbidden Unicode characters",MULTIPLE_AT_CHAR:"Address cannot contain more than one @ character",MISSING_AT_CHAR:"Address must contain one @ character",EMPTY_LOCAL:"Address local part cannot be empty",ADDRESS_TOO_LONG:"Address too long",LOCAL_TOO_LONG:"Address local part too long",EMPTY_LOCAL_SEGMENT:"Address local part contains empty dot-separated segment",INVALID_LOCAL_CHARS:"Address local part contains invalid character",DOMAIN_NON_EMPTY_STRING:"Domain must be a non-empty string",DOMAIN_TOO_LONG:"Domain too long",DOMAIN_INVALID_UNICODE_CHARS:"Domain contains forbidden Unicode characters",DOMAIN_INVALID_CHARS:"Domain contains invalid character",DOMAIN_INVALID_TLDS_CHARS:"Domain contains invalid tld character",
3623
- DOMAIN_SEGMENTS_COUNT:"Domain lacks the minimum required number of segments",DOMAIN_SEGMENTS_COUNT_MAX:"Domain contains too many segments",DOMAIN_FORBIDDEN_TLDS:"Domain uses forbidden TLD",DOMAIN_EMPTY_SEGMENT:"Domain contains empty dot-separated segment",DOMAIN_LONG_SEGMENT:"Domain contains dot-separated segment that is too long"};function errorCode$1(e){return{code:e,error:errorCodes[e]}}const MIN_DOMAIN_SEGMENTS=2,NON_ASCII_RX$1=/[^\x00-\x7f]/,DOMAIN_CONTROL_RX=/[\x00-\x20@\:\/\\#!\$&\'\(\)\*\+,;=\?]/,TLD_SEGMENT_RX=/^[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,DOMAIN_SEGMENT_RX=/^[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,DOMAIN_UNDERSCORE_SEGMENT_RX=/^[a-zA-Z0-9_](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,URL_IMPL=Url$1.URL||URL;function isTldsAllow(e){return!!e.allow}function analyzeDomain(e,t={}){if(!e)return errorCode$1("DOMAIN_NON_EMPTY_STRING");if("string"!=typeof e)throw new Error("Invalid input: domain must be a string");if(e.length>256)return errorCode$1("DOMAIN_TOO_LONG")
3624
- ;if(!!NON_ASCII_RX$1.test(e)){if(!1===t.allowUnicode)return errorCode$1("DOMAIN_INVALID_UNICODE_CHARS");e=e.normalize("NFC")}if(DOMAIN_CONTROL_RX.test(e))return errorCode$1("DOMAIN_INVALID_CHARS");e=punycode(e),t.allowFullyQualified&&"."===e[e.length-1]&&(e=e.slice(0,-1));const r=t.minDomainSegments||MIN_DOMAIN_SEGMENTS,n=e.split(".");if(n.length<r)return errorCode$1("DOMAIN_SEGMENTS_COUNT");if(t.maxDomainSegments&&n.length>t.maxDomainSegments)return errorCode$1("DOMAIN_SEGMENTS_COUNT_MAX");const i=t.tlds;if(i){const e=n[n.length-1].toLowerCase();if(isTldsAllow(i)){if(!i.allow.has(e))return errorCode$1("DOMAIN_FORBIDDEN_TLDS")}else if(i.deny.has(e))return errorCode$1("DOMAIN_FORBIDDEN_TLDS")}for(let e=0;e<n.length;++e){const r=n[e];if(!r.length)return errorCode$1("DOMAIN_EMPTY_SEGMENT");if(r.length>63)return errorCode$1("DOMAIN_LONG_SEGMENT");if(e<n.length-1){if(t.allowUnderscore){if(!DOMAIN_UNDERSCORE_SEGMENT_RX.test(r))return errorCode$1("DOMAIN_INVALID_CHARS")
3625
- }else if(!DOMAIN_SEGMENT_RX.test(r))return errorCode$1("DOMAIN_INVALID_CHARS")}else if(!TLD_SEGMENT_RX.test(r))return errorCode$1("DOMAIN_INVALID_TLDS_CHARS")}return null}function isDomainValid(e,t){return!analyzeDomain(e,t)}function punycode(e){e.includes("%")&&(e=e.replace(/%/g,"%25"));try{return new URL_IMPL(`http://${e}`).host}catch(t){return e}}function validateDomainOptions(e){if(e){if("object"!=typeof e.tlds)throw new Error("Invalid options: tlds must be a boolean or an object");if(isTldsAllow(e.tlds)){if(e.tlds.allow instanceof Set==!1)throw new Error("Invalid options: tlds.allow must be a Set object or true");if(e.tlds.deny)throw new Error("Invalid options: cannot specify both tlds.allow and tlds.deny lists")}else if(e.tlds.deny instanceof Set==!1)throw new Error("Invalid options: tlds.deny must be a Set object")}}const NON_ASCII_RX=/[^\x00-\x7f]/,ENCODER_IMPL=new(require$$0$b.TextEncoder||TextEncoder);function analyzeEmail(e,t){return validateEmail(e,t)}
3626
- function isEmailValid(e,t){return!validateEmail(e,t)}function validateEmail(e,t={}){if("string"!=typeof e)throw new Error("Invalid input: email must be a string");if(!e)return errorCode$1("EMPTY_STRING");const r=!NON_ASCII_RX.test(e);if(!r){if(!1===t.allowUnicode)return errorCode$1("FORBIDDEN_UNICODE");e=e.normalize("NFC")}const n=e.split("@");if(2!==n.length)return n.length>2?errorCode$1("MULTIPLE_AT_CHAR"):errorCode$1("MISSING_AT_CHAR");const[i,s]=n;if(!i)return errorCode$1("EMPTY_LOCAL");if(!t.ignoreLength){if(e.length>254)return errorCode$1("ADDRESS_TOO_LONG");if(ENCODER_IMPL.encode(i).length>64)return errorCode$1("LOCAL_TOO_LONG")}return validateLocal(i,r)||analyzeDomain(s,t)}function validateLocal(e,t){const r=e.split(".");for(const e of r){if(!e.length)return errorCode$1("EMPTY_LOCAL_SEGMENT");if(t){if(!ATEXT_RX.test(e))return errorCode$1("INVALID_LOCAL_CHARS")}else for(const t of e){if(ATEXT_RX.test(t))continue;const e=toBinary(t)
3627
- ;if(!ATOM_RX.test(e))return errorCode$1("INVALID_LOCAL_CHARS")}}return null}function toBinary(e){return Array.from(ENCODER_IMPL.encode(e),e=>String.fromCharCode(e)).join("")}const ATEXT_RX=/^[\w!#\$%&'\*\+\-/=\?\^`\{\|\}~]+$/,ATOM_RX=new RegExp(["(?:[\\xc2-\\xdf][\\x80-\\xbf])","(?:\\xe0[\\xa0-\\xbf][\\x80-\\xbf])|(?:[\\xe1-\\xec][\\x80-\\xbf]{2})|(?:\\xed[\\x80-\\x9f][\\x80-\\xbf])|(?:[\\xee-\\xef][\\x80-\\xbf]{2})","(?:\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2})|(?:[\\xf1-\\xf3][\\x80-\\xbf]{3})|(?:\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})"].join("|"));requireApplyToDefaults();var assertExports=requireAssert(),assert$1=getDefaultExportFromCjs(assertExports);requireBench(),requireBlock(),requireClone(),requireContain(),requireDeepEqual(),requireAssertError(),requireEscapeHeaderAttribute(),requireEscapeHtml(),requireEscapeJson();var escapeRegexExports=requireEscapeRegex(),escapeRegex=getDefaultExportFromCjs(escapeRegexExports);function generate$1(){
3628
- const e={},t="\\dA-Fa-f",r="["+t+"]",n="\\w-\\.~",i="!\\$&'\\(\\)\\*\\+,;=",s="%"+t,o=n+s+i+":@",a="["+o+"]",c="(?:0{0,2}\\d|0?[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])";e.ipv4address="(?:"+c+"\\.){3}"+c;const u=r+"{1,4}",l="(?:"+u+":"+u+"|"+e.ipv4address+")",d="(?:"+u+":){6}"+l,p="::(?:"+u+":){5}"+l,h="(?:"+u+")?::(?:"+u+":){4}"+l,A="(?:(?:"+u+":){0,1}"+u+")?::(?:"+u+":){3}"+l,f="(?:(?:"+u+":){0,2}"+u+")?::(?:"+u+":){2}"+l,g="(?:(?:"+u+":){0,3}"+u+")?::"+u+":"+l,m="(?:(?:"+u+":){0,4}"+u+")?::"+l,y="(?:(?:"+u+":){0,5}"+u+")?::"+u,E="(?:(?:"+u+":){0,6}"+u+")?::";e.ipv4Cidr="(?:\\d|[1-2]\\d|3[0-2])",e.ipv6Cidr="(?:0{0,2}\\d|0?[1-9]\\d|1[01]\\d|12[0-8])",e.ipv6address="(?:"+d+"|"+p+"|"+h+"|"+A+"|"+f+"|"+g+"|"+m+"|"+y+"|"+E+")",e.ipvFuture="v"+r+"+\\.["+n+i+":]+",e.scheme="[a-zA-Z][a-zA-Z\\d+-\\.]*",e.schemeRegex=new RegExp(e.scheme)
3629
- ;const b="["+n+s+i+":]*",C="["+n+s+i+"]{1,255}",I="(?:"+("\\[(?:"+e.ipv6address+"|"+e.ipvFuture+")\\]")+"|"+e.ipv4address+"|"+C+")",v="(?:"+b+"@)?"+I+"(?::\\d*)?",w="(?:"+b+"@)?("+I+")(?::\\d*)?",S=a+"*",_=a+"+",D="(?:\\/"+S+")*",B="\\/(?:"+_+D+")?",R=_+D,T="["+n+s+i+"@]+"+D,x="(?:\\/\\/\\/"+S+D+")";return e.hierPart="(?:(?:\\/\\/"+v+D+")|"+B+"|"+R+"|"+x+")",e.hierPartCapture="(?:(?:\\/\\/"+w+D+")|"+B+"|"+R+")",e.relativeRef="(?:(?:\\/\\/"+v+D+")|"+B+"|"+T+"|)",e.relativeRefCapture="(?:(?:\\/\\/"+w+D+")|"+B+"|"+T+"|)",e.query="["+o+"\\/\\?]*(?=#|$)",e.queryWithSquareBrackets="["+o+"\\[\\]\\/\\?]*(?=#|$)",e.fragment="["+o+"\\/\\?]*",e}requireFlatten(),requireIgnore(),requireIntersect(),requireIsPromise$1(),requireMerge$2(),requireOnce(),requireReach(),requireReachTemplate(),requireStringify$1(),requireWait();const rfc3986=generate$1(),ipVersions={v4Cidr:rfc3986.ipv4Cidr,v6Cidr:rfc3986.ipv6Cidr,ipv4:rfc3986.ipv4address,ipv6:rfc3986.ipv6address,ipvfuture:rfc3986.ipvFuture}
3630
- ;function createRegex(e){const t=rfc3986,r="(?:\\?"+(e.allowQuerySquareBrackets?t.queryWithSquareBrackets:t.query)+")?(?:#"+t.fragment+")?",n=e.domain?t.relativeRefCapture:t.relativeRef;if(e.relativeOnly)return wrap(n+r);let i="";if(e.scheme){assert$1(e.scheme instanceof RegExp||"string"==typeof e.scheme||Array.isArray(e.scheme),"scheme must be a RegExp, String, or Array");const r=[].concat(e.scheme);assert$1(r.length>=1,"scheme must have at least 1 scheme specified");const n=[];for(let e=0;e<r.length;++e){const i=r[e];assert$1(i instanceof RegExp||"string"==typeof i,"scheme at position "+e+" must be a RegExp or String"),i instanceof RegExp?n.push(i.source.toString()):(assert$1(t.schemeRegex.test(i),"scheme at position "+e+" must be a valid scheme"),n.push(escapeRegex(i)))}i=n.join("|")}const s="(?:"+(i?"(?:"+i+")":t.scheme)+":"+(e.domain?t.hierPartCapture:t.hierPart)+")";return wrap((e.allowRelative?"(?:"+s+"|"+n+")":s)+r,i)}function wrap(e,t=null){return{
3631
- raw:e=`(?=.)(?!https?:/(?:$|[^/]))(?!https?:///)(?!https?:[^/])${e}`,regex:new RegExp(`^${e}$`),scheme:t}}const genericUriRegex=createRegex({});function uriRegex(e={}){return e.scheme||e.allowRelative||e.relativeOnly||e.allowQuerySquareBrackets||e.domain?createRegex(e):genericUriRegex}function ipRegex(e={}){const t=e.cidr||"optional";assert$1(["required","optional","forbidden"].includes(t),"options.cidr must be one of required, optional, forbidden"),assert$1(void 0===e.version||"string"==typeof e.version||Array.isArray(e.version),"options.version must be a string or an array of string");let r=e.version||["ipv4","ipv6","ipvfuture"];Array.isArray(r)||(r=[r]),assert$1(r.length>=1,"options.version must have at least 1 version specified");for(const e of r)assert$1("string"==typeof e&&e===e.toLowerCase(),"Invalid options.version value"),assert$1(["ipv4","ipv6","ipvfuture"].includes(e),"options.version contains unknown version "+e+" - must be one of ipv4, ipv6, ipvfuture")
3632
- ;r=Array.from(new Set(r));const n=r.map(e=>{if("forbidden"===t)return ipVersions[e];const r=`\\/${"ipv4"===e?ipVersions.v4Cidr:ipVersions.v6Cidr}`;return"required"===t?`${ipVersions[e]}${r}`:`${ipVersions[e]}(?:${r})?`}),i=`(?:${n.join("|")})`,s=new RegExp(`^${i}$`);return{cidr:t,versions:r,regex:s,raw:i}}const HEX={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15},UTF8={accept:12,reject:0,
3633
- data:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7]};function uriDecode(e){let t=e.indexOf("%");if(-1===t)return e;let r="",n=0,i=0,s=t,o=UTF8.accept;for(;t>-1&&t<e.length;){const a=resolveHex(e[t+1],4)|resolveHex(e[t+2],0),c=UTF8.data[a]
3634
- ;if(o=UTF8.data[256+o+c],i=i<<6|a&UTF8.data[364+c],o!==UTF8.accept){if(o===UTF8.reject)return null;if(t+=3,t>=e.length||"%"!==e[t])return null}else r+=e.slice(n,s),r+=i<=65535?String.fromCharCode(i):String.fromCharCode(55232+(i>>10),56320+(1023&i)),i=0,n=t+3,t=e.indexOf("%",n),s=t}return r+e.slice(n)}function resolveHex(e,t){const r=HEX[e];return void 0===r?255:r<<t}var esm=Object.freeze({__proto__:null,analyzeDomain,analyzeEmail,errorCodes,ipRegex,isDomainValid,isEmailValid,uriDecode,uriRegex,validateDomainOptions}),require$$1=getAugmentedNamespace(esm),commonjs={},tlds={},hasRequiredTlds,hasRequiredCommonjs,string,hasRequiredString,symbol,hasRequiredSymbol,binary$1,hasRequiredBinary,lib,hasRequiredLib,delayed_stream,hasRequiredDelayed_stream,combined_stream,hasRequiredCombined_stream;function requireTlds(){return hasRequiredTlds||(hasRequiredTlds=1,Object.defineProperty(tlds,"__esModule",{value:!0}),tlds.TLDS=void 0,
3635
- tlds.TLDS=["AAA","AARP","ABB","ABBOTT","ABBVIE","ABC","ABLE","ABOGADO","ABUDHABI","AC","ACADEMY","ACCENTURE","ACCOUNTANT","ACCOUNTANTS","ACO","ACTOR","AD","ADS","ADULT","AE","AEG","AERO","AETNA","AF","AFL","AFRICA","AG","AGAKHAN","AGENCY","AI","AIG","AIRBUS","AIRFORCE","AIRTEL","AKDN","AL","ALIBABA","ALIPAY","ALLFINANZ","ALLSTATE","ALLY","ALSACE","ALSTOM","AM","AMAZON","AMERICANEXPRESS","AMERICANFAMILY","AMEX","AMFAM","AMICA","AMSTERDAM","ANALYTICS","ANDROID","ANQUAN","ANZ","AO","AOL","APARTMENTS","APP","APPLE","AQ","AQUARELLE","AR","ARAB","ARAMCO","ARCHI","ARMY","ARPA","ART","ARTE","AS","ASDA","ASIA","ASSOCIATES","AT","ATHLETA","ATTORNEY","AU","AUCTION","AUDI","AUDIBLE","AUDIO","AUSPOST","AUTHOR","AUTO","AUTOS","AW","AWS","AX","AXA","AZ","AZURE","BA","BABY","BAIDU","BANAMEX","BAND","BANK","BAR","BARCELONA","BARCLAYCARD","BARCLAYS","BAREFOOT","BARGAINS","BASEBALL","BASKETBALL","BAUHAUS","BAYERN","BB","BBC","BBT","BBVA","BCG","BCN","BD","BE","BEATS","BEAUTY","BEER","BERLIN","BEST","BESTBUY","BET","BF","BG","BH","BHARTI","BI","BIBLE","BID","BIKE","BING","BINGO","BIO","BIZ","BJ","BLACK","BLACKFRIDAY","BLOCKBUSTER","BLOG","BLOOMBERG","BLUE","BM","BMS","BMW","BN","BNPPARIBAS","BO","BOATS","BOEHRINGER","BOFA","BOM","BOND","BOO","BOOK","BOOKING","BOSCH","BOSTIK","BOSTON","BOT","BOUTIQUE","BOX","BR","BRADESCO","BRIDGESTONE","BROADWAY","BROKER","BROTHER","BRUSSELS","BS","BT","BUILD","BUILDERS","BUSINESS","BUY","BUZZ","BV","BW","BY","BZ","BZH","CA","CAB","CAFE","CAL","CALL","CALVINKLEIN","CAM","CAMERA","CAMP","CANON","CAPETOWN","CAPITAL","CAPITALONE","CAR","CARAVAN","CARDS","CARE","CAREER","CAREERS","CARS","CASA","CASE","CASH","CASINO","CAT","CATERING","CATHOLIC","CBA","CBN","CBRE","CC","CD","CENTER","CEO","CERN","CF","CFA","CFD","CG","CH","CHANEL","CHANNEL","CHARITY","CHASE","CHAT","CHEAP","CHINTAI","CHRISTMAS","CHROME","CHURCH","CI","CIPRIANI","CIRCLE","CISCO","CITADEL","CITI","CITIC","CITY","CK","CL","CLAIMS","CLEANING","CLICK","CLINIC","CLINIQUE","CLOTHING","CLOUD","CLUB","CLUBMED","CM","CN","CO","COACH","CODES","COFFEE","COLLEGE","COLOGNE","COM","COMMBANK","COMMUNITY","COMPANY","COMPARE","COMPUTER","COMSEC","CONDOS","CONSTRUCTION","CONSULTING","CONTACT","CONTRACTORS","COOKING","COOL","COOP","CORSICA","COUNTRY","COUPON","COUPONS","COURSES","CPA","CR","CREDIT","CREDITCARD","CREDITUNION","CRICKET","CROWN","CRS","CRUISE","CRUISES","CU","CUISINELLA","CV","CW","CX","CY","CYMRU","CYOU","CZ","DAD","DANCE","DATA","DATE","DATING","DATSUN","DAY","DCLK","DDS","DE","DEAL","DEALER","DEALS","DEGREE","DELIVERY","DELL","DELOITTE","DELTA","DEMOCRAT","DENTAL","DENTIST","DESI","DESIGN","DEV","DHL","DIAMONDS","DIET","DIGITAL","DIRECT","DIRECTORY","DISCOUNT","DISCOVER","DISH","DIY","DJ","DK","DM","DNP","DO","DOCS","DOCTOR","DOG","DOMAINS","DOT","DOWNLOAD","DRIVE","DTV","DUBAI","DUNLOP","DUPONT","DURBAN","DVAG","DVR","DZ","EARTH","EAT","EC","ECO","EDEKA","EDU","EDUCATION","EE","EG","EMAIL","EMERCK","ENERGY","ENGINEER","ENGINEERING","ENTERPRISES","EPSON","EQUIPMENT","ER","ERICSSON","ERNI","ES","ESQ","ESTATE","ET","EU","EUROVISION","EUS","EVENTS","EXCHANGE","EXPERT","EXPOSED","EXPRESS","EXTRASPACE","FAGE","FAIL","FAIRWINDS","FAITH","FAMILY","FAN","FANS","FARM","FARMERS","FASHION","FAST","FEDEX","FEEDBACK","FERRARI","FERRERO","FI","FIDELITY","FIDO","FILM","FINAL","FINANCE","FINANCIAL","FIRE","FIRESTONE","FIRMDALE","FISH","FISHING","FIT","FITNESS","FJ","FK","FLICKR","FLIGHTS","FLIR","FLORIST","FLOWERS","FLY","FM","FO","FOO","FOOD","FOOTBALL","FORD","FOREX","FORSALE","FORUM","FOUNDATION","FOX","FR","FREE","FRESENIUS","FRL","FROGANS","FRONTIER","FTR","FUJITSU","FUN","FUND","FURNITURE","FUTBOL","FYI","GA","GAL","GALLERY","GALLO","GALLUP","GAME","GAMES","GAP","GARDEN","GAY","GB","GBIZ","GD","GDN","GE","GEA","GENT","GENTING","GEORGE","GF","GG","GGEE","GH","GI","GIFT","GIFTS","GIVES","GIVING","GL","GLASS","GLE","GLOBAL","GLOBO","GM","GMAIL","GMBH","GMO","GMX","GN","GODADDY","GOLD","GOLDPOINT","GOLF","GOO","GOODYEAR","GOOG","GOOGLE","GOP","GOT","GOV","GP","GQ","GR","GRAINGER","GRAPHICS","GRATIS","GREEN","GRIPE","GROCERY","GROUP","GS","GT","GU","GUCCI","GUGE","GUIDE","GUITARS","GURU","GW","GY","HAIR","HAMBURG","HANGOUT","HAUS","HBO","HDFC","HDFCBANK","HEALTH","HEALTHCARE","HELP","HELSINKI","HERE","HERMES","HIPHOP","HISAMITSU","HITACHI","HIV","HK","HKT","HM","HN","HOCKEY","HOLDINGS","HOLIDAY","HOMEDEPOT","HOMEGOODS","HOMES","HOMESENSE","HONDA","HORSE","HOSPITAL","HOST","HOSTING","HOT","HOTELS","HOTMAIL","HOUSE","HOW","HR","HSBC","HT","HU","HUGHES","HYATT","HYUNDAI","IBM","ICBC","ICE","ICU","ID","IE","IEEE","IFM","IKANO","IL","IM","IMAMAT","IMDB","IMMO","IMMOBILIEN","IN","INC","INDUSTRIES","INFINITI","INFO","ING","INK","INSTITUTE","INSURANCE","INSURE","INT","INTERNATIONAL","INTUIT","INVESTMENTS","IO","IPIRANGA","IQ","IR","IRISH","IS","ISMAILI","IST","ISTANBUL","IT","ITAU","ITV","JAGUAR","JAVA","JCB","JE","JEEP","JETZT","JEWELRY","JIO","JLL","JM","JMP","JNJ","JO","JOBS","JOBURG","JOT","JOY","JP","JPMORGAN","JPRS","JUEGOS","JUNIPER","KAUFEN","KDDI","KE","KERRYHOTELS","KERRYPROPERTIES","KFH","KG","KH","KI","KIA","KIDS","KIM","KINDLE","KITCHEN","KIWI","KM","KN","KOELN","KOMATSU","KOSHER","KP","KPMG","KPN","KR","KRD","KRED","KUOKGROUP","KW","KY","KYOTO","KZ","LA","LACAIXA","LAMBORGHINI","LAMER","LAND","LANDROVER","LANXESS","LASALLE","LAT","LATINO","LATROBE","LAW","LAWYER","LB","LC","LDS","LEASE","LECLERC","LEFRAK","LEGAL","LEGO","LEXUS","LGBT","LI","LIDL","LIFE","LIFEINSURANCE","LIFESTYLE","LIGHTING","LIKE","LILLY","LIMITED","LIMO","LINCOLN","LINK","LIVE","LIVING","LK","LLC","LLP","LOAN","LOANS","LOCKER","LOCUS","LOL","LONDON","LOTTE","LOTTO","LOVE","LPL","LPLFINANCIAL","LR","LS","LT","LTD","LTDA","LU","LUNDBECK","LUXE","LUXURY","LV","LY","MA","MADRID","MAIF","MAISON","MAKEUP","MAN","MANAGEMENT","MANGO","MAP","MARKET","MARKETING","MARKETS","MARRIOTT","MARSHALLS","MATTEL","MBA","MC","MCKINSEY","MD","ME","MED","MEDIA","MEET","MELBOURNE","MEME","MEMORIAL","MEN","MENU","MERCKMSD","MG","MH","MIAMI","MICROSOFT","MIL","MINI","MINT","MIT","MITSUBISHI","MK","ML","MLB","MLS","MM","MMA","MN","MO","MOBI","MOBILE","MODA","MOE","MOI","MOM","MONASH","MONEY","MONSTER","MORMON","MORTGAGE","MOSCOW","MOTO","MOTORCYCLES","MOV","MOVIE","MP","MQ","MR","MS","MSD","MT","MTN","MTR","MU","MUSEUM","MUSIC","MV","MW","MX","MY","MZ","NA","NAB","NAGOYA","NAME","NAVY","NBA","NC","NE","NEC","NET","NETBANK","NETFLIX","NETWORK","NEUSTAR","NEW","NEWS","NEXT","NEXTDIRECT","NEXUS","NF","NFL","NG","NGO","NHK","NI","NICO","NIKE","NIKON","NINJA","NISSAN","NISSAY","NL","NO","NOKIA","NORTON","NOW","NOWRUZ","NOWTV","NP","NR","NRA","NRW","NTT","NU","NYC","NZ","OBI","OBSERVER","OFFICE","OKINAWA","OLAYAN","OLAYANGROUP","OLLO","OM","OMEGA","ONE","ONG","ONL","ONLINE","OOO","OPEN","ORACLE","ORANGE","ORG","ORGANIC","ORIGINS","OSAKA","OTSUKA","OTT","OVH","PA","PAGE","PANASONIC","PARIS","PARS","PARTNERS","PARTS","PARTY","PAY","PCCW","PE","PET","PF","PFIZER","PG","PH","PHARMACY","PHD","PHILIPS","PHONE","PHOTO","PHOTOGRAPHY","PHOTOS","PHYSIO","PICS","PICTET","PICTURES","PID","PIN","PING","PINK","PIONEER","PIZZA","PK","PL","PLACE","PLAY","PLAYSTATION","PLUMBING","PLUS","PM","PN","PNC","POHL","POKER","POLITIE","PORN","POST","PR","PRAXI","PRESS","PRIME","PRO","PROD","PRODUCTIONS","PROF","PROGRESSIVE","PROMO","PROPERTIES","PROPERTY","PROTECTION","PRU","PRUDENTIAL","PS","PT","PUB","PW","PWC","PY","QA","QPON","QUEBEC","QUEST","RACING","RADIO","RE","READ","REALESTATE","REALTOR","REALTY","RECIPES","RED","REDUMBRELLA","REHAB","REISE","REISEN","REIT","RELIANCE","REN","RENT","RENTALS","REPAIR","REPORT","REPUBLICAN","REST","RESTAURANT","REVIEW","REVIEWS","REXROTH","RICH","RICHARDLI","RICOH","RIL","RIO","RIP","RO","ROCKS","RODEO","ROGERS","ROOM","RS","RSVP","RU","RUGBY","RUHR","RUN","RW","RWE","RYUKYU","SA","SAARLAND","SAFE","SAFETY","SAKURA","SALE","SALON","SAMSCLUB","SAMSUNG","SANDVIK","SANDVIKCOROMANT","SANOFI","SAP","SARL","SAS","SAVE","SAXO","SB","SBI","SBS","SC","SCB","SCHAEFFLER","SCHMIDT","SCHOLARSHIPS","SCHOOL","SCHULE","SCHWARZ","SCIENCE","SCOT","SD","SE","SEARCH","SEAT","SECURE","SECURITY","SEEK","SELECT","SENER","SERVICES","SEVEN","SEW","SEX","SEXY","SFR","SG","SH","SHANGRILA","SHARP","SHELL","SHIA","SHIKSHA","SHOES","SHOP","SHOPPING","SHOUJI","SHOW","SI","SILK","SINA","SINGLES","SITE","SJ","SK","SKI","SKIN","SKY","SKYPE","SL","SLING","SM","SMART","SMILE","SN","SNCF","SO","SOCCER","SOCIAL","SOFTBANK","SOFTWARE","SOHU","SOLAR","SOLUTIONS","SONG","SONY","SOY","SPA","SPACE","SPORT","SPOT","SR","SRL","SS","ST","STADA","STAPLES","STAR","STATEBANK","STATEFARM","STC","STCGROUP","STOCKHOLM","STORAGE","STORE","STREAM","STUDIO","STUDY","STYLE","SU","SUCKS","SUPPLIES","SUPPLY","SUPPORT","SURF","SURGERY","SUZUKI","SV","SWATCH","SWISS","SX","SY","SYDNEY","SYSTEMS","SZ","TAB","TAIPEI","TALK","TAOBAO","TARGET","TATAMOTORS","TATAR","TATTOO","TAX","TAXI","TC","TCI","TD","TDK","TEAM","TECH","TECHNOLOGY","TEL","TEMASEK","TENNIS","TEVA","TF","TG","TH","THD","THEATER","THEATRE","TIAA","TICKETS","TIENDA","TIPS","TIRES","TIROL","TJ","TJMAXX","TJX","TK","TKMAXX","TL","TM","TMALL","TN","TO","TODAY","TOKYO","TOOLS","TOP","TORAY","TOSHIBA","TOTAL","TOURS","TOWN","TOYOTA","TOYS","TR","TRADE","TRADING","TRAINING","TRAVEL","TRAVELERS","TRAVELERSINSURANCE","TRUST","TRV","TT","TUBE","TUI","TUNES","TUSHU","TV","TVS","TW","TZ","UA","UBANK","UBS","UG","UK","UNICOM","UNIVERSITY","UNO","UOL","UPS","US","UY","UZ","VA","VACATIONS","VANA","VANGUARD","VC","VE","VEGAS","VENTURES","VERISIGN","VERSICHERUNG","VET","VG","VI","VIAJES","VIDEO","VIG","VIKING","VILLAS","VIN","VIP","VIRGIN","VISA","VISION","VIVA","VIVO","VLAANDEREN","VN","VODKA","VOLVO","VOTE","VOTING","VOTO","VOYAGE","VU","WALES","WALMART","WALTER","WANG","WANGGOU","WATCH","WATCHES","WEATHER","WEATHERCHANNEL","WEBCAM","WEBER","WEBSITE","WED","WEDDING","WEIBO","WEIR","WF","WHOSWHO","WIEN","WIKI","WILLIAMHILL","WIN","WINDOWS","WINE","WINNERS","WME","WOLTERSKLUWER","WOODSIDE","WORK","WORKS","WORLD","WOW","WS","WTC","WTF","XBOX","XEROX","XIHUAN","XIN","XN--11B4C3D","XN--1CK2E1B","XN--1QQW23A","XN--2SCRJ9C","XN--30RR7Y","XN--3BST00M","XN--3DS443G","XN--3E0B707E","XN--3HCRJ9C","XN--3PXU8K","XN--42C2D9A","XN--45BR5CYL","XN--45BRJ9C","XN--45Q11C","XN--4DBRK0CE","XN--4GBRIM","XN--54B7FTA0CC","XN--55QW42G","XN--55QX5D","XN--5SU34J936BGSG","XN--5TZM5G","XN--6FRZ82G","XN--6QQ986B3XL","XN--80ADXHKS","XN--80AO21A","XN--80AQECDR1A","XN--80ASEHDB","XN--80ASWG","XN--8Y0A063A","XN--90A3AC","XN--90AE","XN--90AIS","XN--9DBQ2A","XN--9ET52U","XN--9KRT00A","XN--B4W605FERD","XN--BCK1B9A5DRE4C","XN--C1AVG","XN--C2BR7G","XN--CCK2B3B","XN--CCKWCXETD","XN--CG4BKI","XN--CLCHC0EA0B2G2A9GCD","XN--CZR694B","XN--CZRS0T","XN--CZRU2D","XN--D1ACJ3B","XN--D1ALF","XN--E1A4C","XN--ECKVDTC9D","XN--EFVY88H","XN--FCT429K","XN--FHBEI","XN--FIQ228C5HS","XN--FIQ64B","XN--FIQS8S","XN--FIQZ9S","XN--FJQ720A","XN--FLW351E","XN--FPCRJ9C3D","XN--FZC2C9E2C","XN--FZYS8D69UVGM","XN--G2XX48C","XN--GCKR3F0F","XN--GECRJ9C","XN--GK3AT1E","XN--H2BREG3EVE","XN--H2BRJ9C","XN--H2BRJ9C8C","XN--HXT814E","XN--I1B6B1A6A2E","XN--IMR513N","XN--IO0A7I","XN--J1AEF","XN--J1AMH","XN--J6W193G","XN--JLQ480N2RG","XN--JVR189M","XN--KCRX77D1X4A","XN--KPRW13D","XN--KPRY57D","XN--KPUT3I","XN--L1ACC","XN--LGBBAT1AD8J","XN--MGB9AWBF","XN--MGBA3A3EJT","XN--MGBA3A4F16A","XN--MGBA7C0BBN0A","XN--MGBAAM7A8H","XN--MGBAB2BD","XN--MGBAH1A3HJKRD","XN--MGBAI9AZGQP6J","XN--MGBAYH7GPA","XN--MGBBH1A","XN--MGBBH1A71E","XN--MGBC0A9AZCG","XN--MGBCA7DZDO","XN--MGBCPQ6GPA1A","XN--MGBERP4A5D4AR","XN--MGBGU82A","XN--MGBI4ECEXP","XN--MGBPL2FH","XN--MGBT3DHD","XN--MGBTX2B","XN--MGBX4CD0AB","XN--MIX891F","XN--MK1BU44C","XN--MXTQ1M","XN--NGBC5AZD","XN--NGBE9E0A","XN--NGBRX","XN--NODE","XN--NQV7F","XN--NQV7FS00EMA","XN--NYQY26A","XN--O3CW4H","XN--OGBPF8FL","XN--OTU796D","XN--P1ACF","XN--P1AI","XN--PGBS0DH","XN--PSSY2U","XN--Q7CE6A","XN--Q9JYB4C","XN--QCKA1PMC","XN--QXA6A","XN--QXAM","XN--RHQV96G","XN--ROVU88B","XN--RVC1E0AM3E","XN--S9BRJ9C","XN--SES554G","XN--T60B56A","XN--TCKWE","XN--TIQ49XQYJ","XN--UNUP4Y","XN--VERMGENSBERATER-CTB","XN--VERMGENSBERATUNG-PWB","XN--VHQUV","XN--VUQ861B","XN--W4R85EL8FHU5DNRA","XN--W4RS40L","XN--WGBH1C","XN--WGBL6A","XN--XHQ521B","XN--XKC2AL3HYE2A","XN--XKC2DL3A5EE0H","XN--Y9A3AQ","XN--YFRO4I67O","XN--YGBI2AMMX","XN--ZFR164B","XXX","XYZ","YACHTS","YAHOO","YAMAXUN","YANDEX","YE","YODOBASHI","YOGA","YOKOHAMA","YOU","YOUTUBE","YT","YUN","ZA","ZAPPOS","ZARA","ZERO","ZIP","ZM","ZONE","ZUERICH","ZW"]),
3451
+ "agents.md":content$6,"bootstrap.md":content$5,"plan-files.md":content$2,"tessl-system-prompt.md":content$1,"docs/spec-driven-development.md":content$4,"docs/spec-format.md":content$3},KNOWLEDGE_ONLY_FILES={"usage-specs.md":content};function installFullFrameworkFiles(e){return installFrameworkFiles(e,FRAMEWORK_FILES)}function installKnowledgeFrameworkFiles(e){return installFrameworkFiles(e,KNOWLEDGE_ONLY_FILES)}function installFrameworkFiles(e,t){const r=path__default.resolve(e,DEFAULT_TESSL_DIRS.frameworkDirectory);fs$4.existsSync(r)&&fs$4.rmSync(r,{recursive:!0});const n=[];for(const[i,s]of Object.entries(t)){const t=path__default.join(r,i);fs$4.existsSync(path__default.dirname(t))||fs$4.mkdirSync(path__default.dirname(t),{recursive:!0}),fs$4.writeFileSync(t,s.trim());const o=path__default.relative(e,t);n.push(o)}return n}function getExistingFrameworkType(e){return hasHooks(e,DEFAULT_HOOKS)?"full":hasHooks(e,KNOWLEDGE_ONLY_HOOKS)?"spec-registry":void 0}
3452
+ const DEFAULT_KNOWLEDGE_MD_CONTENT="# Knowledge Index\n\n";function ensureKnowledgeMd(e){const t=path__default.resolve(e,KNOWLEDGE_MD_FILENAME$1);if(!fs$4.existsSync(t)){fs$4.writeFileSync(t,DEFAULT_KNOWLEDGE_MD_CONTENT);return[path__default.relative(e,t)]}return[]}class Initializer{#wi;constructor(e){this.#wi=e}addTesslFiles(){const e=[],t=process.cwd(),r=ensureTesslJsonSync(t,{name:path__default.basename(t)});r&&e.push(r);const n=path__default.resolve(t,CONFIG_DIR_NAME);fs__default.mkdirSync(n,{recursive:!0});const i=path__default.resolve(n,".gitignore"),s=path__default.relative(n,DEFAULT_TESSL_DIRS.tmpDirectory);fs__default.writeFileSync(i,`${s}/${EOL}${USAGE_SPEC_DIR_NAME}/${EOL}`),e.push(`${CONFIG_DIR_NAME}/.gitignore`),removeHooks(t,KNOWLEDGE_ONLY_HOOKS);const o=installFullFrameworkFiles(t);e.push(...o);const a=ensureAgentsMd(t);e.push(...a);const c=ensureAgentsMdHooks(t);e.push(...c);const u=ensureKnowledgeMd(t);return e.push(...u),[...new Set(e)]}initializeProject(e,t){
3453
+ const r=Date.now();let n=0,i=!0;try{const e=this.addTesslFiles();return n=Date.now()-r,{filesCreated:e,durationMs:n}}catch(e){throw n=Date.now()-r,i=!1,e}finally{this.#wi.init({success:i,isReinitializing:e,type:"full",...t?{previousType:t}:{}})}}}class KnowledgeInitializer{#wi;constructor(e){this.#wi=e}addTesslFiles(){const e=[],t=process.cwd(),r=ensureTesslJsonSync(t,{name:path__default.basename(t)});r&&e.push(r);const n=path__default.resolve(t,CONFIG_DIR_NAME);fs__default.mkdirSync(n,{recursive:!0});const i=path__default.resolve(n,".gitignore"),s=path__default.relative(n,DEFAULT_TESSL_DIRS.tmpDirectory);fs__default.writeFileSync(i,`${s}/${EOL}${USAGE_SPEC_DIR_NAME}/${EOL}`),e.push(`${CONFIG_DIR_NAME}/.gitignore`),removeHooks(t,DEFAULT_HOOKS);const o=installKnowledgeFrameworkFiles(t);e.push(...o);const a=ensureAgentsMd(t);e.push(...a);const c=ensureAgentsMdHooks(t,KNOWLEDGE_ONLY_HOOKS);e.push(...c);const u=ensureKnowledgeMd(t);return e.push(...u),[...new Set(e)]}
3454
+ initializeProject(e,t){const r=Date.now();let n=0,i=!0;try{const e=this.addTesslFiles();return n=Date.now()-r,{filesCreated:e,durationMs:n}}catch(e){throw n=Date.now()-r,i=!1,e}finally{this.#wi.init({success:i,isReinitializing:e,type:"spec-registry",...t?{previousType:t}:{}})}}}function formatDuration(e){if(e<1e3)return`${e} ms`;const t=e/1e3;if(t<60)return`${t.toFixed(1)} sec`;const r=Math.floor(t/60),n=Math.round(t%60);return`${r} min${n>0?` ${n} sec`:""}`}function FilesCreated({base:e,filepaths:t}){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:t.map(t=>jsxRuntimeExports.jsxs(Text,{children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"+"})," ",e&&jsxRuntimeExports.jsxs(Text,{dimColor:!0,children:["/"!==e?e:"","/"]}),t]},t))})}function Indicator({isSelected:e=!1}){return React.createElement(Box,{marginRight:1},e?React.createElement(Text,{color:"blue"},figures.pointer):React.createElement(Text,null," "))}function Item({isSelected:e=!1,label:t}){
3455
+ return reactExports.createElement(Text,{color:e?"blue":void 0},t)}function toRotated(e,t){if(!Array.isArray(e))throw new TypeError(`Expected an array, got \`${typeof e}\`.`);if(!Number.isSafeInteger(t))throw new TypeError(`The \`steps\` parameter must be an integer, got ${t}.`);const{length:r}=e;if(0===r)return[...e];const n=(t%r+r)%r;return 0===n?[...e]:[...e.slice(-n),...e.slice(0,-n)]}function SelectInput({items:e=[],isFocused:t=!0,initialIndex:r=0,indicatorComponent:n=Indicator,itemComponent:i=Item,limit:s,onSelect:o,onHighlight:a}){const c="number"==typeof s&&e.length>s,u=c?Math.min(s,e.length):e.length,l=u-1,[d,p]=reactExports.useState(r>l?l-r:0),[h,A]=reactExports.useState(r?r>l?l:r:0),f=reactExports.useRef(e);reactExports.useEffect(()=>{isDeepStrictEqual(f.current.map(e=>e.value),e.map(e=>e.value))||(p(0),A(0)),f.current=e},[e]),useInput(reactExports.useCallback((t,r)=>{if("k"===t||r.upArrow){const t=(c?u:e.length)-1,r=0===h,n=r?d+1:d,i=r?c?h:t:h-1;p(n),A(i)
3456
+ ;const s=c?toRotated(e,n).slice(0,u):e;"function"==typeof a&&a(s[i])}if("j"===t||r.downArrow){const t=h===(c?u:e.length)-1,r=t?d-1:d,n=t?c?h:0:h+1;p(r),A(n);const i=c?toRotated(e,r).slice(0,u):e;"function"==typeof a&&a(i[n])}if(/^[1-9]$/.test(t)){const r=Number.parseInt(t,10)-1,n=c?toRotated(e,d).slice(0,u):e;if(r>=0&&r<n.length){const e=n[r];e&&o?.(e)}}if(r.return){const t=c?toRotated(e,d).slice(0,u):e;"function"==typeof o&&o(t[h])}},[c,u,d,h,e,o,a]),{isActive:t});const g=c?toRotated(e,d).slice(0,u):e;return React.createElement(Box,{flexDirection:"column"},g.map((e,t)=>{const r=t===h;return React.createElement(Box,{key:e.key??e.value},React.createElement(n,{isSelected:r}),React.createElement(i,{...e,isSelected:r}))}))}function _optionalChain$p(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)
3457
+ }return r}function SelectItem({items:e,selectColor:t,onSelect:r}){return jsxRuntimeExports.jsx(SelectInput,{items:e,onSelect:r,indicatorComponent:({isSelected:e})=>jsxRuntimeExports.jsx(Box,{marginRight:1,children:e?jsxRuntimeExports.jsx(Text,{color:t,children:figures.pointer}):jsxRuntimeExports.jsx(Text,{children:" "})}),itemComponent:({label:r,isSelected:n})=>{const i=_optionalChain$p([e,"access",e=>e.find,"call",e=>e(e=>e.label===r),"optionalAccess",e=>e.description]);return jsxRuntimeExports.jsxs(Box,{gap:1,children:[jsxRuntimeExports.jsx(Text,{underline:n,color:n?t:void 0,children:r}),n&&!!i&&jsxRuntimeExports.jsxs(Text,{dimColor:!0,children:["(",i,")"]})]})}})}function SpiffyBox({children:e,marginTop:t=1,borderColor:r="white",borderDimColor:n=!0}){return jsxRuntimeExports.jsx(Box,{flexDirection:"column",gap:1,borderStyle:"round",borderColor:r,borderDimColor:n,paddingX:1,paddingY:1,width:84,marginTop:t,children:e})}function ReinitPrompt({onSubmit:e}){const{exit:t}=useApp()
3458
+ ;return jsxRuntimeExports.jsxs(SpiffyBox,{marginTop:0,borderColor:"yellow",children:[jsxRuntimeExports.jsxs(Box,{paddingLeft:2,flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Tessl is already initialized in this directory. Reinitialize?"}),jsxRuntimeExports.jsx(Text,{children:"This will overwrite your existing config, update Spec Authoring files, and add Tessl references to AGENTS.md."})]}),jsxRuntimeExports.jsx(SelectItem,{items:[{label:"Reinitialize",value:!0},{label:"Cancel",value:!1}],onSelect:r=>{e(r.value),t()},selectColor:"yellow"})]})}function UpgradeToFullFrameworkPrompt({onSubmit:e}){const{exit:t}=useApp();return jsxRuntimeExports.jsxs(SpiffyBox,{marginTop:0,borderColor:"blue",children:[jsxRuntimeExports.jsxs(Box,{paddingLeft:2,flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Continuing will upgrade this project to add Tessl Spec Authoring context"}),jsxRuntimeExports.jsx(Text,{
3459
+ children:"Now that you are logged into Tessl, you have access to Spec Authoring commands, in addition to the Spec Registry."}),jsxRuntimeExports.jsx(Text,{children:"Continuing will replace your Tessl framework files and Tessl-managed sections of your AGENTS.md file. Your own content will be preserved."})]}),jsxRuntimeExports.jsx(SelectItem,{items:[{label:"Continue",value:!0},{label:"Cancel",value:!1}],onSelect:r=>{e(r.value),t()},selectColor:"blue"})]})}function DowngradeToKnowledgeOnlyFrameworkPrompt({onSubmit:e}){const{exit:t}=useApp();return jsxRuntimeExports.jsxs(SpiffyBox,{marginTop:0,borderColor:"red",children:[jsxRuntimeExports.jsxs(Box,{paddingLeft:2,flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Continuing will downgrade this project by removing Tessl Spec Authoring context"}),jsxRuntimeExports.jsx(Text,{
3460
+ children:"Because you are not currently logged into Tessl, if you continue your project will remain able to use the Spec Registry, but Spec Authoring commands may not behave as expected upon logging back in."}),jsxRuntimeExports.jsxs(Text,{children:["To refresh the Spec Authoring context, first re-authenticate with"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl login"})," before running"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl init"}),"."]}),jsxRuntimeExports.jsx(Text,{children:"Continuing now will replace your Tessl framework files and Tessl-managed sections of your AGENTS.md file. Your own content will be preserved."})]}),jsxRuntimeExports.jsx(SelectItem,{items:[{label:"Continue",value:!0},{label:"Cancel",value:!1}],onSelect:r=>{e(r.value),t()},selectColor:"red"})]})}function BigTessl(){return jsxRuntimeExports.jsx(Text,{
3461
+ children:"\n ______ ______ ______ ______ __\n /\\__ _\\/\\ ___\\ /\\ ___\\ /\\ ___\\ /\\ \\\n \\/_/\\ \\/\\ \\ __\\ \\ \\___ \\\\ \\___ \\\\ \\ \\____\n \\ \\_\\ \\ \\_____\\\\/\\_____\\\\/\\_____\\\\ \\_____\\\n \\/_/ \\/_____/ \\/_____/ \\/_____/ \\/_____/\n"})}const initCommand=new Command$1({name:"init",summary:"Initialize Tessl in the current directory. Sets up Tessl context and provides a default AI agent integration via AGENTS.md.",requiresConfig:!1,requiresLogin:!1,flags:{force:{type:Boolean,short:"f",description:"Automatically accept the reinitialization prompt"}},handler:async({monitoring:{analytics:e},args:t,isInteractive:r,globalConfigDir:n})=>{const{force:i}=t,s=process.cwd();return await isAuthed({basePath:n})?fullInit(s,i,r,e):knowledgeOnlyInit(s,i,r,e)}});async function fullInit(e,t,r,n){const i=await hasTesslJson(e),s=path__default.join(DEFAULT_TESSL_DIRS.frameworkDirectory,"usage-specs.md"),o=fs$4.existsSync(s);if(i&&!t){let e=!1
3462
+ ;if(!r)throw new ExpectedError("Tessl is already initialized in this directory. Re-run with --force if you want to initialize anyway in non-interactive mode.");if(o){const{clear:t,waitUntilExit:r}=render(jsxRuntimeExports.jsx(UpgradeToFullFrameworkPrompt,{onSubmit:r=>{e=r,t()}}));await r()}else{const{clear:t,waitUntilExit:r}=render(jsxRuntimeExports.jsx(ReinitPrompt,{onSubmit:r=>{e=r,t()}}));await r()}if(!e)throw new ExpectedError("Initialization cancelled.")}const a=new Initializer(n);return await render(jsxRuntimeExports.jsx(Init,{initializer:a,isReinitializing:i,existingFramework:getExistingFrameworkType(e),nextSteps:jsxRuntimeExports.jsx(NextSteps,{})})).waitUntilExit(),SUCCESS}async function knowledgeOnlyInit(e,t,r,n){const i=await hasTesslJson(e),s=path__default.join(DEFAULT_TESSL_DIRS.frameworkDirectory,"agents.md"),o=fs$4.existsSync(s);if(i&&!t){let e=!1
3463
+ ;if(!r)throw new ExpectedError("Tessl is already initialized in this directory. Re-run with --force if you want to initialize anyway in non-interactive mode.");if(o){const{clear:t,waitUntilExit:r}=render(jsxRuntimeExports.jsx(DowngradeToKnowledgeOnlyFrameworkPrompt,{onSubmit:r=>{e=r,t()}}));await r()}else{const{clear:t,waitUntilExit:r}=render(jsxRuntimeExports.jsx(ReinitPrompt,{onSubmit:r=>{e=r,t()}}));await r()}if(!e)throw new ExpectedError("Initialization cancelled.")}const a=new KnowledgeInitializer(n);return await render(jsxRuntimeExports.jsx(Init,{initializer:a,isReinitializing:i,existingFramework:getExistingFrameworkType(e),nextSteps:jsxRuntimeExports.jsx(KnowledgeOnlyNextSteps,{})})).waitUntilExit(),SUCCESS}function Init({initializer:e,isReinitializing:t,existingFramework:r,nextSteps:n}){const{exit:i}=useApp(),[s,o]=reactExports.useState([]),[a,c]=reactExports.useState();return reactExports.useEffect(()=>{try{const{filesCreated:n,durationMs:s}=e.initializeProject(t,r);o(n),c(s),
3464
+ setTimeout(i,100)}catch(e){throw new Error("Failed to initialize a new project.")}},[i,e,o,t,r]),jsxRuntimeExports.jsxs(Box,{flexDirection:"column",gap:1,children:[jsxRuntimeExports.jsx(BigTessl,{}),jsxRuntimeExports.jsxs(Box,{flexDirection:"column",children:[jsxRuntimeExports.jsx(Text,{children:"Initializing Tessl..."}),s.length>0&&jsxRuntimeExports.jsx(FilesCreated,{base:process.cwd(),filepaths:s})]}),void 0!==a&&jsxRuntimeExports.jsxs(Box,{flexDirection:"row",gap:1,children:[jsxRuntimeExports.jsx(Text,{color:"green",children:"Project initialized"}),jsxRuntimeExports.jsx(Text,{color:"green",bold:!0,children:figures.tick}),jsxRuntimeExports.jsx(Text,{dimColor:!0,children:formatDuration(a)})]}),n]})}function NextSteps(){return jsxRuntimeExports.jsxs(Box,{flexDirection:"column",marginBottom:2,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Next steps"}),jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"Wondering what to do next? Here's some tips:"}),jsxRuntimeExports.jsxs(Text,{
3465
+ children:["• Auto-configure your preferred coding agent to use Tessl with"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl setup agent"})]}),jsxRuntimeExports.jsxs(Text,{children:["• Review the quickstart guide with ",jsxRuntimeExports.jsx(CommandText,{children:"tessl help"})]}),jsxRuntimeExports.jsxs(Text,{children:["• Create a spec with ",jsxRuntimeExports.jsx(CommandText,{children:"tessl create"})]})]})}function KnowledgeOnlyNextSteps(){return jsxRuntimeExports.jsxs(Box,{flexDirection:"column",marginBottom:2,children:[jsxRuntimeExports.jsx(Text,{bold:!0,children:"Next steps"}),jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"Wondering what to do next? Here's some tips:"}),jsxRuntimeExports.jsxs(Text,{children:["• Auto-configure your preferred coding agent to use Tessl with"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl setup agent"})]}),jsxRuntimeExports.jsxs(Text,{children:["• Review the quickstart guide with ",jsxRuntimeExports.jsx(CommandText,{
3466
+ children:"tessl help"})]}),jsxRuntimeExports.jsxs(Text,{children:["• Use ",jsxRuntimeExports.jsx(CommandText,{children:"tessl registry search"})," to find usage specs for your project, and"," ",jsxRuntimeExports.jsx(CommandText,{children:"tessl registry install"})," to add them"]})]})}var tail={},hasRequiredTail;function requireTail(){if(hasRequiredTail)return tail;hasRequiredTail=1;let e=require$$0$g,t=fs$4,r=path__default;class n{info(){}error(){}}class i extends e.EventEmitter{constructor(i,s={}){super(),this.filename=i,this.absPath=r.dirname(this.filename),this.separator=void 0!==s.separator?s.separator:/[\r]{0,1}\n/,this.fsWatchOptions=s.fsWatchOptions||{},this.follow=null==s.follow||s.follow,this.logger=s.logger||new n,this.useWatchFile=s.useWatchFile||!1,this.flushAtEOF=s.flushAtEOF||!1,this.encoding=s.encoding||"utf-8";const o=s.fromBeginning||!1;this.nLines=s.nLines||void 0,this.logger.info("Tail starting..."),this.logger.info(`filename: ${this.filename}`),
3467
+ this.logger.info(`encoding: ${this.encoding}`);try{t.accessSync(this.filename,t.constants.F_OK)}catch(e){if("ENOENT"==e.code)throw e}let a;if(this.buffer="",this.internalDispatcher=new e.EventEmitter,this.queue=[],this.isWatching=!1,this.pos=0,this.internalDispatcher.on("next",()=>{this.readBlock()}),this.logger.info(`fromBeginning: ${o}`),a=o||this.nLines<=0?0:void 0!==this.nLines?this.getPositionAtNthLine(this.nLines):this.latestPosition(),void 0===a)throw new Error("Tail can't initialize.");const c=o||null!=this.nLines;try{this.watch(a,c)}catch(e){this.logger.error(`watch for ${this.filename} failed: ${e}`),this.emit("error",`watch for ${this.filename} failed: ${e}`)}}getIndexOfLastLine(e){const t=(e,t)=>{const r=e.match(t);if(null!==r)return r[r.length-1]},r=t(e,this.separator);if(!r)return null;const n=e.lastIndexOf(r);let i;if(e.endsWith(r)){const s=e.substring(0,n),o=t(s,this.separator);if(!o)return null;const a=s.lastIndexOf(o);i=e.substring(a+o.length,n+r.length)
3468
+ }else i=e.substring(n+r.length);return e.lastIndexOf(i)}getPositionAtNthLine(e){const{size:r}=t.statSync(this.filename);if(0===r)return 0;const n=t.openSync(this.filename,"r");let i=r;const s=Math.min(1024,r),o=[];let a="";for(;o.length<e;){if(i-=s,i<0)return 0;const r=Buffer.alloc(s),c=t.readSync(n,r,0,s,i),u=r.subarray(0,c);a=Buffer.from(u).toString(this.encoding)+a;let l=this.getIndexOfLastLine(a);for(;null!==l&&o.length<e;){const e=a.substring(l);o.push(Buffer.byteLength(e)),a=a.substring(0,l),l=this.getIndexOfLastLine(a)}}return t.closeSync(n),r-o.reduce((e,t)=>e+t,0)}latestPosition(){try{return t.statSync(this.filename).size}catch(e){throw this.logger.error(`size check for ${this.filename} failed: ${e}`),this.emit("error",`size check for ${this.filename} failed: ${e}`),e}}readBlock(){if(this.queue.length>=1){const e=this.queue[0];if(e.end>e.start){let r=t.createReadStream(this.filename,{start:e.start,end:e.end-1,encoding:this.encoding});r.on("error",e=>{
3469
+ this.logger.error(`Tail error: ${e}`),this.emit("error",e)}),r.on("end",()=>{this.queue.shift(),this.queue.length>0&&this.internalDispatcher.emit("next"),this.flushAtEOF&&this.buffer.length>0&&(this.emit("line",this.buffer),this.buffer="")}),r.on("data",e=>{if(null===this.separator)this.emit("line",e);else{this.buffer+=e;let t=this.buffer.split(this.separator);this.buffer=t.pop();for(const e of t)this.emit("line",e)}})}}}change(){let e=this.latestPosition();e<this.currentCursorPos?this.currentCursorPos=e:e>this.currentCursorPos&&(this.queue.push({start:this.currentCursorPos,end:e}),this.currentCursorPos=e,1==this.queue.length&&this.internalDispatcher.emit("next"))}watch(e,r){this.isWatching||(this.logger.info(`filesystem.watch present? ${null!=t.watch}`),this.logger.info(`useWatchFile: ${this.useWatchFile}`),this.isWatching=!0,this.currentCursorPos=e,r&&this.change(),!this.useWatchFile&&t.watch?(this.logger.info("watch strategy: watch"),
3470
+ this.watcher=t.watch(this.filename,this.fsWatchOptions,(e,t)=>{this.watchEvent(e,t)})):(this.logger.info("watch strategy: watchFile"),t.watchFile(this.filename,this.fsWatchOptions,(e,t)=>{this.watchFileEvent(e,t)})))}rename(e){void 0!==e&&e===this.filename||(this.unwatch(),this.follow?(this.filename=r.join(this.absPath,e),this.rewatchId=setTimeout(()=>{try{this.watch(this.currentCursorPos)}catch(e){this.logger.error(`'rename' event for ${this.filename}. File not available anymore.`),this.emit("error",e)}},1e3)):(this.logger.error(`'rename' event for ${this.filename}. File not available anymore.`),this.emit("error",`'rename' event for ${this.filename}. File not available anymore.`)))}watchEvent(e,t){try{"change"===e?this.change():"rename"===e&&this.rename(t)}catch(e){this.logger.error(`watchEvent for ${this.filename} failed: ${e}`),this.emit("error",`watchEvent for ${this.filename} failed: ${e}`)}}watchFileEvent(e,t){e.size>t.size&&(this.currentCursorPos=e.size,this.queue.push({
3471
+ start:t.size,end:e.size}),1==this.queue.length&&this.internalDispatcher.emit("next"))}unwatch(){this.watcher?this.watcher.close():t.unwatchFile(this.filename),this.rewatchId&&(clearTimeout(this.rewatchId),this.rewatchId=void 0),this.isWatching=!1,this.queue=[],this.logger&&this.logger.info(`Unwatch ${this.filename}`)}}return tail.Tail=i,tail}var tailExports=requireTail(),lib$4={},assert$2={exports:{}},assertError,hasRequiredAssertError,stringify$1,hasRequiredStringify$1,hasRequiredAssert,reach,hasRequiredReach;function requireAssertError(){return hasRequiredAssertError?assertError:(hasRequiredAssertError=1,assertError=class extends Error{name="AssertError";constructor(e,t){super(e||"Unknown error"),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,t)}})}function requireStringify$1(){return hasRequiredStringify$1||(hasRequiredStringify$1=1,stringify$1=function(...e){try{return JSON.stringify(...e)}catch(e){return"[Cannot display object: "+e.message+"]"}}),
3472
+ stringify$1}function requireAssert(){if(hasRequiredAssert)return assert$2.exports;hasRequiredAssert=1;const e=requireAssertError(),t=requireStringify$1(),r=assert$2.exports=function(n,...i){if(n)return;if(1===i.length&&i[0]instanceof Error)throw i[0];const s=i.filter(e=>""!==e).map(e=>"string"==typeof e?e:e instanceof Error?e.message:t(e));throw new e(s.join(" "),r)};return assert$2.exports}function requireReach(){if(hasRequiredReach)return reach;hasRequiredReach=1;const e=requireAssert(),t={};return reach=function(r,n,i){if(!1===n||null==n)return r;"string"==typeof(i=i||{})&&(i={separator:i});const s=Array.isArray(n);e(!s||!i.separator,"Separator option is not valid for array-based chain");const o=s?n:n.split(i.separator||".");let a=r;for(let r=0;r<o.length;++r){let s=o[r];const c=i.iterables&&t.iterables(a);if(Array.isArray(a)||"set"===c){const e=Number(s);Number.isInteger(e)&&(s=e<0?a.length+e:e)}if(!a||"function"==typeof a&&!1===i.functions||!c&&void 0===a[s]){
3473
+ e(!i.strict||r+1===o.length,"Missing segment",s,"in reach path ",n),e("object"==typeof a||!0===i.functions||"function"!=typeof a,"Invalid segment",s,"in reach path ",n),a=i.default;break}a=c?"set"===c?[...a][s]:a.get(s):a[s]}return a},t.iterables=function(e){return e instanceof Set?"set":e instanceof Map?"map":void 0},reach}var types$1={exports:{}},hasRequiredTypes$1;function requireTypes$1(){return hasRequiredTypes$1||(hasRequiredTypes$1=1,function(e,t){const r={};t=e.exports={array:Array.prototype,buffer:Buffer&&Buffer.prototype,date:Date.prototype,error:Error.prototype,generic:Object.prototype,map:Map.prototype,promise:Promise.prototype,regex:RegExp.prototype,set:Set.prototype,url:URL.prototype,weakMap:WeakMap.prototype,weakSet:WeakSet.prototype},r.typeMap=new Map([["[object Error]",t.error],["[object Map]",t.map],["[object Promise]",t.promise],["[object Set]",t.set],["[object URL]",t.url],["[object WeakMap]",t.weakMap],["[object WeakSet]",t.weakSet]]),
3474
+ t.getInternalProto=function(e){if(Array.isArray(e))return t.array;if(Buffer&&e instanceof Buffer)return t.buffer;if(e instanceof Date)return t.date;if(e instanceof RegExp)return t.regex;if(e instanceof Error)return t.error;const n=Object.prototype.toString.call(e);return r.typeMap.get(n)||t.generic}}(types$1,types$1.exports)),types$1.exports}var utils$1={},hasRequiredUtils$1,clone,hasRequiredClone,merge$2,hasRequiredMerge$2,applyToDefaults,hasRequiredApplyToDefaults,bench,hasRequiredBench,ignore,hasRequiredIgnore,block,hasRequiredBlock,deepEqual,hasRequiredDeepEqual,escapeRegex$1,hasRequiredEscapeRegex,contain,hasRequiredContain,escapeHeaderAttribute,hasRequiredEscapeHeaderAttribute,escapeHtml,hasRequiredEscapeHtml,escapeJson,hasRequiredEscapeJson,flatten,hasRequiredFlatten,intersect,hasRequiredIntersect,isPromise$1,hasRequiredIsPromise$1,once,hasRequiredOnce,reachTemplate,hasRequiredReachTemplate,wait,hasRequiredWait,hasRequiredLib$4;function requireUtils$1(){
3475
+ return hasRequiredUtils$1||(hasRequiredUtils$1=1,utils$1.keys=function(e,t={}){return!1!==t.symbols?Reflect.ownKeys(e):Object.getOwnPropertyNames(e)}),utils$1}function requireClone(){if(hasRequiredClone)return clone;hasRequiredClone=1;const e=requireReach(),t=requireTypes$1(),r=requireUtils$1(),n={needsProtoHack:new Set([t.set,t.map,t.weakSet,t.weakMap]),structuredCloneExists:"function"==typeof structuredClone};return clone=n.clone=function(e,i={},s=null){if("object"!=typeof e||null===e)return e;let o=n.clone,a=s;if(i.shallow){if(!0!==i.shallow)return n.cloneWithShallow(e,i);o=e=>e}else if(a){const t=a.get(e);if(t)return t}else a=new Map;const c=t.getInternalProto(e);switch(c){case t.buffer:return Buffer?.from(e);case t.date:return new Date(e.getTime());case t.regex:case t.url:return new c.constructor(e)}const u=n.base(e,c,i);if(u===e)return e;if(a&&a.set(e,u),c===t.set)for(const t of e)u.add(o(t,i,a));else if(c===t.map)for(const[t,r]of e)u.set(t,o(r,i,a));const l=r.keys(e,i)
3476
+ ;for(const r of l){if("__proto__"===r)continue;if(c===t.array&&"length"===r){u.length=e.length;continue}if(n.structuredCloneExists&&c===t.error&&"stack"===r)continue;const s=Object.getOwnPropertyDescriptor(e,r);s?s.get||s.set?Object.defineProperty(u,r,s):s.enumerable?u[r]=o(e[r],i,a):Object.defineProperty(u,r,{enumerable:!1,writable:!0,configurable:!0,value:o(e[r],i,a)}):Object.defineProperty(u,r,{enumerable:!0,writable:!0,configurable:!0,value:o(e[r],i,a)})}return u},n.cloneWithShallow=function(t,r){const i=r.shallow;(r=Object.assign({},r)).shallow=!1;const s=new Map;for(const r of i){const n=e(t,r);"object"!=typeof n&&"function"!=typeof n||s.set(n,n)}return n.clone(t,r,s)},n.base=function(e,r,i){if(!1===i.prototype)return n.needsProtoHack.has(r)?new r.constructor:r===t.array?[]:{};const s=Object.getPrototypeOf(e);if(s&&s.isImmutable)return e;if(r===t.array){const e=[];return s!==r&&Object.setPrototypeOf(e,s),e}
3477
+ if(r===t.error&&n.structuredCloneExists&&(s===r||Error.isPrototypeOf(s.constructor))){const t=structuredClone(e);return Object.getPrototypeOf(t)!==s&&Object.setPrototypeOf(t,s),t}if(n.needsProtoHack.has(r)){const e=new s.constructor;return s!==r&&Object.setPrototypeOf(e,s),e}return Object.create(s)},clone}function requireMerge$2(){if(hasRequiredMerge$2)return merge$2;hasRequiredMerge$2=1;const e=requireAssert(),t=requireClone(),r=requireUtils$1(),n={};return merge$2=n.merge=function(i,s,o){if(e(i&&"object"==typeof i,"Invalid target value: must be an object"),e(null==s||"object"==typeof s,"Invalid source value: must be null, undefined, or an object"),!s)return i;if(o=Object.assign({nullOverride:!0,mergeArrays:!0},o),Array.isArray(s)){e(Array.isArray(i),"Cannot merge array onto an object"),o.mergeArrays||(i.length=0);for(let e=0;e<s.length;++e)i.push(t(s[e],{symbols:o.symbols}));return i}const a=r.keys(s,o);for(let e=0;e<a.length;++e){const r=a[e]
3478
+ ;if("__proto__"===r||!Object.prototype.propertyIsEnumerable.call(s,r))continue;const c=s[r];if(c&&"object"==typeof c){if(i[r]===c)continue;!i[r]||"object"!=typeof i[r]||Array.isArray(i[r])!==Array.isArray(c)||c instanceof Date||Buffer&&Buffer.isBuffer(c)||c instanceof RegExp?i[r]=t(c,{symbols:o.symbols}):n.merge(i[r],c,o)}else(null!=c||o.nullOverride)&&(i[r]=c)}return i},merge$2}function requireApplyToDefaults(){if(hasRequiredApplyToDefaults)return applyToDefaults;hasRequiredApplyToDefaults=1;const e=requireAssert(),t=requireClone(),r=requireMerge$2(),n=requireReach(),i={};return applyToDefaults=function(n,s,o={}){if(e(n&&"object"==typeof n,"Invalid defaults value: must be an object"),e(!s||!0===s||"object"==typeof s,"Invalid source value: must be true, falsy or an object"),e("object"==typeof o,"Invalid options: must be an object"),!s)return null;if(o.shallow)return i.applyToDefaultsWithShallow(n,s,o);const a=t(n);if(!0===s)return a;const c=void 0!==o.nullOverride&&o.nullOverride
3479
+ ;return r(a,s,{nullOverride:c,mergeArrays:!1})},i.applyToDefaultsWithShallow=function(s,o,a){const c=a.shallow;e(Array.isArray(c),"Invalid keys");const u=new Map,l=!0===o?null:new Set;for(let e of c){e=Array.isArray(e)?e:e.split(".");const t=n(s,e);t&&"object"==typeof t?u.set(t,l&&n(o,e)||t):l&&l.add(e)}const d=t(s,{},u);if(!l)return d;for(const e of l)i.reachCopy(d,o,e);const p=void 0!==a.nullOverride&&a.nullOverride;return r(d,o,{nullOverride:p,mergeArrays:!1})},i.reachCopy=function(e,t,r){for(const e of r){if(!(e in t))return;const r=t[e];if("object"!=typeof r||null===r)return;t=r}const n=t;let i=e;for(let e=0;e<r.length-1;++e){const t=r[e];"object"!=typeof i[t]&&(i[t]={}),i=i[t]}i[r[r.length-1]]=n},applyToDefaults}function requireBench(){if(hasRequiredBench)return bench;hasRequiredBench=1;const e={};return bench=e.Bench=class{constructor(){this.ts=0,this.reset()}reset(){this.ts=e.Bench.now()}elapsed(){return e.Bench.now()-this.ts}static now(){const e=process.hrtime()
3480
+ ;return 1e3*e[0]+e[1]/1e6}}}function requireIgnore(){return hasRequiredIgnore?ignore:(hasRequiredIgnore=1,ignore=function(){})}function requireBlock(){if(hasRequiredBlock)return block;hasRequiredBlock=1;const e=requireIgnore();return block=function(){return new Promise(e)}}function requireDeepEqual(){if(hasRequiredDeepEqual)return deepEqual;hasRequiredDeepEqual=1;const e=requireTypes$1(),t={mismatched:null};return deepEqual=function(e,r,n){return n=Object.assign({prototype:!0},n),!!t.isDeepEqual(e,r,n,[])},t.isDeepEqual=function(r,n,i,s){if(r===n)return 0!==r||1/r==1/n;const o=typeof r;if(o!==typeof n)return!1;if(null===r||null===n)return!1;if("function"===o){if(!i.deepFunction||r.toString()!==n.toString())return!1}else if("object"!==o)return r!=r&&n!=n;const a=t.getSharedType(r,n,!!i.prototype);switch(a){case e.buffer:return Buffer&&Buffer.prototype.equals.call(r,n);case e.promise:return r===n;case e.regex:case e.url:return r.toString()===n.toString();case t.mismatched:return!1}
3481
+ for(let e=s.length-1;e>=0;--e)if(s[e].isSame(r,n))return!0;s.push(new t.SeenEntry(r,n));try{return!!t.isDeepEqualObj(a,r,n,i,s)}finally{s.pop()}},t.getSharedType=function(r,n,i){if(i)return Object.getPrototypeOf(r)!==Object.getPrototypeOf(n)?t.mismatched:e.getInternalProto(r);const s=e.getInternalProto(r);return s!==e.getInternalProto(n)?t.mismatched:s},t.valueOf=function(e){const t=e.valueOf;if(void 0===t)return e;try{return t.call(e)}catch(e){return e}},t.hasOwnEnumerableProperty=function(e,t){return Object.prototype.propertyIsEnumerable.call(e,t)},t.isSetSimpleEqual=function(e,t){for(const r of Set.prototype.values.call(e))if(!Set.prototype.has.call(t,r))return!1;return!0},t.isDeepEqualObj=function(r,n,i,s,o){const{isDeepEqual:a,valueOf:c,hasOwnEnumerableProperty:u}=t,{keys:l,getOwnPropertySymbols:d}=Object;if(r===e.array){if(!s.part){if(n.length!==i.length)return!1;for(let e=0;e<n.length;++e)if(!a(n[e],i[e],s,o))return!1;return!0}
3482
+ for(const e of n)for(const t of i)if(a(e,t,s,o))return!0}else if(r===e.set){if(n.size!==i.size)return!1;if(!t.isSetSimpleEqual(n,i)){const e=new Set(Set.prototype.values.call(i));for(const t of Set.prototype.values.call(n)){if(e.delete(t))continue;let r=!1;for(const n of e)if(a(t,n,s,o)){e.delete(n),r=!0;break}if(!r)return!1}}}else if(r===e.map){if(n.size!==i.size)return!1;for(const[e,t]of Map.prototype.entries.call(n)){if(void 0===t&&!Map.prototype.has.call(i,e))return!1;if(!a(t,Map.prototype.get.call(i,e),s,o))return!1}}else if(r===e.error&&(n.name!==i.name||n.message!==i.message))return!1;const p=c(n),h=c(i);if((n!==p||i!==h)&&!a(p,h,s,o))return!1;const A=l(n);if(!s.part&&A.length!==l(i).length&&!s.skip)return!1;let f=0;for(const e of A)if(s.skip&&s.skip.includes(e))void 0===i[e]&&++f;else{if(!u(i,e))return!1;if(!a(n[e],i[e],s,o))return!1}if(!s.part&&A.length-f!==l(i).length)return!1;if(!1!==s.symbols){const e=d(n),t=new Set(d(i));for(const r of e){
3483
+ if(!s.skip?.includes(r))if(u(n,r)){if(!u(i,r))return!1;if(!a(n[r],i[r],s,o))return!1}else if(u(i,r))return!1;t.delete(r)}for(const e of t)if(u(i,e))return!1}return!0},t.SeenEntry=class{constructor(e,t){this.obj=e,this.ref=t}isSame(e,t){return this.obj===e&&this.ref===t}},deepEqual}function requireEscapeRegex(){return hasRequiredEscapeRegex||(hasRequiredEscapeRegex=1,escapeRegex$1=function(e){return e.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g,"\\$&")}),escapeRegex$1}function requireContain(){if(hasRequiredContain)return contain;hasRequiredContain=1;const e=requireAssert(),t=requireDeepEqual(),r=requireEscapeRegex(),n=requireUtils$1(),i={};return contain=function(t,r,n={}){return"object"!=typeof r&&(r=[r]),e(!Array.isArray(r)||r.length,"Values array cannot be empty"),"string"==typeof t?i.string(t,r,n):Array.isArray(t)?i.array(t,r,n):(e("object"==typeof t,"Reference must be string or an object"),i.object(t,r,n))},i.array=function(e,t,r){if(Array.isArray(t)||(t=[t]),
3484
+ !e.length)return!1;if(r.only&&r.once&&e.length!==t.length)return!1;let n;const s=new Map;for(const e of t)if(r.deep&&e&&"object"==typeof e){n=n??i.compare(r);let t=!1;for(const[r,i]of s.entries())if(n(r,e)){++i.allowed,t=!0;break}t||s.set(e,{allowed:1,hits:0})}else{const t=s.get(e);t?++t.allowed:s.set(e,{allowed:1,hits:0})}let o=0;for(const t of e){let e;if(r.deep&&t&&"object"==typeof t){n=n??i.compare(r);for(const[r,i]of s.entries())if(n(r,t)){e=i;break}}else e=s.get(t);if(e&&(++e.hits,++o,r.once&&e.hits>e.allowed))return!1}if(r.only&&o!==e.length)return!1;for(const e of s.values())if(e.hits!==e.allowed&&e.hits<e.allowed&&!r.part)return!1;return!!o},i.object=function(t,r,s){e(void 0===s.once,"Cannot use option once with object");const o=n.keys(t,s);if(!o.length)return!1;if(Array.isArray(r))return i.array(o,r,s);const a=Object.getOwnPropertySymbols(r).filter(e=>r.propertyIsEnumerable(e)),c=[...Object.keys(r),...a],u=i.compare(s),l=new Set(c);for(const e of o)if(l.has(e)){
3485
+ if(!u(r[e],t[e]))return!1;l.delete(e)}else if(s.only)return!1;return!l.size||!!s.part&&l.size<c.length},i.string=function(t,n,i){if(""===t)return 1===n.length&&""===n[0]||!i.once&&!n.some(e=>""!==e);const s=new Map,o=[];for(const t of n)if(e("string"==typeof t,"Cannot compare string reference to non-string value"),t){const e=s.get(t);e?++e.allowed:(s.set(t,{allowed:1,hits:0}),o.push(r(t)))}else if(i.once||i.only)return!1;if(!o.length)return!0;const a=new RegExp(`(${o.join("|")})`,"g"),c=t.replace(a,(e,t)=>(++s.get(t).hits,""));if(i.only&&c)return!1;let u=!1;for(const e of s.values())if(e.hits&&(u=!0),e.hits!==e.allowed){if(e.hits<e.allowed&&!i.part)return!1;if(i.once)return!1}return!!u},i.compare=function(e){if(!e.deep)return i.shallow;const r=void 0!==e.only,n=void 0!==e.part,s={prototype:r?e.only:!!n&&!e.part,part:r?!e.only:!!n&&e.part};return(e,r)=>t(e,r,s)},i.shallow=function(e,t){return e===t},contain}function requireEscapeHeaderAttribute(){
3486
+ if(hasRequiredEscapeHeaderAttribute)return escapeHeaderAttribute;hasRequiredEscapeHeaderAttribute=1;const e=requireAssert();return escapeHeaderAttribute=function(t){return e(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(t),"Bad attribute value ("+t+")"),t.replace(/\\/g,"\\\\").replace(/\"/g,'\\"')},escapeHeaderAttribute}function requireEscapeHtml(){if(hasRequiredEscapeHtml)return escapeHtml;hasRequiredEscapeHtml=1;const e={};return escapeHtml=function(t){if(!t)return"";let r="";for(let n=0;n<t.length;++n){const i=t.charCodeAt(n);e.isSafe(i)?r+=t[n]:r+=e.escapeHtmlChar(i)}return r},e.escapeHtmlChar=function(t){const r=e.namedHtml.get(t);if(r)return r;if(t>=256)return"&#"+t+";";return`&#x${t.toString(16).padStart(2,"0")};`},e.isSafe=function(t){return e.safeCharCodes.has(t)},e.namedHtml=new Map([[38,"&amp;"],[60,"&lt;"],[62,"&gt;"],[34,"&quot;"],[160,"&nbsp;"],[162,"&cent;"],[163,"&pound;"],[164,"&curren;"],[169,"&copy;"],[174,"&reg;"]]),e.safeCharCodes=function(){
3487
+ const e=new Set;for(let t=32;t<123;++t)(t>=97||t>=65&&t<=90||t>=48&&t<=57||32===t||46===t||44===t||45===t||58===t||95===t)&&e.add(t);return e}(),escapeHtml}function requireEscapeJson(){if(hasRequiredEscapeJson)return escapeJson;hasRequiredEscapeJson=1;const e={};return escapeJson=function(t){return t?t.replace(/[<>&\u2028\u2029]/g,e.escape):""},e.escape=function(t){return e.replacements.get(t)},e.replacements=new Map([["<","\\u003c"],[">","\\u003e"],["&","\\u0026"],["\u2028","\\u2028"],["\u2029","\\u2029"]]),escapeJson}function requireFlatten(){if(hasRequiredFlatten)return flatten;hasRequiredFlatten=1;const e={};return flatten=e.flatten=function(t,r){const n=r||[];for(const r of t)Array.isArray(r)?e.flatten(r,n):n.push(r);return n},flatten}function requireIntersect(){if(hasRequiredIntersect)return intersect;hasRequiredIntersect=1;const e={};return intersect=function(t,r,n={}){if(!t||!r)return n.first?null:[];const i=[],s=Array.isArray(t)?new Set(t):t,o=new Set
3488
+ ;for(const t of r)if(e.has(s,t)&&!o.has(t)){if(n.first)return t;i.push(t),o.add(t)}return n.first?null:i},e.has=function(e,t){return"function"==typeof e.has?e.has(t):void 0!==e[t]},intersect}function requireIsPromise$1(){return hasRequiredIsPromise$1?isPromise$1:(hasRequiredIsPromise$1=1,isPromise$1=function(e){return"function"==typeof e?.then})}function requireOnce(){if(hasRequiredOnce)return once;hasRequiredOnce=1;const e=Symbol("wrapped");return once=function(t){if(t[e])return t;let r=!1;const n=function(...e){r||(r=!0,t(...e))};return n[e]=!0,n},once}function requireReachTemplate(){if(hasRequiredReachTemplate)return reachTemplate;hasRequiredReachTemplate=1;const e=requireReach();return reachTemplate=function(t,r,n){return r.replace(/{([^{}]+)}/g,(r,i)=>e(t,i,n)??"")},reachTemplate}function requireWait(){if(hasRequiredWait)return wait;hasRequiredWait=1;const e=2**31-1;return wait=function(t,r,n){if("bigint"==typeof t&&(t=Number(t)),t>=Number.MAX_SAFE_INTEGER&&(t=1/0),
3489
+ "number"!=typeof t&&void 0!==t)throw new TypeError("Timeout must be a number or bigint");return new Promise(i=>{const s=n?n.setTimeout:setTimeout,o=()=>{const n=Math.min(t,e);t-=n,s(()=>t>0?o():i(r),n)};t!==1/0&&o()})},wait}function requireLib$4(){return hasRequiredLib$4||(hasRequiredLib$4=1,lib$4.applyToDefaults=requireApplyToDefaults(),lib$4.assert=requireAssert(),lib$4.AssertError=requireAssertError(),lib$4.Bench=requireBench(),lib$4.block=requireBlock(),lib$4.clone=requireClone(),lib$4.contain=requireContain(),lib$4.deepEqual=requireDeepEqual(),lib$4.escapeHeaderAttribute=requireEscapeHeaderAttribute(),lib$4.escapeHtml=requireEscapeHtml(),lib$4.escapeJson=requireEscapeJson(),lib$4.escapeRegex=requireEscapeRegex(),lib$4.flatten=requireFlatten(),lib$4.ignore=requireIgnore(),lib$4.intersect=requireIntersect(),lib$4.isPromise=requireIsPromise$1(),lib$4.merge=requireMerge$2(),lib$4.once=requireOnce(),lib$4.reach=requireReach(),lib$4.reachTemplate=requireReachTemplate(),
3490
+ lib$4.stringify=requireStringify$1(),lib$4.wait=requireWait()),lib$4}var cache={},common={},version$1="18.0.1",require$$1$1={version:version$1},schemas={},hasRequiredSchemas;function requireSchemas(){if(hasRequiredSchemas)return schemas;hasRequiredSchemas=1;const e=requireLib(),t={};return t.wrap=e.string().min(1).max(2).allow(!1),schemas.preferences=e.object({allowUnknown:e.boolean(),abortEarly:e.boolean(),artifacts:e.boolean(),cache:e.boolean(),context:e.object(),convert:e.boolean(),dateFormat:e.valid("date","iso","string","time","utc"),debug:e.boolean(),errors:{escapeHtml:e.boolean(),label:e.valid("path","key",!1),language:[e.string(),e.object().ref()],render:e.boolean(),stack:e.boolean(),wrap:{label:t.wrap,array:t.wrap,string:t.wrap}},externals:e.boolean(),messages:e.object(),noDefaults:e.boolean(),nonEnumerables:e.boolean(),presence:e.valid("required","optional","forbidden"),skipFunctions:e.boolean(),stripUnknown:e.object({arrays:e.boolean(),objects:e.boolean()
3491
+ }).or("arrays","objects").allow(!0,!1),warnings:e.boolean()}).strict(),t.nameRx=/^[a-zA-Z0-9]\w*$/,t.rule=e.object({alias:e.array().items(e.string().pattern(t.nameRx)).single(),args:e.array().items(e.string(),e.object({name:e.string().pattern(t.nameRx).required(),ref:e.boolean(),assert:e.alternatives([e.function(),e.object().schema()]).conditional("ref",{is:!0,then:e.required()}),normalize:e.function(),message:e.string().when("assert",{is:e.function(),then:e.required()})})),convert:e.boolean(),manifest:e.boolean(),method:e.function().allow(!1),multi:e.boolean(),validate:e.function()}),schemas.extension=e.object({type:e.alternatives([e.string(),e.object().regex()]).required(),args:e.function(),cast:e.object().pattern(t.nameRx,e.object({from:e.function().maxArity(1).required(),to:e.function().minArity(1).maxArity(2).required()})),base:e.object().schema().when("type",{is:e.object().regex(),then:e.forbidden()}),coerce:[e.function().maxArity(3),e.object({
3492
+ method:e.function().maxArity(3).required(),from:e.array().items(e.string()).single()})],flags:e.object().pattern(t.nameRx,e.object({setter:e.string(),default:e.any()})),manifest:{build:e.function().arity(2)},messages:[e.object(),e.string()],modifiers:e.object().pattern(t.nameRx,e.function().minArity(1).maxArity(2)),overrides:e.object().pattern(t.nameRx,e.function()),prepare:e.function().maxArity(3),rebuild:e.function().arity(1),rules:e.object().pattern(t.nameRx,t.rule),terms:e.object().pattern(t.nameRx,e.object({init:e.array().allow(null).required(),manifest:e.object().pattern(/.+/,[e.valid("schema","single"),e.object({mapped:e.object({from:e.string().required(),to:e.string().required()}).required()})])})),validate:e.function().maxArity(3)}).strict(),schemas.extensions=e.array().items(e.object(),e.function().arity(1)).strict(),t.desc={buffer:e.object({buffer:e.string()}),func:e.object({function:e.function().required(),options:{literal:!0}}),override:e.object({override:!0}),
3493
+ ref:e.object({ref:e.object({type:e.valid("value","global","local"),path:e.array().required(),separator:e.string().length(1).allow(!1),ancestor:e.number().min(0).integer().allow("root"),map:e.array().items(e.array().length(2)).min(1),adjust:e.function(),iterables:e.boolean(),in:e.boolean(),render:e.boolean()}).required()}),regex:e.object({regex:e.string().min(3)}),special:e.object({special:e.valid("deep").required()}),template:e.object({template:e.string().required(),options:e.object()}),value:e.object({value:e.alternatives([e.object(),e.array()]).required()})},t.desc.entity=e.alternatives([e.array().items(e.link("...")),e.boolean(),e.function(),e.number(),e.string(),t.desc.buffer,t.desc.func,t.desc.ref,t.desc.regex,t.desc.special,t.desc.template,t.desc.value,e.link("/")]),t.desc.values=e.array().items(null,e.boolean(),e.function(),e.number().allow(1/0,-1/0),e.string().allow(""),e.symbol(),t.desc.buffer,t.desc.func,t.desc.override,t.desc.ref,t.desc.regex,t.desc.template,t.desc.value),
3494
+ t.desc.messages=e.object().pattern(/.+/,[e.string(),t.desc.template,e.object().pattern(/.+/,[e.string(),t.desc.template])]),schemas.description=e.object({type:e.string().required(),flags:e.object({cast:e.string(),default:e.any(),description:e.string(),empty:e.link("/"),failover:t.desc.entity,id:e.string(),label:e.string(),only:!0,presence:["optional","required","forbidden"],result:["raw","strip"],strip:e.boolean(),unit:e.string()}).unknown(),preferences:{allowUnknown:e.boolean(),abortEarly:e.boolean(),artifacts:e.boolean(),cache:e.boolean(),convert:e.boolean(),dateFormat:["date","iso","string","time","utc"],errors:{escapeHtml:e.boolean(),label:["path","key"],language:[e.string(),t.desc.ref],wrap:{label:t.wrap,array:t.wrap}},externals:e.boolean(),messages:t.desc.messages,noDefaults:e.boolean(),nonEnumerables:e.boolean(),presence:["required","optional","forbidden"],skipFunctions:e.boolean(),stripUnknown:e.object({arrays:e.boolean(),objects:e.boolean()
3495
+ }).or("arrays","objects").allow(!0,!1),warnings:e.boolean()},allow:t.desc.values,invalid:t.desc.values,rules:e.array().min(1).items({name:e.string().required(),args:e.object().min(1),keep:e.boolean(),message:[e.string(),t.desc.messages],warn:e.boolean()}),keys:e.object().pattern(/.*/,e.link("/")),link:t.desc.ref}).pattern(/^[a-z]\w*$/,e.any()),schemas}var messages={},template$1={exports:{}},lib$3={},hasRequiredLib$3;function requireLib$3(){return hasRequiredLib$3||(hasRequiredLib$3=1,function(e){const t={operators:["!","^","*","/","%","+","-","<","<=",">",">=","==","!=","&&","||","??"],operatorCharacters:["!","^","*","/","%","+","-","<","=",">","&","|","?"],operatorsOrder:[["^"],["*","/","%"],["+","-"],["<","<=",">",">="],["==","!="],["&&"],["||","??"]],operatorsPrefix:["!","n"],literals:{'"':'"',"`":"`","'":"'","[":"]"},numberRx:/^(?:[0-9]*(\.[0-9]*)?){1}$/,tokenRx:/^[\w\$\#\.\@\:\{\}]+$/,symbol:Symbol("formula"),settings:Symbol("settings")};e.Parser=class{constructor(e,r={}){
3496
+ if(!r[t.settings]&&r.constants)for(const e in r.constants){const t=r.constants[e];if(null!==t&&!["boolean","number","string"].includes(typeof t))throw new Error(`Formula constant ${e} contains invalid ${typeof t} value type`)}this.settings=r[t.settings]?r:Object.assign({[t.settings]:!0,constants:{},functions:{}},r),this.single=null,this._parts=null,this._parse(e)}_parse(r){let n=[],i="",s=0,o=!1;const a=r=>{if(s)throw new Error("Formula missing closing parenthesis");const a=n.length?n[n.length-1]:null;if(o||i||r){if(a&&"reference"===a.type&&")"===r)return a.type="function",a.value=this._subFormula(i,a.value),void(i="");if(")"===r){const t=new e.Parser(i,this.settings);n.push({type:"segment",value:t})}else if(o){if("]"===o)return n.push({type:"reference",value:i}),void(i="");n.push({type:"literal",value:i})}else if(t.operatorCharacters.includes(i))a&&"operator"===a.type&&t.operators.includes(a.value+i)?a.value+=i:n.push({type:"operator",value:i});else if(i.match(t.numberRx))n.push({
3497
+ type:"constant",value:parseFloat(i)});else if(void 0!==this.settings.constants[i])n.push({type:"constant",value:this.settings.constants[i]});else{if(!i.match(t.tokenRx))throw new Error(`Formula contains invalid token: ${i}`);n.push({type:"reference",value:i})}i=""}};for(const e of r)o?e===o?(a(),o=!1):i+=e:s?"("===e?(i+=e,++s):")"===e?(--s,s?i+=e:a(e)):i+=e:e in t.literals?o=t.literals[e]:"("===e?(a(),++s):t.operatorCharacters.includes(e)?(a(),i=e,a()):" "!==e?i+=e:a();a(),n=n.map((e,t)=>"operator"!==e.type||"-"!==e.value||t&&"operator"!==n[t-1].type?e:{type:"operator",value:"n"});let c=!1;for(const e of n){if("operator"===e.type){if(t.operatorsPrefix.includes(e.value))continue;if(!c)throw new Error("Formula contains an operator in invalid position");if(!t.operators.includes(e.value))throw new Error(`Formula contains an unknown operator ${e.value}`)}else if(c)throw new Error("Formula missing expected operator");c=!c}if(!c)throw new Error("Formula contains invalid trailing operator")
3498
+ ;1===n.length&&["reference","literal","constant"].includes(n[0].type)&&(this.single={type:"reference"===n[0].type?"reference":"value",value:n[0].value}),this._parts=n.map(e=>{if("operator"===e.type)return t.operatorsPrefix.includes(e.value)?e:e.value;if("reference"!==e.type)return e.value;if(this.settings.tokenRx&&!this.settings.tokenRx.test(e.value))throw new Error(`Formula contains invalid reference ${e.value}`);return this.settings.reference?this.settings.reference(e.value):t.reference(e.value)})}_subFormula(r,n){const i=this.settings.functions[n];if("function"!=typeof i)throw new Error(`Formula contains unknown function ${n}`);let s=[];if(r){let e="",i=0,o=!1;const a=()=>{if(!e)throw new Error(`Formula contains function ${n} with invalid arguments ${r}`);s.push(e),e=""};for(let n=0;n<r.length;++n){const s=r[n];o?(e+=s,s===o&&(o=!1)):s in t.literals&&!i?(e+=s,o=t.literals[s]):","!==s||i?(e+=s,"("===s?++i:")"===s&&--i):a()}a()}return s=s.map(t=>new e.Parser(t,this.settings)),
3499
+ function(e){const t=[];for(const r of s)t.push(r.evaluate(e));return i.call(e,...t)}}evaluate(e){const r=this._parts.slice();for(let n=r.length-2;n>=0;--n){const i=r[n];if(i&&"operator"===i.type){const s=r[n+1];r.splice(n+1,1);const o=t.evaluate(s,e);r[n]=t.single(i.value,o)}}return t.operatorsOrder.forEach(n=>{for(let i=1;i<r.length-1;)if(n.includes(r[i])){const n=r[i],s=t.evaluate(r[i-1],e),o=t.evaluate(r[i+1],e);r.splice(i,2);const a=t.calculate(n,s,o);r[i-1]=0===a?0:a}else i+=2}),t.evaluate(r[0],e)}},e.Parser.prototype[t.symbol]=!0,t.reference=function(e){return function(t){return t&&void 0!==t[e]?t[e]:null}},t.evaluate=function(e,r){return null===e?null:"function"==typeof e?e(r):e[t.symbol]?e.evaluate(r):e},t.single=function(e,t){if("!"===e)return!t;const r=-t;return 0===r?0:r},t.calculate=function(e,r,n){if("??"===e)return t.exists(r)?r:n;if("string"==typeof r||"string"==typeof n){if("+"===e)return(r=t.exists(r)?r:"")+(n=t.exists(n)?n:"")}else switch(e){case"^":
3500
+ return Math.pow(r,n);case"*":return r*n;case"/":return r/n;case"%":return r%n;case"+":return r+n;case"-":return r-n}switch(e){case"<":return r<n;case"<=":return r<=n;case">":return r>n;case">=":return r>=n;case"==":return r===n;case"!=":return r!==n;case"&&":return r&&n;case"||":return r||n}return null},t.exists=function(e){return null!=e}}(lib$3)),lib$3}var errors$1={},annotate={},hasRequiredAnnotate,hasRequiredErrors$1;function requireAnnotate(){if(hasRequiredAnnotate)return annotate;hasRequiredAnnotate=1;const{clone:e}=requireLib$4(),t=requireCommon(),r={annotations:Symbol("annotations")};return annotate.error=function(n){if(!this._original||"object"!=typeof this._original)return this.details[0].message;const i=n?"":"",s=n?"":"",o=n?"":"",a=e(this._original);for(let e=this.details.length-1;e>=0;--e){const n=e+1,i=this.details[e],s=i.path;let o=a;for(let e=0;;++e){const a=s[e];if(t.isSchema(o)&&(o=o.clone()),!(e+1<s.length&&"string"!=typeof o[a])){
3501
+ const e=o[r.annotations]||{errors:{},missing:{}};o[r.annotations]=e;const t=a||i.context.key;void 0!==o[a]?(e.errors[t]=e.errors[t]||[],e.errors[t].push(n)):e.missing[t]=n;break}o=o[a]}}const c=/_\$key\$_([, \d]+)_\$end\$_"/g,u=/"_\$miss\$_([^|]+)\|(\d+)_\$end\$_": "__missing__"/g,l=/\s*"_\$idx\$_([, \d]+)_\$end\$_",?\n(.*)/g,d=/"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)]"/g;let p=r.safeStringify(a,2).replace(c,(e,t)=>`" ${i}[${t}]${o}`).replace(u,(e,t,r)=>`${s}"${t}"${o}${i} [${r}]: -- missing --${o}`).replace(l,(e,t,r)=>`\n${r} ${i}[${t}]${o}`).replace(d,(e,t)=>t);p=`${p}\n${i}`;for(let e=0;e<this.details.length;++e){p=`${p}\n[${e+1}] ${this.details[e].message}`}return p+=o,p},r.safeStringify=function(e,t){return JSON.stringify(e,r.serializer(),t)},r.serializer=function(){const e=[],t=[],n=(r,n)=>t[0]===n?"[Circular ~]":"[Circular ~."+e.slice(0,t.indexOf(n)).join(".")+"]";return function(i,s){if(t.length>0){const r=t.indexOf(this);~r?(t.length=r+1,e.length=r+1,
3502
+ e[r]=i):(t.push(this),e.push(i)),~t.indexOf(s)&&(s=n.call(this,i,s))}else t.push(s);if(s){const e=s[r.annotations];if(e){if(Array.isArray(s)){const t=[];for(let r=0;r<s.length;++r)e.errors[r]&&t.push(`_$idx$_${e.errors[r].sort().join(", ")}_$end$_`),t.push(s[r]);s=t}else{for(const t in e.errors)s[`${t}_$key$_${e.errors[t].sort().join(", ")}_$end$_`]=s[t],s[t]=void 0;for(const t in e.missing)s[`_$miss$_${t}|${e.missing[t]}_$end$_`]="__missing__"}return s}}return s===1/0||s===-1/0||Number.isNaN(s)||"function"==typeof s||"symbol"==typeof s?"["+s.toString()+"]":s}},annotate}function requireErrors$1(){return hasRequiredErrors$1||(hasRequiredErrors$1=1,function(e){const t=requireAnnotate(),r=requireCommon(),n=requireTemplate();e.Report=class{constructor(t,r,n,i,s,o,a){if(this.code=t,this.flags=i,this.messages=s,this.path=o.path,this.prefs=a,this.state=o,this.value=r,this.message=null,this.template=null,this.local=n||{},this.local.label=e.label(this.flags,this.state,this.prefs,this.messages),
3503
+ void 0===this.value||this.local.hasOwnProperty("value")||(this.local.value=this.value),this.path.length){const e=this.path[this.path.length-1];"object"!=typeof e&&(this.local.key=e)}}_setTemplate(e){if(this.template=e,!this.flags.label&&0===this.path.length){const e=this._template(this.template,"root");e&&(this.local.label=e)}}toString(){if(this.message)return this.message;const e=this.code;if(!this.prefs.errors.render)return this.code;const t=this._template(this.template)||this._template(this.prefs.messages)||this._template(this.messages);return void 0===t?`Error code "${e}" is not defined, your custom type is missing the correct messages definition`:(this.message=t.render(this.value,this.state,this.prefs,this.local,{errors:this.prefs.errors,messages:[this.prefs.messages,this.messages]}),this.prefs.errors.label||(this.message=this.message.replace(/^"" /,"").trim()),this.message)}_template(t,r){return e.template(this.value,t,r||this.code,this.state,this.prefs)}},e.path=function(e){
3504
+ let t="";for(const r of e)"object"!=typeof r&&("string"==typeof r?(t&&(t+="."),t+=r):t+=`[${r}]`);return t},e.template=function(e,t,i,s,o){if(!t)return;if(n.isTemplate(t))return"root"!==i?t:null;let a=o.errors.language;if(r.isResolvable(a)&&(a=a.resolve(e,s,o)),a&&t[a]){if(void 0!==t[a][i])return t[a][i];if(void 0!==t[a]["*"])return t[a]["*"]}return t[i]?t[i]:t["*"]},e.label=function(t,r,n,i){if(!n.errors.label)return"";if(t.label)return t.label;let s=r.path;"key"===n.errors.label&&r.path.length>1&&(s=r.path.slice(-1));const o=e.path(s);return o||(e.template(null,n.messages,"root",r,n)||i&&e.template(null,i,"root",r,n)||"value")},e.process=function(t,r,n){if(!t)return null;const{override:i,message:s,details:o}=e.details(t);if(i)return i;if(n.errors.stack)return new e.ValidationError(s,o,r);const a=Error.stackTraceLimit;Error.stackTraceLimit=0;const c=new e.ValidationError(s,o,r);return Error.stackTraceLimit=a,c},e.details=function(e,t={}){let r=[];const n=[];for(const i of e){
3505
+ if(i instanceof Error){if(!1!==t.override)return{override:i};const e=i.toString();r.push(e),n.push({message:e,type:"override",context:{error:i}});continue}const e=i.toString();r.push(e),n.push({message:e,path:i.path.filter(e=>"object"!=typeof e),type:i.code,context:i.local})}return r.length>1&&(r=[...new Set(r)]),{message:r.join(". "),details:n}},e.ValidationError=class extends Error{constructor(e,t,r){super(e),this._original=r,this.details=t}static isError(t){return t instanceof e.ValidationError}},e.ValidationError.prototype.isJoi=!0,e.ValidationError.prototype.name="ValidationError",e.ValidationError.prototype.annotate=t.error}(errors$1)),errors$1}var ref$2={},hasRequiredRef$1,hasRequiredTemplate,hasRequiredMessages,hasRequiredCommon,hasRequiredCache;function requireRef$1(){return hasRequiredRef$1||(hasRequiredRef$1=1,function(e){const{assert:t,clone:r,reach:n}=requireLib$4(),i=requireCommon();let s;const o={symbol:Symbol("ref"),defaults:{adjust:null,in:!1,iterables:null,map:null,
3506
+ separator:".",type:"value"}};e.create=function(e,r={}){t("string"==typeof e,"Invalid reference key:",e),i.assertOptions(r,["adjust","ancestor","in","iterables","map","prefix","render","separator"]),t(!r.prefix||"object"==typeof r.prefix,"options.prefix must be of type object");const n=Object.assign({},o.defaults,r);delete n.prefix;const s=n.separator,a=o.context(e,s,r.prefix);if(n.type=a.type,e=a.key,"value"===n.type)if(a.root&&(t(!s||e[0]!==s,"Cannot specify relative path with root prefix"),n.ancestor="root",e||(e=null)),s&&s===e)e=null,n.ancestor=0;else if(void 0!==n.ancestor)t(!s||!e||e[0]!==s,"Cannot combine prefix with ancestor option");else{const[t,r]=o.ancestor(e,s);r&&""===(e=e.slice(r))&&(e=null),n.ancestor=t}return n.path=s?null===e?[]:e.split(s):[e],new o.Ref(n)},e.in=function(t,r={}){return e.create(t,{...r,in:!0})},e.isRef=function(e){return!!e&&!!e[i.symbols.ref]},o.Ref=class{constructor(e){t("object"==typeof e,"Invalid reference construction"),
3507
+ i.assertOptions(e,["adjust","ancestor","in","iterables","map","path","render","separator","type","depth","key","root","display"]),t([!1,void 0].includes(e.separator)||"string"==typeof e.separator&&1===e.separator.length,"Invalid separator"),t(!e.adjust||"function"==typeof e.adjust,"options.adjust must be a function"),t(!e.map||Array.isArray(e.map),"options.map must be an array"),t(!e.map||!e.adjust,"Cannot set both map and adjust options"),Object.assign(this,o.defaults,e),t("value"===this.type||void 0===this.ancestor,"Non-value references cannot reference ancestors"),Array.isArray(this.map)&&(this.map=new Map(this.map)),this.depth=this.path.length,this.key=this.path.length?this.path.join(this.separator):null,this.root=this.path[0],this.updateDisplay()}resolve(e,r,n,i,s={}){return t(!this.in||s.in,"Invalid in() reference usage"),
3508
+ "global"===this.type?this._resolve(n.context,r,s):"local"===this.type?this._resolve(i,r,s):this.ancestor?"root"===this.ancestor?this._resolve(r.ancestors[r.ancestors.length-1],r,s):(t(this.ancestor<=r.ancestors.length,"Invalid reference exceeds the schema root:",this.display),this._resolve(r.ancestors[this.ancestor-1],r,s)):this._resolve(e,r,s)}_resolve(e,t,r){let i;if("value"===this.type&&t.mainstay.shadow&&!1!==r.shadow&&(i=t.mainstay.shadow.get(this.absolute(t))),void 0===i&&(i=n(e,this.path,{iterables:this.iterables,functions:!0})),this.adjust&&(i=this.adjust(i)),this.map){const e=this.map.get(i);void 0!==e&&(i=e)}return t.mainstay&&t.mainstay.tracer.resolve(t,this,i),i}toString(){return this.display}absolute(e){return[...e.path.slice(0,-this.ancestor),...this.path]}clone(){return new o.Ref(this)}describe(){const e={path:this.path};"value"!==this.type&&(e.type=this.type),"."!==this.separator&&(e.separator=this.separator),
3509
+ "value"===this.type&&1!==this.ancestor&&(e.ancestor=this.ancestor),this.map&&(e.map=[...this.map]);for(const t of["adjust","iterables","render"])null!==this[t]&&void 0!==this[t]&&(e[t]=this[t]);return!1!==this.in&&(e.in=!0),{ref:e}}updateDisplay(){const e=null!==this.key?this.key:"";if("value"!==this.type)return void(this.display=`ref:${this.type}:${e}`);if(!this.separator)return void(this.display=`ref:${e}`);if(!this.ancestor)return void(this.display=`ref:${this.separator}${e}`);if("root"===this.ancestor)return void(this.display=`ref:root:${e}`);if(1===this.ancestor)return void(this.display=`ref:${e||".."}`);const t=new Array(this.ancestor+1).fill(this.separator).join("");this.display=`ref:${t}${e||""}`}},o.Ref.prototype[i.symbols.ref]=!0,e.build=function(e){return"value"===(e=Object.assign({},o.defaults,e)).type&&void 0===e.ancestor&&(e.ancestor=1),new o.Ref(e)},o.context=function(e,t,r={}){if(e=e.trim(),r){const n=void 0===r.global?"$":r.global;if(n!==t&&e.startsWith(n))return{
3510
+ key:e.slice(n.length),type:"global"};const i=void 0===r.local?"#":r.local;if(i!==t&&e.startsWith(i))return{key:e.slice(i.length),type:"local"};const s=void 0===r.root?"/":r.root;if(s!==t&&e.startsWith(s))return{key:e.slice(s.length),type:"value",root:!0}}return{key:e,type:"value"}},o.ancestor=function(e,t){if(!t)return[1,0];if(e[0]!==t)return[1,0];if(e[1]!==t)return[0,1];let r=2;for(;e[r]===t;)++r;return[r-1,r]},e.toSibling=0,e.toParent=1,e.Manager=class{constructor(){this.refs=[]}register(t,r){if(t)if(r=void 0===r?e.toParent:r,Array.isArray(t))for(const e of t)this.register(e,r);else if(i.isSchema(t))for(const e of t._refs.refs)e.ancestor-r>=0&&this.refs.push({ancestor:e.ancestor-r,root:e.root});else e.isRef(t)&&"value"===t.type&&t.ancestor-r>=0&&this.refs.push({ancestor:t.ancestor-r,root:t.root}),s=s||requireTemplate(),s.isTemplate(t)&&this.register(t.refs(),r)}get length(){return this.refs.length}clone(){const t=new e.Manager;return t.refs=r(this.refs),t}reset(){this.refs=[]}
3511
+ roots(){return this.refs.filter(e=>!e.ancestor).map(e=>e.root)}}}(ref$2)),ref$2}function requireTemplate(){return hasRequiredTemplate||(hasRequiredTemplate=1,function(e){const{assert:t,clone:r,escapeHtml:n}=requireLib$4(),i=requireLib$3(),s=requireCommon(),o=requireErrors$1(),a=requireRef$1(),c={symbol:Symbol("template"),opens:new Array(1e3).join("\0"),closes:new Array(1e3).join(""),dateFormat:{date:Date.prototype.toDateString,iso:Date.prototype.toISOString,string:Date.prototype.toString,time:Date.prototype.toTimeString,utc:Date.prototype.toUTCString}};e.exports=c.Template=class{constructor(e,n){if(t("string"==typeof e,"Template source must be a string"),t(!e.includes("\0")&&!e.includes(""),"Template source cannot contain reserved control characters"),this.source=e,this.rendered=e,this._template=null,n){const{functions:e,...i}=n;this._settings=Object.keys(i).length?r(i):void 0,this._functions=e,
3512
+ this._functions&&(t(Object.keys(this._functions).every(e=>"string"==typeof e),"Functions keys must be strings"),t(Object.values(this._functions).every(e=>"function"==typeof e),"Functions values must be functions"))}else this._settings=void 0,this._functions=void 0;this._parse()}_parse(){if(!this.source.includes("{"))return;const e=c.encode(this.source),t=c.split(e);let r=!1;const n=[],i=t.shift();i&&n.push(i);for(const e of t){const t="{"!==e[0],i=t?"}":"}}",s=e.indexOf(i);if(-1===s||"{"===e[1]){n.push(`{${c.decode(e)}`);continue}let o=e.slice(t?0:1,s);const a=":"===o[0];a&&(o=o.slice(1));const u=this._ref(c.decode(o),{raw:t,wrapped:a});n.push(u),"string"!=typeof u&&(r=!0);const l=e.slice(s+i.length);l&&n.push(c.decode(l))}r?this._template=n:this.rendered=n.join("")}static date(e,t){return c.dateFormat[t.dateFormat].call(e)}describe(e={}){if(!this._settings&&e.compact)return this.source;const t={template:this.source};return this._settings&&(t.options=this._settings),
3513
+ this._functions&&(t.functions=this._functions),t}static build(e){return new c.Template(e.template,e.options||e.functions?{...e.options,functions:e.functions}:void 0)}isDynamic(){return!!this._template}static isTemplate(e){return!!e&&!!e[s.symbols.template]}refs(){if(!this._template)return;const e=[];for(const t of this._template)"string"!=typeof t&&e.push(...t.refs);return e}resolve(e,t,r,n){return this._template&&1===this._template.length?this._part(this._template[0],e,t,r,n,{}):this.render(e,t,r,n)}_part(e,...t){return e.ref?e.ref.resolve(...t):e.formula.evaluate(t)}render(e,t,r,i,s={}){if(!this.isDynamic())return this.rendered;const o=[];for(const a of this._template)if("string"==typeof a)o.push(a);else{const u=this._part(a,e,t,r,i,s),l=c.stringify(u,e,t,r,i,s);if(void 0!==l){const e=a.raw||!1===(s.errors&&s.errors.escapeHtml)?l:n(l);o.push(c.wrap(e,a.wrapped&&r.errors.wrap.label))}}return o.join("")}_ref(e,{raw:t,wrapped:r}){const n=[],s=e=>{const t=a.create(e,this._settings)
3514
+ ;return n.push(t),e=>{const r=t.resolve(...e);return void 0!==r?r:null}};try{const t=this._functions?{...c.functions,...this._functions}:c.functions;var o=new i.Parser(e,{reference:s,functions:t,constants:c.constants})}catch(t){throw t.message=`Invalid template variable "${e}" fails due to: ${t.message}`,t}if(o.single){if("reference"===o.single.type){const e=n[0];return{ref:e,raw:t,refs:n,wrapped:r||"local"===e.type&&"label"===e.key}}return c.stringify(o.single.value)}return{formula:o,raw:t,refs:n}}toString(){return this.source}},c.Template.prototype[s.symbols.template]=!0,c.Template.prototype.isImmutable=!0,c.encode=function(e){return e.replace(/\\(\{+)/g,(e,t)=>c.opens.slice(0,t.length)).replace(/\\(\}+)/g,(e,t)=>c.closes.slice(0,t.length))},c.decode=function(e){return e.replace(/\u0000/g,"{").replace(/\u0001/g,"}")},c.split=function(e){const t=[];let r="";for(let n=0;n<e.length;++n){const i=e[n];if("{"===i){let i="";for(;n+1<e.length&&"{"===e[n+1];)i+="{",++n;t.push(r),r=i}else r+=i
3515
+ }return t.push(r),t},c.wrap=function(e,t){return t?1===t.length?`${t}${e}${t}`:`${t[0]}${e}${t[1]}`:e},c.stringify=function(e,t,r,n,i,s={}){const o=typeof e,u=n&&n.errors&&n.errors.wrap||{};let l=!1;if(a.isRef(e)&&e.render&&(l=e.in,e=e.resolve(t,r,n,i,{in:e.in,...s})),null===e)return"null";if("string"===o)return c.wrap(e,s.arrayItems&&u.string);if("number"===o||"function"===o||"symbol"===o)return e.toString();if("object"!==o)return JSON.stringify(e);if(e instanceof Date)return c.Template.date(e,n);if(e instanceof Map){const t=[];for(const[r,n]of e.entries())t.push(`${r.toString()} -> ${n.toString()}`);e=t}if(!Array.isArray(e))return e.toString();const d=[];for(const o of e)d.push(c.stringify(o,t,r,n,i,{arrayItems:!0,...s}));return c.wrap(d.join(", "),!l&&u.array)},c.constants={true:!0,false:!1,null:null,second:1e3,minute:6e4,hour:36e5,day:864e5},c.functions={if:(e,t,r)=>e?t:r,
3516
+ length:e=>"string"==typeof e?e.length:e&&"object"==typeof e?Array.isArray(e)?e.length:Object.keys(e).length:null,msg(e){const[t,r,n,i,s]=this,a=s.messages;if(!a)return"";const c=o.template(t,a[0],e,r,n)||o.template(t,a[1],e,r,n);return c?c.render(t,r,n,i,s):""},number:e=>"number"==typeof e?e:"string"==typeof e?parseFloat(e):"boolean"==typeof e?e?1:0:e instanceof Date?e.getTime():null}}(template$1)),template$1.exports}function requireMessages(){return hasRequiredMessages||(hasRequiredMessages=1,function(e){const{assert:t,clone:r}=requireLib$4(),n=requireTemplate();e.compile=function(e,i){if("string"==typeof e)return t(!i,"Cannot set single message string"),new n(e);if(n.isTemplate(e))return t(!i,"Cannot set single message template"),e;t("object"==typeof e&&!Array.isArray(e),"Invalid message options"),i=i?r(i):{};for(let r in e){const s=e[r];if("root"===r||n.isTemplate(s)){i[r]=s;continue}if("string"==typeof s){i[r]=new n(s);continue}
3517
+ t("object"==typeof s&&!Array.isArray(s),"Invalid message for",r);const o=r;for(r in i[o]=i[o]||{},s){const e=s[r];"root"===r||n.isTemplate(e)?i[o][r]=e:(t("string"==typeof e,"Invalid message for",r,"in",o),i[o][r]=new n(e))}}return i},e.decompile=function(e){const t={};for(let r in e){const i=e[r];if("root"===r){t.root=i;continue}if(n.isTemplate(i)){t[r]=i.describe({compact:!0});continue}const s=r;for(r in t[s]={},i){const e=i[r];"root"!==r?t[s][r]=e.describe({compact:!0}):t[s].root=e}}return t},e.merge=function(i,s){if(!i)return e.compile(s);if(!s)return i;if("string"==typeof s)return new n(s);if(n.isTemplate(s))return s;const o=r(i);for(let e in s){const r=s[e];if("root"===e||n.isTemplate(r)){o[e]=r;continue}if("string"==typeof r){o[e]=new n(r);continue}t("object"==typeof r&&!Array.isArray(r),"Invalid message for",e);const i=e;for(e in o[i]=o[i]||{},r){const s=r[e];"root"===e||n.isTemplate(s)?o[i][e]=s:(t("string"==typeof s,"Invalid message for",e,"in",i),o[i][e]=new n(s))}}return o}
3518
+ }(messages)),messages}function requireCommon(){return hasRequiredCommon||(hasRequiredCommon=1,function(e){const{assert:t,AssertError:r}=requireLib$4(),n=require$$1$1;let i,s;const o={isoDate:/^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/};e.version=n.version,e.defaults={abortEarly:!0,allowUnknown:!1,artifacts:!1,cache:!0,context:null,convert:!0,dateFormat:"iso",errors:{escapeHtml:!1,label:"path",language:null,render:!0,stack:!1,wrap:{label:'"',array:"[]"}},externals:!0,messages:{},nonEnumerables:!1,noDefaults:!1,presence:"optional",skipFunctions:!1,stripUnknown:!1,warnings:!1},e.symbols={any:Symbol.for("@hapi/joi/schema"),arraySingle:Symbol("arraySingle"),
3519
+ deepDefault:Symbol("deepDefault"),errors:Symbol("errors"),literal:Symbol("literal"),override:Symbol("override"),parent:Symbol("parent"),prefs:Symbol("prefs"),ref:Symbol("ref"),template:Symbol("template"),values:Symbol("values")},e.assertOptions=function(e,r,n="Options"){t(e&&"object"==typeof e&&!Array.isArray(e),"Options must be of type object");const i=Object.keys(e).filter(e=>!r.includes(e));t(0===i.length,`${n} contain unknown keys: ${i}`)},e.checkPreferences=function(e){s=s||requireSchemas();const t=s.preferences.validate(e);if(t.error)throw new r([t.error.details[0].message])},e.compare=function(e,t,r){switch(r){case"=":return e===t;case">":return e>t;case"<":return e<t;case">=":return e>=t;case"<=":return e<=t}},e.default=function(e,t){return void 0===e?t:e},e.isIsoDate=function(e){return o.isoDate.test(e)},e.isNumber=function(e){return"number"==typeof e&&!isNaN(e)},e.isResolvable=function(t){return!!t&&(t[e.symbols.ref]||t[e.symbols.template])},e.isSchema=function(r,n={}){
3520
+ const i=r&&r[e.symbols.any];return!!i&&(t(n.legacy||i.version===e.version,"Cannot mix different versions of joi schemas"),!0)},e.isValues=function(t){return t[e.symbols.values]},e.limit=function(e){return Number.isSafeInteger(e)&&e>=0},e.preferences=function(t,r){i=i||requireMessages(),t=t||{},r=r||{};const n=Object.assign({},t,r);return r.errors&&t.errors&&(n.errors=Object.assign({},t.errors,r.errors),n.errors.wrap=Object.assign({},t.errors.wrap,r.errors.wrap)),r.messages&&(n.messages=i.compile(r.messages,t.messages)),delete n[e.symbols.prefs],n},e.tryWithPath=function(e,t,r={}){try{return e()}catch(e){throw void 0!==e.path?e.path=t+"."+e.path:e.path=t,r.append&&(e.message=`${e.message} (${e.path})`),e}},e.validateArg=function(t,r,{assert:n,message:i}){if(e.isSchema(n)){const e=n.validate(t);if(!e.error)return;return e.error.message}if(!n(t))return r?`${r} ${i}`:i},e.verifyFlat=function(e,r){for(const n of e)t(!Array.isArray(n),"Method no longer accepts array arguments:",r)}
3521
+ }(common)),common}function requireCache(){if(hasRequiredCache)return cache;hasRequiredCache=1;const{assert:e,clone:t}=requireLib$4(),r=requireCommon(),n={max:1e3,supported:new Set(["undefined","boolean","number","string"])};return cache.provider={provision:e=>new n.Cache(e)},n.Cache=class{constructor(t={}){r.assertOptions(t,["max"]),e(void 0===t.max||t.max&&t.max>0&&isFinite(t.max),"Invalid max cache size"),this._max=t.max||n.max,this._map=new Map,this._list=new n.List}get length(){return this._map.size}set(e,t){if(null!==e&&!n.supported.has(typeof e))return;let r=this._map.get(e);if(r)return r.value=t,void this._list.first(r);r=this._list.unshift({key:e,value:t}),this._map.set(e,r),this._compact()}get(e){const r=this._map.get(e);if(r)return this._list.first(r),t(r.value)}_compact(){if(this._map.size>this._max){const e=this._list.pop();this._map.delete(e.key)}}},n.List=class{constructor(){this.tail=null,this.head=null}unshift(e){return e.next=null,e.prev=this.head,
3522
+ this.head&&(this.head.next=e),this.head=e,this.tail||(this.tail=e),e}first(e){e!==this.head&&(this._remove(e),this.unshift(e))}pop(){return this._remove(this.tail)}_remove(e){const{next:t,prev:r}=e;return t.prev=r,r&&(r.next=t),e===this.tail&&(this.tail=t),e.prev=null,e.next=null,e}},cache}var compile={},hasRequiredCompile;function requireCompile(){return hasRequiredCompile||(hasRequiredCompile=1,function(e){const{assert:t}=requireLib$4(),r=requireCommon(),n=requireRef$1(),i={};e.schema=function(e,t,n={}){r.assertOptions(n,["appendPath","override"]);try{return i.schema(e,t,n)}catch(e){throw n.appendPath&&void 0!==e.path&&(e.message=`${e.message} (${e.path})`),e}},i.schema=function(e,n,s){t(void 0!==n,"Invalid undefined schema"),Array.isArray(n)&&(t(n.length,"Invalid empty array schema"),1===n.length&&(n=n[0]));const o=(t,...r)=>!1!==s.override?t.valid(e.override,...r):t.valid(...r);if(i.simple(n))return o(e,n);if("function"==typeof n)return e.custom(n)
3523
+ ;if(t("object"==typeof n,"Invalid schema content:",typeof n),r.isResolvable(n))return o(e,n);if(r.isSchema(n))return n;if(Array.isArray(n)){for(const t of n)if(!i.simple(t))return e.alternatives().try(...n);return o(e,...n)}return n instanceof RegExp?e.string().regex(n):n instanceof Date?o(e.date(),n):(t(Object.getPrototypeOf(n)===Object.getPrototypeOf({}),"Schema can only contain plain objects"),e.object().keys(n))},e.ref=function(e,t){return n.isRef(e)?e:n.create(e,t)},e.compile=function(n,s,o={}){r.assertOptions(o,["legacy"]);const a=s&&s[r.symbols.any];if(a)return t(o.legacy||a.version===r.version,"Cannot mix different versions of joi schemas:",a.version,r.version),s;if("object"!=typeof s||!o.legacy)return e.schema(n,s,{appendPath:!0});const c=i.walk(s);return c?c.compile(c.root,s):e.schema(n,s,{appendPath:!0})},i.walk=function(e){if("object"!=typeof e)return null;if(Array.isArray(e)){for(const t of e){const e=i.walk(t);if(e)return e}return null}const n=e[r.symbols.any]
3524
+ ;if(n)return{root:e[n.root],compile:n.compile};t(Object.getPrototypeOf(e)===Object.getPrototypeOf({}),"Schema can only contain plain objects");for(const t in e){const r=i.walk(e[t]);if(r)return r}return null},i.simple=function(e){return null===e||["boolean","string","number"].includes(typeof e)},e.when=function(s,o,a){if(void 0===a&&(t(o&&"object"==typeof o,"Missing options"),a=o,o=n.create(".")),Array.isArray(a)&&(a={switch:a}),r.assertOptions(a,["is","not","then","otherwise","switch","break"]),r.isSchema(o))return t(void 0===a.is,'"is" can not be used with a schema condition'),t(void 0===a.not,'"not" can not be used with a schema condition'),t(void 0===a.switch,'"switch" can not be used with a schema condition'),i.condition(s,{is:o,then:a.then,otherwise:a.otherwise,break:a.break});if(t(n.isRef(o)||"string"==typeof o,"Invalid condition:",o),t(void 0===a.not||void 0===a.is,'Cannot combine "is" with "not"'),void 0===a.switch){let c=a;void 0!==a.not&&(c={is:a.not,then:a.otherwise,
3525
+ otherwise:a.then,break:a.break});let u=void 0!==c.is?s.$_compile(c.is):s.$_root.invalid(null,!1,0,"").required();return t(void 0!==c.then||void 0!==c.otherwise,'options must have at least one of "then", "otherwise", or "switch"'),t(void 0===c.break||void 0===c.then||void 0===c.otherwise,"Cannot specify then, otherwise, and break all together"),void 0===a.is||n.isRef(a.is)||r.isSchema(a.is)||(u=u.required()),i.condition(s,{ref:e.ref(o),is:u,then:c.then,otherwise:c.otherwise,break:c.break})}t(Array.isArray(a.switch),'"switch" must be an array'),t(void 0===a.is,'Cannot combine "switch" with "is"'),t(void 0===a.not,'Cannot combine "switch" with "not"'),t(void 0===a.then,'Cannot combine "switch" with "then"');const c={ref:e.ref(o),switch:[],break:a.break};for(let e=0;e<a.switch.length;++e){const i=a.switch[e],o=e===a.switch.length-1;r.assertOptions(i,o?["is","then","otherwise"]:["is","then"]),t(void 0!==i.is,'Switch statement missing "is"'),
3526
+ t(void 0!==i.then,'Switch statement missing "then"');const u={is:s.$_compile(i.is),then:s.$_compile(i.then)};if(n.isRef(i.is)||r.isSchema(i.is)||(u.is=u.is.required()),o){t(void 0===a.otherwise||void 0===i.otherwise,'Cannot specify "otherwise" inside and outside a "switch"');const e=void 0!==a.otherwise?a.otherwise:i.otherwise;void 0!==e&&(t(void 0===c.break,"Cannot specify both otherwise and break"),u.otherwise=s.$_compile(e))}c.switch.push(u)}return c},i.condition=function(e,t){for(const r of["then","otherwise"])void 0===t[r]?delete t[r]:t[r]=e.$_compile(t[r]);return t}}(compile)),compile}var extend={},hasRequiredExtend;function requireExtend(){if(hasRequiredExtend)return extend;hasRequiredExtend=1;const{assert:e,clone:t}=requireLib$4(),r=requireCommon(),n=requireMessages(),i={};return extend.type=function(s,o){const a=Object.getPrototypeOf(s),c=t(a),u=s._assign(Object.create(c)),l=Object.assign({},o);delete l.base,c._definition=l;const d=a._definition||{}
3527
+ ;l.messages=n.merge(d.messages,l.messages),l.properties=Object.assign({},d.properties,l.properties),u.type=l.type,l.flags=Object.assign({},d.flags,l.flags);const p=Object.assign({},d.terms);if(l.terms)for(const t in l.terms){const r=l.terms[t];e(void 0===u.$_terms[t],"Invalid term override for",l.type,t),u.$_terms[t]=r.init,p[t]=r}l.terms=p,l.args||(l.args=d.args),l.prepare=i.prepare(l.prepare,d.prepare),l.coerce&&("function"==typeof l.coerce&&(l.coerce={method:l.coerce}),l.coerce.from&&!Array.isArray(l.coerce.from)&&(l.coerce={method:l.coerce.method,from:[].concat(l.coerce.from)})),l.coerce=i.coerce(l.coerce,d.coerce),l.validate=i.validate(l.validate,d.validate);const h=Object.assign({},d.rules);if(l.rules)for(const t in l.rules){const n=l.rules[t];e("object"==typeof n,"Invalid rule definition for",l.type,t);let i=n.method;if(void 0===i&&(i=function(){return this.$_addRule(t)}),i&&(e(!c[t],"Rule conflict in",l.type,t),c[t]=i),e(!h[t],"Rule conflict in",l.type,t),h[t]=n,n.alias){
3528
+ const e=[].concat(n.alias);for(const t of e)c[t]=n.method}n.args&&(n.argsByName=new Map,n.args=n.args.map(t=>("string"==typeof t&&(t={name:t}),e(!n.argsByName.has(t.name),"Duplicated argument name",t.name),r.isSchema(t.assert)&&(t.assert=t.assert.strict().label(t.name)),n.argsByName.set(t.name,t),t)))}l.rules=h;const A=Object.assign({},d.modifiers);if(l.modifiers)for(const t in l.modifiers){e(!c[t],"Rule conflict in",l.type,t);const r=l.modifiers[t];e("function"==typeof r,"Invalid modifier definition for",l.type,t);const n=function(e){return this.rule({[t]:e})};c[t]=n,A[t]=r}if(l.modifiers=A,l.overrides){c._super=a,u.$_super={};for(const t in l.overrides)e(a[t],"Cannot override missing",t),l.overrides[t][r.symbols.parent]=a[t],u.$_super[t]=a[t].bind(u);Object.assign(c,l.overrides)}l.cast=Object.assign({},d.cast,l.cast);const f=Object.assign({},d.manifest,l.manifest);return f.build=i.build(l.manifest&&l.manifest.build,d.manifest&&d.manifest.build),l.manifest=f,
3529
+ l.rebuild=i.rebuild(l.rebuild,d.rebuild),u},i.build=function(e,t){return e&&t?function(r,n){return t(e(r,n),n)}:e||t},i.coerce=function(e,t){return e&&t?{from:e.from&&t.from?[...new Set([...e.from,...t.from])]:null,method(r,n){let i;if((!t.from||t.from.includes(typeof r))&&(i=t.method(r,n),i)){if(i.errors||void 0===i.value)return i;r=i.value}if(!e.from||e.from.includes(typeof r)){const t=e.method(r,n);if(t)return t}return i}}:e||t},i.prepare=function(e,t){return e&&t?function(r,n){const i=e(r,n);if(i){if(i.errors||void 0===i.value)return i;r=i.value}return t(r,n)||i}:e||t},i.rebuild=function(e,t){return e&&t?function(r){t(r),e(r)}:e||t},i.validate=function(e,t){return e&&t?function(r,n){const i=t(r,n);if(i){if(i.errors&&(!Array.isArray(i.errors)||i.errors.length))return i;r=i.value}return e(r,n)||i}:e||t},extend}var manifest={},hasRequiredManifest;function requireManifest(){if(hasRequiredManifest)return manifest;hasRequiredManifest=1
3530
+ ;const{assert:e,clone:t}=requireLib$4(),r=requireCommon(),n=requireMessages(),i=requireRef$1(),s=requireTemplate();let o;const a={};return manifest.describe=function(i){const s=i._definition,o={type:i.type,flags:{},rules:[]};for(const e in i._flags)"_"!==e[0]&&(o.flags[e]=a.describe(i._flags[e]));Object.keys(o.flags).length||delete o.flags,i._preferences&&(o.preferences=t(i._preferences,{shallow:["messages"]}),delete o.preferences[r.symbols.prefs],o.preferences.messages&&(o.preferences.messages=n.decompile(o.preferences.messages))),i._valids&&(o.allow=i._valids.describe()),i._invalids&&(o.invalid=i._invalids.describe());for(const e of i._rules){if(!1===s.rules[e.name].manifest)continue;const t={name:e.name};for(const r in s.modifiers)void 0!==e[r]&&(t[r]=a.describe(e[r]));if(e.args){t.args={};for(const r in e.args){const n=e.args[r];("options"!==r||Object.keys(n).length)&&(t.args[r]=a.describe(n,{assign:r}))}Object.keys(t.args).length||delete t.args}o.rules.push(t)}
3531
+ o.rules.length||delete o.rules;for(const t in i.$_terms){if("_"===t[0])continue;e(!o[t],"Cannot describe schema due to internal name conflict with",t);const n=i.$_terms[t];if(!n)continue;if(n instanceof Map){n.size&&(o[t]=[...n.entries()]);continue}if(r.isValues(n)){o[t]=n.describe();continue}e(s.terms[t],"Term",t,"missing configuration");const c=s.terms[t].manifest,u="object"==typeof c;if(!n.length&&!u)continue;const l=[];for(const e of n)l.push(a.describe(e));if(u){const{from:e,to:r}=c.mapped;o[t]={};for(const n of l)o[t][n[r]]=n[e];continue}"single"!==c?o[t]=l:(e(1===l.length,"Term",t,"contains more than one item"),o[t]=l[0])}return a.validate(i.$_root,o),o},a.describe=function(e,n={}){if(Array.isArray(e))return e.map(a.describe);if(e===r.symbols.deepDefault)return{special:"deep"};if("object"!=typeof e||null===e)return e;if("options"===n.assign)return t(e);if(Buffer&&Buffer.isBuffer(e))return{buffer:e.toString("binary")};if(e instanceof Date)return e.toISOString()
3532
+ ;if(e instanceof Error)return e;if(e instanceof RegExp)return"regex"===n.assign?e.toString():{regex:e.toString()};if(e[r.symbols.literal])return{function:e.literal};if("function"==typeof e.describe)return"ref"===n.assign?e.describe().ref:e.describe();const i={};for(const t in e){const r=e[t];void 0!==r&&(i[t]=a.describe(r,{assign:t}))}return i},manifest.build=function(e,t){return new a.Builder(e).parse(t)},a.Builder=class{constructor(e){this.joi=e}parse(t){a.validate(this.joi,t);let r=this.joi[t.type]()._bare();const n=r._definition;if(t.flags)for(const i in t.flags){const s=n.flags[i]&&n.flags[i].setter||i;e("function"==typeof r[s],"Invalid flag",i,"for type",t.type),r=r[s](this.build(t.flags[i]))}if(t.preferences&&(r=r.preferences(this.build(t.preferences))),t.allow&&(r=r.allow(...this.build(t.allow))),t.invalid&&(r=r.invalid(...this.build(t.invalid))),t.rules)for(const i of t.rules){e("function"==typeof r[i.name],"Invalid rule",i.name,"for type",t.type);const s=[];if(i.args){
3533
+ const r={};for(const e in i.args)r[e]=this.build(i.args[e],{assign:e});const o=Object.keys(r),a=n.rules[i.name].args;if(a){e(o.length<=a.length,"Invalid number of arguments for",t.type,i.name,"(expected up to",a.length,", found",o.length,")");for(const{name:e}of a)s.push(r[e])}else e(1===o.length,"Invalid number of arguments for",t.type,i.name,"(expected up to 1, found",o.length,")"),s.push(r[o[0]])}r=r[i.name](...s);const o={};for(const e in n.modifiers)void 0!==i[e]&&(o[e]=this.build(i[e]));Object.keys(o).length&&(r=r.rule(o))}const i={};for(const r in t){if(["allow","flags","invalid","whens","preferences","rules","type"].includes(r))continue;e(n.terms[r],"Term",r,"missing configuration");const s=n.terms[r].manifest;if("schema"!==s)if("values"!==s)if("single"!==s)if("object"!=typeof s)i[r]=this.build(t[r]);else{i[r]={};for(const e in t[r]){const n=t[r][e];i[r][e]=this.parse(n)}}else i[r]=this.build(t[r]);else i[r]=t[r].map(e=>this.build(e));else i[r]=t[r].map(e=>this.parse(e))}
3534
+ return t.whens&&(i.whens=t.whens.map(e=>this.build(e))),r=n.manifest.build(r,i),r.$_temp.ruleset=!1,r}build(n,o={}){if(null===n)return null;if(Array.isArray(n))return n.map(e=>this.build(e));if(n instanceof Error)return n;if("options"===o.assign)return t(n);if("regex"===o.assign)return a.regex(n);if("ref"===o.assign)return i.build(n);if("object"!=typeof n)return n;if(1===Object.keys(n).length){if(n.buffer)return e(Buffer,"Buffers are not supported"),Buffer&&Buffer.from(n.buffer,"binary");if(n.function)return{[r.symbols.literal]:!0,literal:n.function};if(n.override)return r.symbols.override;if(n.ref)return i.build(n.ref);if(n.regex)return a.regex(n.regex);if(n.special)return e(["deep"].includes(n.special),"Unknown special value",n.special),r.symbols.deepDefault;if(n.value)return t(n.value)}if(n.type)return this.parse(n);if(n.template)return s.build(n);const c={};for(const e in n)c[e]=this.build(n[e],{assign:e});return c}},a.regex=function(e){
3535
+ const t=e.lastIndexOf("/"),r=e.slice(1,t),n=e.slice(t+1);return new RegExp(r,n)},a.validate=function(e,t){o=o||requireSchemas(),e.assert(t,o.description)},manifest}var trace={},lib$2={},hasRequiredLib$2,hasRequiredTrace;function requireLib$2(){return hasRequiredLib$2||(hasRequiredLib$2=1,lib$2.location=function(e=0){const t=Error.prepareStackTrace;Error.prepareStackTrace=(e,t)=>t;const r={};Error.captureStackTrace(r,this);const n=r.stack[e+1];return Error.prepareStackTrace=t,{filename:n.getFileName(),line:n.getLineNumber()}}),lib$2}function requireTrace(){if(hasRequiredTrace)return trace;hasRequiredTrace=1;const{deepEqual:e}=requireLib$4(),t=requireLib$2(),r=requireErrors$1(),n={codes:{error:1,pass:2,full:3},labels:{0:"never used",1:"always error",2:"always pass"}};return trace.setup=function(e){const t=function(){return e._tracer=e._tracer||new n.Tracer,e._tracer};e.trace=t,e[Symbol.for("@hapi/lab/coverage/initialize")]=t,e.untrace=()=>{e._tracer=null}},trace.location=function(e){
3536
+ return e.$_setFlag("_tracerLocation",t.location(2))},n.Tracer=class{constructor(){this.name="Joi",this._schemas=new Map}_register(e){const r=this._schemas.get(e);if(r)return r.store;const i=new n.Store(e),{filename:s,line:o}=e._flags._tracerLocation||t.location(5);return this._schemas.set(e,{filename:s,line:o,store:i}),i}_combine(e,t){for(const{store:r}of this._schemas.values())r._combine(e,t)}report(e){const t=[];for(const{filename:r,line:i,store:s}of this._schemas.values()){if(e&&e!==r)continue;const o=[],a=[];for(const[e,t]of s._sources.entries()){if(n.sub(t.paths,a))continue;if(!t.entry){o.push({status:"never reached",paths:[...t.paths]}),a.push(...t.paths);continue}for(const r of["valid","invalid"]){const n=e[`_${r}s`];if(!n)continue;const i=new Set(n._values),s=new Set(n._refs);for(const{value:e,ref:n}of t[r])i.delete(e),s.delete(n);(i.size||s.size)&&o.push({status:[...i,...[...s].map(e=>e.display)],rule:`${r}s`})}const r=e._rules.map(e=>e.name)
3537
+ ;for(const t of["default","failover"])void 0!==e._flags[t]&&r.push(t);for(const e of r){const r=n.labels[t.rule[e]||0];if(r){const n={rule:e,status:r};t.paths.size&&(n.paths=[...t.paths]),o.push(n)}}}o.length&&t.push({filename:r,line:i,missing:o,severity:"error",message:`Schema missing tests for ${o.map(n.message).join(", ")}`})}return t.length?t:null}},n.Store=class{constructor(e){this.active=!0,this._sources=new Map,this._combos=new Map,this._scan(e)}debug(e,t,r,n){e.mainstay.debug&&e.mainstay.debug.push({type:t,name:r,result:n,path:e.path})}entry(e,t){n.debug(t,{type:"entry"}),this._record(e,e=>{e.entry=!0})}filter(e,t,r,i){n.debug(t,{type:r,...i}),this._record(e,e=>{e[r].add(i)})}log(e,t,r,i,s){n.debug(t,{type:r,name:i,result:"full"===s?"pass":s}),this._record(e,e=>{e[r][i]=e[r][i]||0,e[r][i]|=n.codes[s]})}resolve(e,t,r){if(!e.mainstay.debug)return;const n={type:"resolve",ref:t.display,to:r,path:e.path};e.mainstay.debug.push(n)}value(t,r,n,i,s){if(!t.mainstay.debug||e(n,i))return
3538
+ ;const o={type:"value",by:r,from:n,to:i,path:t.path};s&&(o.name=s),t.mainstay.debug.push(o)}_record(e,t){const r=this._sources.get(e);if(r)return void t(r);const n=this._combos.get(e);for(const e of n)this._record(e,t)}_scan(e,t){const r=t||[];let i=this._sources.get(e);i||(i={paths:new Set,entry:!1,rule:{},valid:new Set,invalid:new Set},this._sources.set(e,i)),r.length&&i.paths.add(r);e.$_modify({each:(e,t)=>{const i=n.id(e,t);this._scan(e,r.concat(i))},ref:!1})}_combine(e,t){this._combos.set(e,t)}},n.message=function(e){return`${e.paths?r.path(e.paths[0])+(e.rule?":":""):""}${e.rule||""} (${e.status})`},n.id=function(e,{source:t,name:r,path:n,key:i}){return e._flags.id?e._flags.id:i||(r=`@${r}`,"terms"===t?[r,n[Math.min(n.length-1,1)]]:r)},n.sub=function(t,r){for(const n of t)for(const t of r)if(e(n.slice(0,t.length),t))return!0;return!1},n.debug=function(e,t){e.mainstay.debug&&(t.path=e.debug?[...e.path,e.debug]:e.path,e.mainstay.debug.push(t))},trace}var modify={},hasRequiredModify
3539
+ ;function requireModify(){return hasRequiredModify||(hasRequiredModify=1,function(e){const{assert:t}=requireLib$4(),r=requireCommon(),n=requireRef$1(),i={};e.Ids=i.Ids=class{constructor(){this._byId=new Map,this._byKey=new Map,this._schemaChain=!1}clone(){const e=new i.Ids;return e._byId=new Map(this._byId),e._byKey=new Map(this._byKey),e._schemaChain=this._schemaChain,e}concat(e){e._schemaChain&&(this._schemaChain=!0);for(const[r,n]of e._byId.entries())t(!this._byKey.has(r),"Schema id conflicts with existing key:",r),this._byId.set(r,n);for(const[r,n]of e._byKey.entries())t(!this._byId.has(r),"Schema key conflicts with existing id:",r),this._byKey.set(r,n)}fork(e,n,s){const o=this._collect(e);o.push({schema:s});const a=o.shift();let c={id:a.id,schema:n(a.schema)};t(r.isSchema(c.schema),"adjuster function failed to return a joi schema type");for(const e of o)c={id:e.id,schema:i.fork(e.schema,c.id,c.schema)};return c.schema}labels(e,t=[]){const r=e[0],n=this._get(r)
3540
+ ;if(!n)return[...t,...e].join(".");const i=e.slice(1);return t=[...t,n.schema._flags.label||r],i.length?n.schema._ids.labels(i,t):t.join(".")}reach(e,r=[]){const n=e[0],i=this._get(n);t(i,"Schema does not contain path",[...r,...e].join("."));const s=e.slice(1);return s.length?i.schema._ids.reach(s,[...r,n]):i.schema}register(e,{key:n}={}){if(!e||!r.isSchema(e))return;(e.$_property("schemaChain")||e._ids._schemaChain)&&(this._schemaChain=!0);const i=e._flags.id;if(i){const r=this._byId.get(i);t(!r||r.schema===e,"Cannot add different schemas with the same id:",i),t(!this._byKey.has(i),"Schema id conflicts with existing key:",i),this._byId.set(i,{schema:e,id:i})}n&&(t(!this._byKey.has(n),"Schema already contains key:",n),t(!this._byId.has(n),"Schema key conflicts with existing id:",n),this._byKey.set(n,{schema:e,id:n}))}reset(){this._byId=new Map,this._byKey=new Map,this._schemaChain=!1}_collect(e,r=[],n=[]){const i=e[0],s=this._get(i)
3541
+ ;t(s,"Schema does not contain path",[...r,...e].join(".")),n=[s,...n];const o=e.slice(1);return o.length?s.schema._ids._collect(o,[...r,i],n):n}_get(e){return this._byId.get(e)||this._byKey.get(e)}},i.fork=function(t,r,n){const i=e.schema(t,{each:(e,{key:t})=>{if(r===(e._flags.id||t))return n},ref:!1});return i?i.$_mutateRebuild():t},e.schema=function(e,t){let r;for(const n in e._flags){if("_"===n[0])continue;const s=i.scan(e._flags[n],{source:"flags",name:n},t);void 0!==s&&(r=r||e.clone(),r._flags[n]=s)}for(let n=0;n<e._rules.length;++n){const s=e._rules[n],o=i.scan(s.args,{source:"rules",name:s.name},t);if(void 0!==o){r=r||e.clone();const t=Object.assign({},s);t.args=o,r._rules[n]=t;r._singleRules.get(s.name)===s&&r._singleRules.set(s.name,t)}}for(const n in e.$_terms){if("_"===n[0])continue;const s=i.scan(e.$_terms[n],{source:"terms",name:n},t);void 0!==s&&(r=r||e.clone(),r.$_terms[n]=s)}return r},i.scan=function(e,t,s,o,a){const c=o||[];if(null===e||"object"!=typeof e)return;let u
3542
+ ;if(Array.isArray(e)){for(let r=0;r<e.length;++r){const n="terms"===t.source&&"keys"===t.name&&e[r].key,o=i.scan(e[r],t,s,[r,...c],n);void 0!==o&&(u=u||e.slice(),u[r]=o)}return u}if(!1!==s.schema&&r.isSchema(e)||!1!==s.ref&&n.isRef(e)){const r=s.each(e,{...t,path:c,key:a});if(r===e)return;return r}for(const r in e){if("_"===r[0])continue;const n=i.scan(e[r],t,s,[r,...c],a);void 0!==n&&(u=u||Object.assign({},e),u[r]=n)}return u}}(modify)),modify}var validator={},state$1,hasRequiredState$2,hasRequiredValidator,values,hasRequiredValues,base,hasRequiredBase,any,hasRequiredAny,alternatives,hasRequiredAlternatives,array,hasRequiredArray,boolean,hasRequiredBoolean,date,hasRequiredDate;function requireState$2(){if(hasRequiredState$2)return state$1;hasRequiredState$2=1;const{clone:e,reach:t}=requireLib$4(),r=requireCommon(),n={value:Symbol("value")};return state$1=n.State=class{constructor(e,t,r){this.path=e,this.ancestors=t,this.mainstay=r.mainstay,this.schemas=r.schemas,this.debug=null}
3543
+ localize(e,t=null,r=null){const i=new n.State(e,t,this);return r&&i.schemas&&(i.schemas=[n.schemas(r),...i.schemas]),i}nest(e,t){const r=new n.State(this.path,this.ancestors,this);return r.schemas=r.schemas&&[n.schemas(e),...r.schemas],r.debug=t,r}shadow(e,t){this.mainstay.shadow=this.mainstay.shadow||new n.Shadow,this.mainstay.shadow.set(this.path,e,t)}snapshot(){this.mainstay.shadow&&(this._snapshot=e(this.mainstay.shadow.node(this.path))),this.mainstay.snapshot()}restore(){this.mainstay.shadow&&(this.mainstay.shadow.override(this.path,this._snapshot),this._snapshot=void 0),this.mainstay.restore()}commit(){this.mainstay.shadow&&(this.mainstay.shadow.override(this.path,this._snapshot),this._snapshot=void 0),this.mainstay.commit()}},n.schemas=function(e){return r.isSchema(e)?{schema:e}:e},n.Shadow=class{constructor(){this._values=null}set(e,t,r){if(!e.length)return;if("strip"===r&&"number"==typeof e[e.length-1])return;this._values=this._values||new Map;let i=this._values
3544
+ ;for(let t=0;t<e.length;++t){const r=e[t];let n=i.get(r);n||(n=new Map,i.set(r,n)),i=n}i[n.value]=t}get(e){const t=this.node(e);if(t)return t[n.value]}node(e){if(this._values)return t(this._values,e,{iterables:!0})}override(e,r){if(!this._values)return;const n=e.slice(0,-1),i=e[e.length-1],s=t(this._values,n,{iterables:!0});r?s.set(i,r):s&&s.delete(i)}},state$1}function requireValidator(){return hasRequiredValidator||(hasRequiredValidator=1,function(e){const{assert:t,clone:r,ignore:n,reach:i}=requireLib$4(),s=requireCommon(),o=requireErrors$1(),a=requireState$2(),c={result:Symbol("result")};e.entry=function(e,r,n){let i=s.defaults;n&&(t(void 0===n.warnings,"Cannot override warnings preference in synchronous validation"),t(void 0===n.artifacts,"Cannot override artifacts preference in synchronous validation"),i=s.preferences(s.defaults,n));const a=c.entry(e,r,i);t(!a.mainstay.externals.length,"Schema with external rules must use validateAsync()");const u={value:a.value}
3545
+ ;return a.error&&(u.error=a.error),a.mainstay.warnings.length&&(u.warning=o.details(a.mainstay.warnings)),a.mainstay.debug&&(u.debug=a.mainstay.debug),a.mainstay.artifacts&&(u.artifacts=a.mainstay.artifacts),u},e.entryAsync=async function(e,t,r){let n=s.defaults;r&&(n=s.preferences(s.defaults,r));const a=c.entry(e,t,n),u=a.mainstay;if(a.error)throw u.debug&&(a.error.debug=u.debug),a.error;if(u.externals.length){let t=a.value;const l=[];for(const a of u.externals){const d=a.state.path,p="link"===a.schema.type?u.links.get(a.schema):null;let h,A,f=t;const g=d.length?[t]:[],m=d.length?i(e,d):e;if(d.length){h=d[d.length-1];let e=t;for(const t of d.slice(0,-1))e=e[t],g.unshift(e);A=g[0],f=A[h]}try{const e=(e,t)=>(p||a.schema).$_createError(e,f,t,a.state,n),i=await a.method(f,{schema:a.schema,linked:p,state:a.state,prefs:r,original:m,error:e,errorsArray:c.errorsArray,warn:(e,t)=>u.warnings.push((p||a.schema).$_createError(e,f,t,a.state,n)),
3546
+ message:(e,t)=>(p||a.schema).$_createError("external",f,t,a.state,n,{messages:e})});if(void 0===i||i===f)continue;if(i instanceof o.Report){if(u.tracer.log(a.schema,a.state,"rule","external","error"),l.push(i),n.abortEarly)break;continue}if(Array.isArray(i)&&i[s.symbols.errors]){if(u.tracer.log(a.schema,a.state,"rule","external","error"),l.push(...i),n.abortEarly)break;continue}A?(u.tracer.value(a.state,"rule",f,i,"external"),A[h]=i):(u.tracer.value(a.state,"rule",t,i,"external"),t=i)}catch(e){throw n.errors.label&&(e.message+=` (${a.label})`),e}}if(a.value=t,l.length)throw a.error=o.process(l,e,n),u.debug&&(a.error.debug=u.debug),a.error}if(!n.warnings&&!n.debug&&!n.artifacts)return a.value;const l={value:a.value};return u.warnings.length&&(l.warning=o.details(u.warnings)),u.debug&&(l.debug=u.debug),u.artifacts&&(l.artifacts=u.artifacts),l},e.standard=function(t,r){return r.isAsync()?e.entryAsync(t,r):e.entry(t,r)},c.Mainstay=class{constructor(e,t,r){this.externals=[],
3547
+ this.warnings=[],this.tracer=e,this.debug=t,this.links=r,this.shadow=null,this.artifacts=null,this._snapshots=[]}snapshot(){this._snapshots.push({externals:this.externals.slice(),warnings:this.warnings.slice()})}restore(){const e=this._snapshots.pop();this.externals=e.externals,this.warnings=e.warnings}commit(){this._snapshots.pop()}},c.entry=function(t,r,n){const{tracer:i,cleanup:s}=c.tracer(r,n),u=n.debug?[]:null,l=r._ids._schemaChain?new Map:null,d=new c.Mainstay(i,u,l),p=r._ids._schemaChain?[{schema:r}]:null,h=new a([],[],{mainstay:d,schemas:p}),A=e.validate(t,r,h,n);s&&r.$_root.untrace();const f=o.process(A.errors,t,n);return{value:A.value,error:f,mainstay:d}},c.tracer=function(e,r){return e.$_root._tracer?{tracer:e.$_root._tracer._register(e)}:r.debug?(t(e.$_root.trace,"Debug mode not supported"),{tracer:e.$_root.trace()._register(e),cleanup:!0}):{tracer:c.ignore}},e.validate=function(e,t,r,n,i={}){if(t.$_terms.whens&&(t=t._generate(e,r,n).schema),
3548
+ t._preferences&&(n=c.prefs(t,n)),t._cache&&n.cache){const n=t._cache.get(e);if(r.mainstay.tracer.debug(r,"validate","cached",!!n),n)return n}const o=(i,s,o)=>t.$_createError(i,e,s,o||r,n),a={original:e,prefs:n,schema:t,state:r,error:o,errorsArray:c.errorsArray,warn:(e,t,n)=>r.mainstay.warnings.push(o(e,t,n)),message:(i,s)=>t.$_createError("custom",e,s,r,n,{messages:i})};r.mainstay.tracer.entry(t,r);const u=t._definition;if(u.prepare&&void 0!==e&&n.convert){const t=u.prepare(e,a);if(t){if(r.mainstay.tracer.value(r,"prepare",e,t.value),t.errors)return c.finalize(t.value,[].concat(t.errors),a);e=t.value}}if(u.coerce&&void 0!==e&&n.convert&&(!u.coerce.from||u.coerce.from.includes(typeof e))){const t=u.coerce.method(e,a);if(t){if(r.mainstay.tracer.value(r,"coerced",e,t.value),t.errors)return c.finalize(t.value,[].concat(t.errors),a);e=t.value}}const l=t._flags.empty;l&&l.$_match(c.trim(e,t),r.nest(l),s.defaults)&&(r.mainstay.tracer.value(r,"empty",e,void 0),e=void 0)
3549
+ ;const d=i.presence||t._flags.presence||(t._flags._endedSwitch?null:n.presence);if(void 0===e){if("forbidden"===d)return c.finalize(e,null,a);if("required"===d)return c.finalize(e,[t.$_createError("any.required",e,null,r,n)],a);if("optional"===d){if(t._flags.default!==s.symbols.deepDefault)return c.finalize(e,null,a);r.mainstay.tracer.value(r,"default",e,{}),e={}}}else if("forbidden"===d)return c.finalize(e,[t.$_createError("any.unknown",e,null,r,n)],a);const p=[];if(t._valids){const i=t._valids.get(e,r,n,t._flags.insensitive);if(i)return n.convert&&(r.mainstay.tracer.value(r,"valids",e,i.value),e=i.value),r.mainstay.tracer.filter(t,r,"valid",i),c.finalize(e,null,a);if(t._flags.only){const i=t.$_createError("any.only",e,{valids:t._valids.values({display:!0})},r,n);if(n.abortEarly)return c.finalize(e,[i],a);p.push(i)}}if(t._invalids){const i=t._invalids.get(e,r,n,t._flags.insensitive);if(i){r.mainstay.tracer.filter(t,r,"invalid",i);const s=t.$_createError("any.invalid",e,{
3550
+ invalids:t._invalids.values({display:!0})},r,n);if(n.abortEarly)return c.finalize(e,[s],a);p.push(s)}}if(u.validate){const t=u.validate(e,a);if(t&&(r.mainstay.tracer.value(r,"base",e,t.value),e=t.value,t.errors)){if(!Array.isArray(t.errors))return p.push(t.errors),c.finalize(e,p,a);if(t.errors.length)return p.push(...t.errors),c.finalize(e,p,a)}}return t._rules.length?c.rules(e,p,a):c.finalize(e,p,a)},c.rules=function(e,t,r){const{schema:n,state:i,prefs:o}=r;for(const a of n._rules){const u=n._definition.rules[a.method];if(u.convert&&o.convert){i.mainstay.tracer.log(n,i,"rule",a.name,"full");continue}let l,d=a.args;if(a._resolve.length){d=Object.assign({},d);for(const t of a._resolve){const r=u.argsByName.get(t),a=d[t].resolve(e,i,o),c=r.normalize?r.normalize(a):a,p=s.validateArg(c,null,r);if(p){l=n.$_createError("any.ref",a,{arg:t,ref:d[t],reason:p},i,o);break}d[t]=c}}l=l||u.validate(e,r,d,a);const p=c.rule(l,a);if(p.errors){if(i.mainstay.tracer.log(n,i,"rule",a.name,"error"),a.warn){
3551
+ i.mainstay.warnings.push(...p.errors);continue}if(o.abortEarly)return c.finalize(e,p.errors,r);t.push(...p.errors)}else i.mainstay.tracer.log(n,i,"rule",a.name,"pass"),i.mainstay.tracer.value(i,"rule",e,p.value,a.name),e=p.value}return c.finalize(e,t,r)},c.rule=function(e,t){return e instanceof o.Report?(c.error(e,t),{errors:[e],value:null}):Array.isArray(e)&&e[s.symbols.errors]?(e.forEach(e=>c.error(e,t)),{errors:e,value:null}):{errors:null,value:e}},c.error=function(e,t){return t.message&&e._setTemplate(t.message),e},c.finalize=function(e,r,n){r=r||[];const{schema:i,state:s,prefs:a}=n;if(r.length){const t=c.default("failover",void 0,r,n);void 0!==t&&(s.mainstay.tracer.value(s,"failover",e,t),e=t,r=[])}if(r.length&&i._flags.error)if("function"==typeof i._flags.error){r=i._flags.error(r),Array.isArray(r)||(r=[r]);for(const e of r)t(e instanceof Error||e instanceof o.Report,"error() must return an Error object")}else r=[i._flags.error];if(void 0===e){const t=c.default("default",e,r,n)
3552
+ ;s.mainstay.tracer.value(s,"default",e,t),e=t}if(i._flags.cast&&void 0!==e){const t=i._definition.cast[i._flags.cast];if(t.from(e)){const r=t.to(e,n);s.mainstay.tracer.value(s,"cast",e,r,i._flags.cast),e=r}}if(i.$_terms.externals&&a.externals&&!1!==a._externals)for(const{method:e}of i.$_terms.externals)s.mainstay.externals.push({method:e,schema:i,state:s,label:o.label(i._flags,s,a)});const u={value:e,errors:r.length?r:null};return i._flags.result&&(u.value="strip"===i._flags.result?void 0:n.original,s.mainstay.tracer.value(s,i._flags.result,e,u.value),s.shadow(e,i._flags.result)),i._cache&&!1!==a.cache&&!i._refs.length&&i._cache.set(n.original,u),void 0===e||u.errors||void 0===i._flags.artifact||(s.mainstay.artifacts=s.mainstay.artifacts||new Map,s.mainstay.artifacts.has(i._flags.artifact)||s.mainstay.artifacts.set(i._flags.artifact,[]),s.mainstay.artifacts.get(i._flags.artifact).push(s.path)),u},c.prefs=function(e,t){const r=t===s.defaults
3553
+ ;return r&&e._preferences[s.symbols.prefs]?e._preferences[s.symbols.prefs]:(t=s.preferences(t,e._preferences),r&&(e._preferences[s.symbols.prefs]=t),t)},c.default=function(e,t,n,i){const{schema:o,state:a,prefs:c}=i,u=o._flags[e];if(c.noDefaults||void 0===u)return t;if(a.mainstay.tracer.log(o,a,"rule",e,"full"),!u)return u;if("function"==typeof u){const t=u.length?[r(a.ancestors[0]),i]:[];try{return u(...t)}catch(t){return void n.push(o.$_createError(`any.${e}`,null,{error:t},a,c))}}return"object"!=typeof u?u:u[s.symbols.literal]?u.literal:s.isResolvable(u)?u.resolve(t,a,c):r(u)},c.trim=function(e,t){if("string"!=typeof e)return e;const r=t.$_getRule("trim");return r&&r.args.enabled?e.trim():e},c.ignore={active:!1,debug:n,entry:n,filter:n,log:n,resolve:n,value:n},c.errorsArray=function(){const e=[];return e[s.symbols.errors]=!0,e}}(validator)),validator}function requireValues(){if(hasRequiredValues)return values;hasRequiredValues=1
3554
+ ;const{assert:e,deepEqual:t}=requireLib$4(),r=requireCommon(),n={};return values=n.Values=class{constructor(e,t){this._values=new Set(e),this._refs=new Set(t),this._lowercase=n.lowercases(e),this._override=!1}get length(){return this._values.size+this._refs.size}add(e,t){r.isResolvable(e)?this._refs.has(e)||(this._refs.add(e),t&&t.register(e)):this.has(e,null,null,!1)||(this._values.add(e),"string"==typeof e&&this._lowercase.set(e.toLowerCase(),e))}static merge(e,t,r){if(e=e||new n.Values,t){if(t._override)return t.clone();for(const r of[...t._values,...t._refs])e.add(r)}if(r)for(const t of[...r._values,...r._refs])e.remove(t);return e.length?e:null}remove(e){r.isResolvable(e)?this._refs.delete(e):(this._values.delete(e),"string"==typeof e&&this._lowercase.delete(e.toLowerCase()))}has(e,t,r,n){return!!this.get(e,t,r,n)}get(e,r,n,i){if(!this.length)return!1;if(this._values.has(e))return{value:e};if("string"==typeof e&&e&&i){const t=this._lowercase.get(e.toLowerCase());if(t)return{
3555
+ value:t}}if(!this._refs.size&&"object"!=typeof e)return!1;if("object"==typeof e)for(const r of this._values)if(t(r,e))return{value:r};if(r)for(const s of this._refs){const o=s.resolve(e,r,n,null,{in:!0});if(void 0===o)continue;const a=s.in&&"object"==typeof o?Array.isArray(o)?o:Object.keys(o):[o];for(const r of a)if(typeof r==typeof e)if(i&&e&&"string"==typeof e){if(r.toLowerCase()===e.toLowerCase())return{value:r,ref:s}}else if(t(r,e))return{value:r,ref:s}}return!1}override(){this._override=!0}values(e){if(e&&e.display){const e=[];for(const t of[...this._values,...this._refs])void 0!==t&&e.push(t);return e}return Array.from([...this._values,...this._refs])}clone(){const e=new n.Values(this._values,this._refs);return e._override=this._override,e}concat(t){e(!t._override,"Cannot concat override set of values");const r=new n.Values([...this._values,...t._values],[...this._refs,...t._refs]);return r._override=this._override,r}describe(){const e=[];this._override&&e.push({override:!0})
3556
+ ;for(const t of this._values.values())e.push(t&&"object"==typeof t?{value:t}:t);for(const t of this._refs.values())e.push(t.describe());return e}},n.Values.prototype[r.symbols.values]=!0,n.Values.prototype.slice=n.Values.prototype.clone,n.lowercases=function(e){const t=new Map;if(e)for(const r of e)"string"==typeof r&&t.set(r.toLowerCase(),r);return t},values}function requireBase(){if(hasRequiredBase)return base;hasRequiredBase=1;const{assert:e,clone:t,deepEqual:r,merge:n}=requireLib$4(),i=requireCache(),s=requireCommon(),o=requireCompile(),a=requireErrors$1(),c=requireExtend(),u=requireManifest(),l=requireMessages(),d=requireModify(),p=requireRef$1(),h=requireTrace(),A=requireValidator(),f=requireValues(),g={Base:class{constructor(e){this.type=e,this.$_root=null,this._definition={},this._reset()}_reset(){this._ids=new d.Ids,this._preferences=null,this._refs=new p.Manager,this._cache=null,this._valids=null,this._invalids=null,this._flags={},this._rules=[],this._singleRules=new Map,
3557
+ this.$_terms={},this.$_temp={ruleset:null,whens:{}}}describe(){return e("function"==typeof u.describe,"Manifest functionality disabled"),u.describe(this)}allow(...e){return s.verifyFlat(e,"allow"),this._values(e,"_valids")}alter(t){e(t&&"object"==typeof t&&!Array.isArray(t),"Invalid targets argument"),e(!this._inRuleset(),"Cannot set alterations inside a ruleset");const r=this.clone();r.$_terms.alterations=r.$_terms.alterations||[];for(const n in t){const i=t[n];e("function"==typeof i,"Alteration adjuster for",n,"must be a function"),r.$_terms.alterations.push({target:n,adjuster:i})}return r.$_temp.ruleset=!1,r}artifact(t){return e(void 0!==t,"Artifact cannot be undefined"),e(!this._cache,"Cannot set an artifact with a rule cache"),this.$_setFlag("artifact",t)}cast(t){return e(!1===t||"string"==typeof t,"Invalid to value"),e(!1===t||this._definition.cast[t],"Type",this.type,"does not support casting to",t),this.$_setFlag("cast",!1===t?void 0:t)}default(e,t){
3558
+ return this._default("default",e,t)}description(t){return e(t&&"string"==typeof t,"Description must be a non-empty string"),this.$_setFlag("description",t)}empty(e){const t=this.clone();return void 0!==e&&(e=t.$_compile(e,{override:!1})),t.$_setFlag("empty",e,{clone:!1})}error(t){return e(t,"Missing error"),e(t instanceof Error||"function"==typeof t,"Must provide a valid Error object or a function"),this.$_setFlag("error",t)}example(t,r={}){return e(void 0!==t,"Missing example"),s.assertOptions(r,["override"]),this._inner("examples",t,{single:!0,override:r.override})}external(t,r){return"object"==typeof t&&(e(!r,"Cannot combine options with description"),r=t.description,t=t.method),e("function"==typeof t,"Method must be a function"),e(void 0===r||r&&"string"==typeof r,"Description must be a non-empty string"),this._inner("externals",{method:t,description:r},{single:!0})}failover(e,t){return this._default("failover",e,t)}forbidden(){return this.presence("forbidden")}id(t){
3559
+ return t?(e("string"==typeof t,"id must be a non-empty string"),e(/^[^\.]+$/.test(t),"id cannot contain period character"),this.$_setFlag("id",t)):this.$_setFlag("id",void 0)}invalid(...e){return this._values(e,"_invalids")}label(t){return e(t&&"string"==typeof t,"Label name must be a non-empty string"),this.$_setFlag("label",t)}meta(t){return e(void 0!==t,"Meta cannot be undefined"),this._inner("metas",t,{single:!0})}note(...t){e(t.length,"Missing notes");for(const r of t)e(r&&"string"==typeof r,"Notes must be non-empty strings");return this._inner("notes",t)}only(t=!0){return e("boolean"==typeof t,"Invalid mode:",t),this.$_setFlag("only",t)}optional(){return this.presence("optional")}prefs(t){e(t,"Missing preferences"),e(void 0===t.context,"Cannot override context"),e(void 0===t.externals,"Cannot override externals"),e(void 0===t.warnings,"Cannot override warnings"),e(void 0===t.debug,"Cannot override debug"),s.checkPreferences(t);const r=this.clone()
3560
+ ;return r._preferences=s.preferences(r._preferences,t),r}presence(t){return e(["optional","required","forbidden"].includes(t),"Unknown presence mode",t),this.$_setFlag("presence",t)}raw(e=!0){return this.$_setFlag("result",e?"raw":void 0)}result(t){return e(["raw","strip"].includes(t),"Unknown result mode",t),this.$_setFlag("result",t)}required(){return this.presence("required")}strict(e){const t=this.clone(),r=void 0!==e&&!e;return t._preferences=s.preferences(t._preferences,{convert:r}),t}strip(e=!0){return this.$_setFlag("result",e?"strip":void 0)}tag(...t){e(t.length,"Missing tags");for(const r of t)e(r&&"string"==typeof r,"Tags must be non-empty strings");return this._inner("tags",t)}unit(t){return e(t&&"string"==typeof t,"Unit name must be a non-empty string"),this.$_setFlag("unit",t)}valid(...e){s.verifyFlat(e,"valid");const t=this.allow(...e);return t.$_setFlag("only",!!t._valids,{clone:!1}),t}when(t,r){const n=this.clone();n.$_terms.whens||(n.$_terms.whens=[])
3561
+ ;const i=o.when(n,t,r);if(!["any","link"].includes(n.type)){const t=i.is?[i]:i.switch;for(const r of t)e(!r.then||"any"===r.then.type||r.then.type===n.type,"Cannot combine",n.type,"with",r.then&&r.then.type),e(!r.otherwise||"any"===r.otherwise.type||r.otherwise.type===n.type,"Cannot combine",n.type,"with",r.otherwise&&r.otherwise.type)}return n.$_terms.whens.push(i),n.$_mutateRebuild()}cache(t){e(!this._inRuleset(),"Cannot set caching inside a ruleset"),e(!this._cache,"Cannot override schema cache"),e(void 0===this._flags.artifact,"Cannot cache a rule with an artifact");const r=this.clone();return r._cache=t||i.provider.provision(),r.$_temp.ruleset=!1,r}clone(){const e=Object.create(Object.getPrototypeOf(this));return this._assign(e)}concat(t){e(s.isSchema(t),"Invalid schema object"),e("any"===this.type||"any"===t.type||t.type===this.type,"Cannot merge type",this.type,"with another type:",t.type),e(!this._inRuleset(),"Cannot concatenate onto a schema with open ruleset"),
3562
+ e(!t._inRuleset(),"Cannot concatenate a schema with open ruleset");let r=this.clone();if("any"===this.type&&"any"!==t.type){const e=t.clone();for(const t of Object.keys(r))"type"!==t&&(e[t]=r[t]);r=e}r._ids.concat(t._ids),r._refs.register(t,p.toSibling),r._preferences=r._preferences?s.preferences(r._preferences,t._preferences):t._preferences,r._valids=f.merge(r._valids,t._valids,t._invalids),r._invalids=f.merge(r._invalids,t._invalids,t._valids);for(const e of t._singleRules.keys())r._singleRules.has(e)&&(r._rules=r._rules.filter(t=>t.keep||t.name!==e),r._singleRules.delete(e));for(const e of t._rules)t._definition.rules[e.method].multi||r._singleRules.set(e.name,e),r._rules.push(e);if(r._flags.empty&&t._flags.empty){r._flags.empty=r._flags.empty.concat(t._flags.empty);const e=Object.assign({},t._flags);delete e.empty,n(r._flags,e)}else if(t._flags.empty){r._flags.empty=t._flags.empty;const e=Object.assign({},t._flags);delete e.empty,n(r._flags,e)}else n(r._flags,t._flags)
3563
+ ;for(const e in t.$_terms){const n=t.$_terms[e];n?r.$_terms[e]?r.$_terms[e]=r.$_terms[e].concat(n):r.$_terms[e]=n.slice():r.$_terms[e]||(r.$_terms[e]=n)}return this.$_root._tracer&&this.$_root._tracer._combine(r,[this,t]),r.$_mutateRebuild()}extend(t){return e(!t.base,"Cannot extend type with another base"),c.type(this,t)}extract(e){return e=Array.isArray(e)?e:e.split("."),this._ids.reach(e)}fork(t,r){e(!this._inRuleset(),"Cannot fork inside a ruleset");let n=this;for(let e of[].concat(t))e=Array.isArray(e)?e:e.split("."),n=n._ids.fork(e,r,n);return n.$_temp.ruleset=!1,n}isAsync(){if(Boolean(this.$_terms.externals?.length))return!0;if(this.$_terms.whens)for(const e of this.$_terms.whens){if(e.then?.isAsync())return!0;if(e.otherwise?.isAsync())return!0;if(e.switch)for(const t of e.switch){if(t.then?.isAsync())return!0;if(t.otherwise?.isAsync())return!0}}return!1}rule(r){const n=this._definition;s.assertOptions(r,Object.keys(n.modifiers)),
3564
+ e(!1!==this.$_temp.ruleset,"Cannot apply rules to empty ruleset or the last rule added does not support rule properties");const i=null===this.$_temp.ruleset?this._rules.length-1:this.$_temp.ruleset;e(i>=0&&i<this._rules.length,"Cannot apply rules to empty ruleset");const o=this.clone();for(let s=i;s<o._rules.length;++s){const i=o._rules[s],a=t(i);for(const t in r)n.modifiers[t](a,r[t]),e(a.name===i.name,"Cannot change rule name");o._rules[s]=a,o._singleRules.get(a.name)===i&&o._singleRules.set(a.name,a)}return o.$_temp.ruleset=!1,o.$_mutateRebuild()}get ruleset(){e(!this._inRuleset(),"Cannot start a new ruleset without closing the previous one");const t=this.clone();return t.$_temp.ruleset=t._rules.length,t}get $(){return this.ruleset}tailor(t){t=[].concat(t),e(!this._inRuleset(),"Cannot tailor inside a ruleset");let r=this;if(this.$_terms.alterations)for(const{target:n,adjuster:i}of this.$_terms.alterations)t.includes(n)&&(r=i(r),
3565
+ e(s.isSchema(r),"Alteration adjuster for",n,"failed to return a schema object"));return r=r.$_modify({each:e=>e.tailor(t),ref:!1}),r.$_temp.ruleset=!1,r.$_mutateRebuild()}tracer(){return h.location?h.location(this):this}validate(e,t){return A.entry(e,this,t)}validateAsync(e,t){return A.entryAsync(e,this,t)}$_addRule(t){"string"==typeof t&&(t={name:t}),e(t&&"object"==typeof t,"Invalid options"),e(t.name&&"string"==typeof t.name,"Invalid rule name");for(const r in t)e("_"!==r[0],"Cannot set private rule properties");const r=Object.assign({},t);r._resolve=[],r.method=r.method||r.name;const n=this._definition.rules[r.method],i=r.args;e(n,"Unknown rule",r.method);const o=this.clone();if(i){e(1===Object.keys(i).length||Object.keys(i).length===this._definition.rules[r.name].args.length,"Invalid rule definition for",this.type,r.name);for(const t in i){let a=i[t];if(n.argsByName){const c=n.argsByName.get(t);if(c.ref&&s.isResolvable(a))r._resolve.push(t),
3566
+ o.$_mutateRegister(a);else if(c.normalize&&(a=c.normalize(a),i[t]=a),c.assert){const r=s.validateArg(a,t,c);e(!r,r,"or reference")}}void 0!==a?i[t]=a:delete i[t]}}return n.multi||(o._ruleRemove(r.name,{clone:!1}),o._singleRules.set(r.name,r)),!1===o.$_temp.ruleset&&(o.$_temp.ruleset=null),n.priority?o._rules.unshift(r):o._rules.push(r),o}$_compile(e,t){return o.schema(this.$_root,e,t)}$_createError(e,t,r,n,i,s={}){const o=!1!==s.flags?this._flags:{},c=s.messages?l.merge(this._definition.messages,s.messages):this._definition.messages;return new a.Report(e,t,r,o,c,n,i)}$_getFlag(e){return this._flags[e]}$_getRule(e){return this._singleRules.get(e)}$_mapLabels(e){return e=Array.isArray(e)?e:e.split("."),this._ids.labels(e)}$_match(e,t,r,n){(r=Object.assign({},r)).abortEarly=!0,r._externals=!1,t.snapshot();const i=!A.validate(e,this,t,r,n).errors;return t.restore(),i}$_modify(e){return s.assertOptions(e,["each","once","ref","schema"]),d.schema(this,e)||this}$_mutateRebuild(){
3567
+ e(!this._inRuleset(),"Cannot add this rule inside a ruleset"),this._refs.reset(),this._ids.reset();return this.$_modify({each:(e,{source:t,name:r,path:n,key:i})=>{const s=this._definition[t][r]&&this._definition[t][r].register;!1!==s&&this.$_mutateRegister(e,{family:s,key:i})}}),this._definition.rebuild&&this._definition.rebuild(this),this.$_temp.ruleset=!1,this}$_mutateRegister(e,{family:t,key:r}={}){this._refs.register(e,t),this._ids.register(e,{key:r})}$_property(e){return this._definition.properties[e]}$_reach(e){return this._ids.reach(e)}$_rootReferences(){return this._refs.roots()}$_setFlag(t,n,i={}){e("_"===t[0]||!this._inRuleset(),"Cannot set flag inside a ruleset");const s=this._definition.flags[t]||{};if(r(n,s.default)&&(n=void 0),r(n,this._flags[t]))return this;const o=!1!==i.clone?this.clone():this;return void 0!==n?(o._flags[t]=n,o.$_mutateRegister(n)):delete o._flags[t],"_"!==t[0]&&(o.$_temp.ruleset=!1),o}$_parent(e,...t){return this[e][s.symbols.parent].call(this,...t)}
3568
+ $_validate(e,t,r){return A.validate(e,this,t,r)}_assign(e){e.type=this.type,e.$_root=this.$_root,e.$_temp=Object.assign({},this.$_temp),e.$_temp.whens={},e._ids=this._ids.clone(),e._preferences=this._preferences,e._valids=this._valids&&this._valids.clone(),e._invalids=this._invalids&&this._invalids.clone(),e._rules=this._rules.slice(),e._singleRules=t(this._singleRules,{shallow:!0}),e._refs=this._refs.clone(),e._flags=Object.assign({},this._flags),e._cache=null,e.$_terms={};for(const t in this.$_terms)e.$_terms[t]=this.$_terms[t]?this.$_terms[t].slice():null;e.$_super={};for(const t in this.$_super)e.$_super[t]=this._super[t].bind(e);return e}_bare(){const e=this.clone();e._reset();const t=e._definition.terms;for(const r in t){const n=t[r];e.$_terms[r]=n.init}return e.$_mutateRebuild()}_default(t,r,n={}){s.assertOptions(n,"literal"),e(void 0!==r,"Missing",t,"value"),e("function"==typeof r||!n.literal,"Only function value supports literal option"),"function"==typeof r&&n.literal&&(r={
3569
+ [s.symbols.literal]:!0,literal:r});return this.$_setFlag(t,r)}_generate(e,t,r){if(!this.$_terms.whens)return{schema:this};const n=[],i=[];for(let s=0;s<this.$_terms.whens.length;++s){const o=this.$_terms.whens[s];if(o.concat){n.push(o.concat),i.push(`${s}.concat`);continue}const a=o.ref?o.ref.resolve(e,t,r):e,c=o.is?[o]:o.switch,u=i.length;for(let u=0;u<c.length;++u){const{is:l,then:d,otherwise:p}=c[u],h=`${s}${o.switch?"."+u:""}`;if(l.$_match(a,t.nest(l,`${h}.is`),r)){if(d){const s=t.localize([...t.path,`${h}.then`],t.ancestors,t.schemas),{schema:o,id:a}=d._generate(e,s,r);n.push(o),i.push(`${h}.then${a?`(${a})`:""}`);break}}else if(p){const s=t.localize([...t.path,`${h}.otherwise`],t.ancestors,t.schemas),{schema:o,id:a}=p._generate(e,s,r);n.push(o),i.push(`${h}.otherwise${a?`(${a})`:""}`);break}}if(o.break&&i.length>u)break}const s=i.join(", ");if(t.mainstay.tracer.debug(t,"rule","when",s),!s)return{schema:this};if(!t.mainstay.tracer.active&&this.$_temp.whens[s])return{
3570
+ schema:this.$_temp.whens[s],id:s};let o=this;this._definition.generate&&(o=this._definition.generate(this,e,t,r));for(const e of n)o=o.concat(e);return this.$_root._tracer&&this.$_root._tracer._combine(o,[this,...n]),this.$_temp.whens[s]=o,{schema:o,id:s}}_inner(t,r,n={}){e(!this._inRuleset(),`Cannot set ${t} inside a ruleset`);const i=this.clone();return i.$_terms[t]&&!n.override||(i.$_terms[t]=[]),n.single?i.$_terms[t].push(r):i.$_terms[t].push(...r),i.$_temp.ruleset=!1,i}_inRuleset(){return null!==this.$_temp.ruleset&&!1!==this.$_temp.ruleset}_ruleRemove(e,t={}){if(!this._singleRules.has(e))return this;const r=!1!==t.clone?this.clone():this;r._singleRules.delete(e);const n=[];for(let t=0;t<r._rules.length;++t){const i=r._rules[t];i.name!==e||i.keep?n.push(i):r._inRuleset()&&t<r.$_temp.ruleset&&--r.$_temp.ruleset}return r._rules=n,r}_values(t,r){s.verifyFlat(t,r.slice(1,-1));const n=this.clone(),i=t[0]===s.symbols.override;if(i&&(t=t.slice(1)),
3571
+ !n[r]&&t.length?n[r]=new f:i&&(n[r]=t.length?new f:null,n.$_mutateRebuild()),!n[r])return n;i&&n[r].override();for(const i of t){e(void 0!==i,"Cannot call allow/valid/invalid with undefined"),e(i!==s.symbols.override,"Override must be the first value");const t="_invalids"===r?"_valids":"_invalids";n[t]&&(n[t].remove(i),n[t].length||(e("_valids"===r||!n._flags.only,"Setting invalid value",i,"leaves schema rejecting all values due to previous valid rule"),n[t]=null)),n[r].add(i,n._refs)}return n}get"~standard"(){const e=e=>{let t;return t=a.ValidationError.isError(e)?e.details.map(({message:e,path:t})=>({message:e,path:t})):[{message:e.message}],{issues:t}},t=e=>({value:e});return{version:1,vendor:"joi",validate:r=>{const n=A.standard(r,this);return n instanceof Promise?n.then(t,e):n.error?e(n.error):t(n.value)}}}}};return g.Base.prototype[s.symbols.any]={version:s.version,compile:o.compile,root:"$_root"},g.Base.prototype.isImmutable=!0,g.Base.prototype.deny=g.Base.prototype.invalid,
3572
+ g.Base.prototype.disallow=g.Base.prototype.invalid,g.Base.prototype.equal=g.Base.prototype.valid,g.Base.prototype.exist=g.Base.prototype.required,g.Base.prototype.not=g.Base.prototype.invalid,g.Base.prototype.options=g.Base.prototype.prefs,g.Base.prototype.preferences=g.Base.prototype.prefs,base=new g.Base}function requireAny(){if(hasRequiredAny)return any;hasRequiredAny=1;const{assert:e}=requireLib$4(),t=requireBase(),r=requireCommon(),n=requireMessages();return any=t.extend({type:"any",flags:{only:{default:!1}},terms:{alterations:{init:null},examples:{init:null},externals:{init:null},metas:{init:[]},notes:{init:[]},shared:{init:null},tags:{init:[]},whens:{init:null}},rules:{custom:{method(t,r){return e("function"==typeof t,"Method must be a function"),e(void 0===r||r&&"string"==typeof r,"Description must be a non-empty string"),this.$_addRule({name:"custom",args:{method:t,description:r}})},validate(e,t,{method:r}){try{return r(e,t)}catch(e){return t.error("any.custom",{error:e})}},
3573
+ args:["method","description"],multi:!0},messages:{method(e){return this.prefs({messages:e})}},shared:{method(t){e(r.isSchema(t)&&t._flags.id,"Schema must be a schema with an id");const n=this.clone();return n.$_terms.shared=n.$_terms.shared||[],n.$_terms.shared.push(t),n.$_mutateRegister(t),n}},warning:{method(t,r){return e(t&&"string"==typeof t,"Invalid warning code"),this.$_addRule({name:"warning",args:{code:t,local:r},warn:!0})},validate:(e,t,{code:r,local:n})=>t.error(r,n),args:["code","local"],multi:!0}},modifiers:{keep(e,t=!0){e.keep=t},message(e,t){e.message=n.compile(t)},warn(e,t=!0){e.warn=t}},manifest:{build(e,t){for(const r in t){const n=t[r];if(["examples","externals","metas","notes","tags"].includes(r))for(const t of n)e=e[r.slice(0,-1)](t);else{if("alterations"===r){const t={};for(const{target:e,adjuster:r}of n)t[e]=r;e=e.alter(t);continue}if("whens"!==r){if("shared"===r)for(const t of n)e=e.shared(t)}else for(const t of n){
3574
+ const{ref:r,is:n,not:i,then:s,otherwise:o,concat:a}=t;e=a?e.concat(a):r?e.when(r,{is:n,not:i,then:s,otherwise:o,switch:t.switch,break:t.break}):e.when(n,{then:s,otherwise:o,break:t.break})}}}return e}},messages:{"any.custom":"{{#label}} failed custom validation because {{#error.message}}","any.default":"{{#label}} threw an error when running default method","any.failover":"{{#label}} threw an error when running failover method","any.invalid":"{{#label}} contains an invalid value","any.only":'{{#label}} must be {if(#valids.length == 1, "", "one of ")}{{#valids}}',"any.ref":"{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}","any.required":"{{#label}} is required","any.unknown":"{{#label}} is not allowed"}}),any}function requireAlternatives(){if(hasRequiredAlternatives)return alternatives;hasRequiredAlternatives=1;const{assert:e,merge:t}=requireLib$4(),r=requireAny(),n=requireCommon(),i=requireCompile(),s=requireErrors$1(),o=requireRef$1(),a={};return alternatives=r.extend({
3575
+ type:"alternatives",flags:{match:{default:"any"}},terms:{matches:{init:[],register:o.toSibling}},args:(e,...t)=>1===t.length&&Array.isArray(t[0])?e.try(...t[0]):e.try(...t),validate(e,r){const{schema:n,error:i,state:o,prefs:c}=r;if(n._flags.match){const r=[],a=[];for(let t=0;t<n.$_terms.matches.length;++t){const i=n.$_terms.matches[t],s=o.nest(i.schema,`match.${t}`);s.snapshot();const u=i.schema.$_validate(e,s,c);u.errors?(a.push(u.errors),s.restore()):(r.push(u.value),s.commit())}if(0===r.length){return{errors:i("alternatives.any",{details:a.map(e=>s.details(e,{override:!1}))})}}if("one"===n._flags.match)return 1===r.length?{value:r[0]}:{errors:i("alternatives.one")};if(r.length!==n.$_terms.matches.length){return{errors:i("alternatives.all",{details:a.map(e=>s.details(e,{override:!1}))})}}const u=e=>e.$_terms.matches.some(e=>"object"===e.schema.type||"alternatives"===e.schema.type&&u(e.schema));return u(n)?{value:r.reduce((e,r)=>t(e,r,{mergeArrays:!1}))}:{value:r[r.length-1]}}
3576
+ const u=[];for(let t=0;t<n.$_terms.matches.length;++t){const r=n.$_terms.matches[t];if(r.schema){const n=o.nest(r.schema,`match.${t}`);n.snapshot();const i=r.schema.$_validate(e,n,c);if(!i.errors)return n.commit(),i;n.restore(),u.push({schema:r.schema,reports:i.errors});continue}const i=r.ref?r.ref.resolve(e,o,c):e,s=r.is?[r]:r.switch;for(let n=0;n<s.length;++n){const a=s[n],{is:u,then:l,otherwise:d}=a,p=`match.${t}${r.switch?"."+n:""}`;if(u.$_match(i,o.nest(u,`${p}.is`),c)){if(l)return l.$_validate(e,o.nest(l,`${p}.then`),c)}else if(d)return d.$_validate(e,o.nest(d,`${p}.otherwise`),c)}}return a.errors(u,r)},rules:{conditional:{method(t,r){e(!this._flags._endedSwitch,"Unreachable condition"),e(!this._flags.match,"Cannot combine match mode",this._flags.match,"with conditional rule"),e(void 0===r.break,"Cannot use break option with alternatives conditional");const n=this.clone(),s=i.when(n,t,r),o=s.is?[s]:s.switch;for(const e of o)if(e.then&&e.otherwise){n.$_setFlag("_endedSwitch",!0,{
3577
+ clone:!1});break}return n.$_terms.matches.push(s),n.$_mutateRebuild()}},match:{method(t){if(e(["any","one","all"].includes(t),"Invalid alternatives match mode",t),"any"!==t)for(const r of this.$_terms.matches)e(r.schema,"Cannot combine match mode",t,"with conditional rules");return this.$_setFlag("match",t)}},try:{method(...t){e(t.length,"Missing alternative schemas"),n.verifyFlat(t,"try"),e(!this._flags._endedSwitch,"Unreachable condition");const r=this.clone();for(const e of t)r.$_terms.matches.push({schema:r.$_compile(e)});return r.$_mutateRebuild()}}},overrides:{label(e){return this.$_parent("label",e).$_modify({each:(t,r)=>"is"!==r.path[0]&&"string"!=typeof t._flags.label?t.label(e):void 0,ref:!1})},isAsync(){if(this.$_terms.externals?.length)return!0;for(const e of this.$_terms.matches){if(e.schema?.isAsync())return!0;if(e.then?.isAsync())return!0;if(e.otherwise?.isAsync())return!0}return!1}},rebuild(e){e.$_modify({each:t=>{
3578
+ n.isSchema(t)&&"array"===t.type&&e.$_setFlag("_arrayItems",!0,{clone:!1})}})},manifest:{build(e,t){if(t.matches)for(const r of t.matches){const{schema:t,ref:n,is:i,not:s,then:o,otherwise:a}=r;e=t?e.try(t):n?e.conditional(n,{is:i,then:o,not:s,otherwise:a,switch:r.switch}):e.conditional(i,{then:o,otherwise:a})}return e}},messages:{"alternatives.all":"{{#label}} does not match all of the required types","alternatives.any":"{{#label}} does not match any of the allowed types","alternatives.match":"{{#label}} does not match any of the allowed types","alternatives.one":"{{#label}} matches more than one allowed type","alternatives.types":"{{#label}} must be one of {{#types}}"}}),a.errors=function(e,{error:t,state:r}){if(!e.length)return{errors:t("alternatives.any")};if(1===e.length)return{errors:e[0].reports};const n=new Set,i=[];for(const{reports:o,schema:c}of e){if(o.length>1)return a.unmatched(e,t);const u=o[0];if(u instanceof s.Report==!1)return a.unmatched(e,t)
3579
+ ;if(u.state.path.length!==r.path.length){i.push({type:c.type,report:u});continue}if("any.only"===u.code){for(const e of u.local.valids)n.add(e);continue}const[l,d]=u.code.split(".");"base"!==d?i.push({type:c.type,report:u}):"object.base"===u.code?n.add(u.local.type):n.add(l)}return i.length?1===i.length?{errors:i[0].report}:a.unmatched(e,t):{errors:t("alternatives.types",{types:[...n]})}},a.unmatched=function(e,t){const r=[];for(const t of e)r.push(...t.reports);return{errors:t("alternatives.match",s.details(r,{override:!1}))}},alternatives}function requireArray(){if(hasRequiredArray)return array;hasRequiredArray=1;const{assert:e,deepEqual:t,reach:r}=requireLib$4(),n=requireAny(),i=requireCommon(),s=requireCompile(),o={};return array=n.extend({type:"array",flags:{single:{default:!1},sparse:{default:!1}},terms:{items:{init:[],manifest:"schema"},ordered:{init:[],manifest:"schema"},_exclusions:{init:[]},_inclusions:{init:[]},_requireds:{init:[]}},coerce:{from:"object",
3580
+ method(e,{schema:t,state:r,prefs:n}){if(!Array.isArray(e))return;const i=t.$_getRule("sort");return i?o.sort(t,e,i.args.options,r,n):void 0}},validate(e,{schema:t,error:r}){if(!Array.isArray(e)){if(t._flags.single){const t=[e];return t[i.symbols.arraySingle]=!0,{value:t}}return{errors:r("array.base")}}if(t.$_getRule("items")||t.$_terms.externals)return{value:e.slice()}},rules:{has:{method(e){e=this.$_compile(e,{appendPath:!0});const t=this.$_addRule({name:"has",args:{schema:e}});return t.$_mutateRegister(e),t},validate(e,{state:t,prefs:r,error:n},{schema:i}){const s=[e,...t.ancestors];for(let n=0;n<e.length;++n){const o=t.localize([...t.path,n],s,i);if(i.$_match(e[n],o,r))return e}const o=i._flags.label;return o?n("array.hasKnown",{patternLabel:o}):n("array.hasUnknown",null)},multi:!0},items:{method(...e){i.verifyFlat(e,"items");const t=this.$_addRule("items");for(let r=0;r<e.length;++r){const n=i.tryWithPath(()=>this.$_compile(e[r]),r,{append:!0});t.$_terms.items.push(n)}
3581
+ return t.$_mutateRebuild()},validate(e,{schema:t,error:r,state:n,prefs:s,errorsArray:a}){const c=t.$_terms._requireds.slice(),u=t.$_terms.ordered.slice(),l=[...t.$_terms._inclusions,...c],d=!e[i.symbols.arraySingle];delete e[i.symbols.arraySingle];const p=a();let h=e.length;for(let i=0;i<h;++i){const a=e[i];let A=!1,f=!1;const g=d?i:new Number(i),m=[...n.path,g];if(!t._flags.sparse&&void 0===a){if(p.push(r("array.sparse",{key:g,path:m,pos:i,value:void 0},n.localize(m))),s.abortEarly)return p;u.shift();continue}const y=[e,...n.ancestors];for(const e of t.$_terms._exclusions)if(e.$_match(a,n.localize(m,y,e),s,{presence:"ignore"})){if(p.push(r("array.excludes",{pos:i,value:a},n.localize(m))),s.abortEarly)return p;A=!0,u.shift();break}if(A)continue;if(t.$_terms.ordered.length){if(u.length){const c=u.shift(),l=c.$_validate(a,n.localize(m,y,c),s);if(l.errors){if(p.push(...l.errors),s.abortEarly)return p}else if("strip"===c._flags.result)o.fastSplice(e,i),--i,--h;else{
3582
+ if(!t._flags.sparse&&void 0===l.value){if(p.push(r("array.sparse",{key:g,path:m,pos:i,value:void 0},n.localize(m))),s.abortEarly)return p;continue}e[i]=l.value}continue}if(!t.$_terms.items.length){if(p.push(r("array.orderedLength",{pos:i,limit:t.$_terms.ordered.length})),s.abortEarly)return p;break}}const E=[];let b=c.length;for(let u=0;u<b;++u){const l=n.localize(m,y,c[u]);l.snapshot();const d=c[u].$_validate(a,l,s);if(E[u]=d,!d.errors){if(l.commit(),e[i]=d.value,f=!0,o.fastSplice(c,u),--u,--b,!t._flags.sparse&&void 0===d.value&&(p.push(r("array.sparse",{key:g,path:m,pos:i,value:void 0},n.localize(m))),s.abortEarly))return p;break}l.restore()}if(f)continue;const C=s.stripUnknown&&!!s.stripUnknown.arrays||!1;b=l.length;for(const u of l){let l;const d=c.indexOf(u);if(-1!==d)l=E[d];else{const c=n.localize(m,y,u);if(c.snapshot(),l=u.$_validate(a,c,s),!l.errors){c.commit(),"strip"===u._flags.result?(o.fastSplice(e,i),--i,
3583
+ --h):t._flags.sparse||void 0!==l.value?e[i]=l.value:(p.push(r("array.sparse",{key:g,path:m,pos:i,value:void 0},n.localize(m))),A=!0),f=!0;break}c.restore()}if(1===b){if(C){o.fastSplice(e,i),--i,--h,f=!0;break}if(p.push(...l.errors),s.abortEarly)return p;A=!0;break}}if(!A&&((t.$_terms._inclusions.length||t.$_terms._requireds.length)&&!f)){if(C){o.fastSplice(e,i),--i,--h;continue}if(p.push(r("array.includes",{pos:i,value:a},n.localize(m))),s.abortEarly)return p}}return c.length&&o.fillMissedErrors(t,p,c,e,n,s),u.length&&(o.fillOrderedErrors(t,p,u,e,n,s),p.length||o.fillDefault(u,e,n,s)),p.length?p:e},priority:!0,manifest:!1},length:{method(e){return this.$_addRule({name:"length",args:{limit:e},operator:"="})},validate:(e,t,{limit:r},{name:n,operator:s,args:o})=>i.compare(e.length,r,s)?e:t.error("array."+n,{limit:o.limit,value:e}),args:[{name:"limit",ref:!0,assert:i.limit,message:"must be a positive integer"}]},max:{method(e){return this.$_addRule({name:"max",method:"length",args:{limit:e
3584
+ },operator:"<="})}},min:{method(e){return this.$_addRule({name:"min",method:"length",args:{limit:e},operator:">="})}},ordered:{method(...e){i.verifyFlat(e,"ordered");const t=this.$_addRule("items");for(let r=0;r<e.length;++r){const n=i.tryWithPath(()=>this.$_compile(e[r]),r,{append:!0});o.validateSingle(n,t),t.$_mutateRegister(n),t.$_terms.ordered.push(n)}return t.$_mutateRebuild()}},single:{method(t){const r=void 0===t||!!t;return e(!r||!this._flags._arrayItems,"Cannot specify single rule when array has array items"),this.$_setFlag("single",r)}},sort:{method(t={}){i.assertOptions(t,["by","order"]);const r={order:t.order||"ascending"};return t.by&&(r.by=s.ref(t.by,{ancestor:0}),e(!r.by.ancestor,"Cannot sort by ancestor")),this.$_addRule({name:"sort",args:{options:r}})},validate(e,{error:t,state:r,prefs:n,schema:i},{options:s}){const{value:a,errors:c}=o.sort(i,e,s,r,n);if(c)return c;for(let r=0;r<e.length;++r)if(e[r]!==a[r])return t("array.sort",{order:s.order,by:s.by?s.by.key:"value"})
3585
+ ;return e},convert:!0},sparse:{method(e){const t=void 0===e||!!e;if(this._flags.sparse===t)return this;return(t?this.clone():this.$_addRule("items")).$_setFlag("sparse",t,{clone:!1})}},unique:{method(t,r={}){e(!t||"function"==typeof t||"string"==typeof t,"comparator must be a function or a string"),i.assertOptions(r,["ignoreUndefined","separator"]);const n={name:"unique",args:{options:r,comparator:t}};if(t)if("string"==typeof t){const e=i.default(r.separator,".");n.path=e?t.split(e):[t]}else n.comparator=t;return this.$_addRule(n)},validate(n,{state:i,error:s,schema:o},{comparator:a,options:c},{comparator:u,path:l}){const d={string:Object.create(null),number:Object.create(null),undefined:Object.create(null),boolean:Object.create(null),bigint:Object.create(null),object:new Map,function:new Map,custom:new Map},p=u||t,h=c.ignoreUndefined;for(let t=0;t<n.length;++t){const o=l?r(n[t],l):n[t],c=u?d.custom:d[typeof o];if(e(c,"Failed to find unique map container for type",typeof o),
3586
+ c instanceof Map){const e=c.entries();let r;for(;!(r=e.next()).done;)if(p(r.value[0],o)){const e=i.localize([...i.path,t],[n,...i.ancestors]),o={pos:t,value:n[t],dupePos:r.value[1],dupeValue:n[r.value[1]]};return l&&(o.path=a),s("array.unique",o,e)}c.set(o,t)}else{if((!h||void 0!==o)&&void 0!==c[o]){const e={pos:t,value:n[t],dupePos:c[o],dupeValue:n[c[o]]};l&&(e.path=a);return s("array.unique",e,i.localize([...i.path,t],[n,...i.ancestors]))}c[o]=t}}return n},args:["comparator","options"],multi:!0}},overrides:{isAsync(){if(this.$_terms.externals?.length)return!0;for(const e of this.$_terms.items)if(e.isAsync())return!0;for(const e of this.$_terms.ordered)if(e.isAsync())return!0;return!1}},cast:{set:{from:Array.isArray,to:(e,t)=>new Set(e)}},rebuild(e){e.$_terms._inclusions=[],e.$_terms._exclusions=[],e.$_terms._requireds=[];for(const t of e.$_terms.items)o.validateSingle(t,e),
3587
+ "required"===t._flags.presence?e.$_terms._requireds.push(t):"forbidden"===t._flags.presence?e.$_terms._exclusions.push(t):e.$_terms._inclusions.push(t);for(const t of e.$_terms.ordered)o.validateSingle(t,e)},manifest:{build:(e,t)=>(t.items&&(e=e.items(...t.items)),t.ordered&&(e=e.ordered(...t.ordered)),e)},messages:{"array.base":"{{#label}} must be an array","array.excludes":"{{#label}} contains an excluded value","array.hasKnown":"{{#label}} does not contain at least one required match for type {:#patternLabel}","array.hasUnknown":"{{#label}} does not contain at least one required match","array.includes":"{{#label}} does not match any of the allowed types","array.includesRequiredBoth":"{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)","array.includesRequiredKnowns":"{{#label}} does not contain {{#knownMisses}}","array.includesRequiredUnknowns":"{{#label}} does not contain {{#unknownMisses}} required value(s)",
3588
+ "array.length":"{{#label}} must contain {{#limit}} items","array.max":"{{#label}} must contain less than or equal to {{#limit}} items","array.min":"{{#label}} must contain at least {{#limit}} items","array.orderedLength":"{{#label}} must contain at most {{#limit}} items","array.sort":"{{#label}} must be sorted in {#order} order by {{#by}}","array.sort.mismatching":"{{#label}} cannot be sorted due to mismatching types","array.sort.unsupported":"{{#label}} cannot be sorted due to unsupported type {#type}","array.sparse":"{{#label}} must not be a sparse array item","array.unique":"{{#label}} contains a duplicate value"}}),o.fillMissedErrors=function(e,t,r,n,i,s){const o=[];let a=0;for(const e of r){const t=e._flags.label;t?o.push(t):++a}o.length?a?t.push(e.$_createError("array.includesRequiredBoth",n,{knownMisses:o,unknownMisses:a},i,s)):t.push(e.$_createError("array.includesRequiredKnowns",n,{knownMisses:o},i,s)):t.push(e.$_createError("array.includesRequiredUnknowns",n,{unknownMisses:a
3589
+ },i,s))},o.fillOrderedErrors=function(e,t,r,n,i,s){const a=[];for(const e of r)"required"===e._flags.presence&&a.push(e);a.length&&o.fillMissedErrors(e,t,a,n,i,s)},o.fillDefault=function(e,t,r,n){const i=[];let s=!0;for(let o=e.length-1;o>=0;--o){const a=e[o],c=[t,...r.ancestors],u=a.$_validate(void 0,r.localize(r.path,c,a),n).value;if(s){if(void 0===u)continue;s=!1}i.unshift(u)}i.length&&t.push(...i)},o.fastSplice=function(e,t){let r=t;for(;r<e.length;)e[r++]=e[r];--e.length},o.validateSingle=function(t,r){("array"===t.type||t._flags._arrayItems)&&(e(!r._flags.single,"Cannot specify array item with single rule enabled"),r.$_setFlag("_arrayItems",!0,{clone:!1}))},o.sort=function(e,t,r,n,i){const s="ascending"===r.order?1:-1,a=-1*s,c=s,u=(u,l)=>{let d=o.compare(u,l,a,c);if(null!==d)return d;if(r.by&&(u=r.by.resolve(u,n,i),l=r.by.resolve(l,n,i)),d=o.compare(u,l,a,c),null!==d)return d;const p=typeof u;if(p!==typeof l)throw e.$_createError("array.sort.mismatching",t,null,n,i)
3590
+ ;if("number"!==p&&"string"!==p)throw e.$_createError("array.sort.unsupported",t,{type:p},n,i);return"number"===p?(u-l)*s:u<l?a:c};try{return{value:t.slice().sort(u)}}catch(e){return{errors:e}}},o.compare=function(e,t,r,n){return e===t?0:void 0===e?1:void 0===t?-1:null===e?n:null===t?r:null},array}function requireBoolean(){if(hasRequiredBoolean)return boolean;hasRequiredBoolean=1;const{assert:e}=requireLib$4(),t=requireAny(),r=requireCommon(),n=requireValues(),i={isBool:function(e){return"boolean"==typeof e}};return boolean=t.extend({type:"boolean",flags:{sensitive:{default:!1}},terms:{falsy:{init:null,manifest:"values"},truthy:{init:null,manifest:"values"}},coerce(e,{schema:t}){if("boolean"!=typeof e){if("string"==typeof e){const r=t._flags.sensitive?e:e.toLowerCase();e="true"===r||"false"!==r&&e}return"boolean"!=typeof e&&(e=t.$_terms.truthy&&t.$_terms.truthy.has(e,null,null,!t._flags.sensitive)||(!t.$_terms.falsy||!t.$_terms.falsy.has(e,null,null,!t._flags.sensitive))&&e),{value:e}}
3591
+ },validate(e,{error:t}){if("boolean"!=typeof e)return{value:e,errors:t("boolean.base")}},rules:{truthy:{method(...t){r.verifyFlat(t,"truthy");const i=this.clone();i.$_terms.truthy=i.$_terms.truthy||new n;for(let r=0;r<t.length;++r){const n=t[r];e(void 0!==n,"Cannot call truthy with undefined"),i.$_terms.truthy.add(n)}return i}},falsy:{method(...t){r.verifyFlat(t,"falsy");const i=this.clone();i.$_terms.falsy=i.$_terms.falsy||new n;for(let r=0;r<t.length;++r){const n=t[r];e(void 0!==n,"Cannot call falsy with undefined"),i.$_terms.falsy.add(n)}return i}},sensitive:{method(e=!0){return this.$_setFlag("sensitive",e)}}},cast:{number:{from:i.isBool,to:(e,t)=>e?1:0},string:{from:i.isBool,to:(e,t)=>e?"true":"false"}},manifest:{build:(e,t)=>(t.truthy&&(e=e.truthy(...t.truthy)),t.falsy&&(e=e.falsy(...t.falsy)),e)},messages:{"boolean.base":"{{#label}} must be a boolean"}}),boolean}function requireDate(){if(hasRequiredDate)return date;hasRequiredDate=1
3592
+ ;const{assert:e}=requireLib$4(),t=requireAny(),r=requireCommon(),n=requireTemplate(),i={isDate:function(e){return e instanceof Date}};return date=t.extend({type:"date",coerce:{from:["number","string"],method:(e,{schema:t})=>({value:i.parse(e,t._flags.format)||e})},validate(e,{schema:t,error:r,prefs:n}){if(e instanceof Date&&!isNaN(e.getTime()))return;const i=t._flags.format;return n.convert&&i&&"string"==typeof e?{value:e,errors:r("date.format",{format:i})}:{value:e,errors:r("date.base")}},rules:{compare:{method:!1,validate(e,t,{date:n},{name:i,operator:s,args:o}){const a="now"===n?Date.now():n.getTime();return r.compare(e.getTime(),a,s)?e:t.error("date."+i,{limit:o.date,value:e})},args:[{name:"date",ref:!0,normalize:e=>"now"===e?e:i.parse(e),assert:e=>null!==e,message:"must have a valid date format"}]},format:{method(t){return e(["iso","javascript","unix"].includes(t),"Unknown date format",t),this.$_setFlag("format",t)}},greater:{method(e){return this.$_addRule({name:"greater",
3593
+ method:"compare",args:{date:e},operator:">"})}},iso:{method(){return this.format("iso")}},less:{method(e){return this.$_addRule({name:"less",method:"compare",args:{date:e},operator:"<"})}},max:{method(e){return this.$_addRule({name:"max",method:"compare",args:{date:e},operator:"<="})}},min:{method(e){return this.$_addRule({name:"min",method:"compare",args:{date:e},operator:">="})}},timestamp:{method(t="javascript"){return e(["javascript","unix"].includes(t),'"type" must be one of "javascript, unix"'),this.format(t)}}},cast:{number:{from:i.isDate,to:(e,t)=>e.getTime()},string:{from:i.isDate,to:(e,{prefs:t})=>n.date(e,t)}},messages:{"date.base":"{{#label}} must be a valid date","date.format":'{{#label}} must be in {msg("date.format." + #format) || #format} format',"date.greater":"{{#label}} must be greater than {{:#limit}}","date.less":"{{#label}} must be less than {{:#limit}}","date.max":"{{#label}} must be less than or equal to {{:#limit}}",
3594
+ "date.min":"{{#label}} must be greater than or equal to {{:#limit}}","date.format.iso":"ISO 8601 date","date.format.javascript":"timestamp or number of milliseconds","date.format.unix":"timestamp or number of seconds"}}),i.parse=function(e,t){if(e instanceof Date)return e;if("string"!=typeof e&&(isNaN(e)||!isFinite(e)))return null;if(/^\s*$/.test(e))return null;if("iso"===t)return r.isIsoDate(e)?i.date(e.toString()):null;const n=e;if("string"==typeof e&&/^[+-]?\d+(\.\d+)?$/.test(e)&&(e=parseFloat(e)),t){if("javascript"===t)return i.date(1*e);if("unix"===t)return i.date(1e3*e);if("string"==typeof n)return null}return i.date(e)},i.date=function(e){const t=new Date(e);return isNaN(t.getTime())?null:t},date}var lib$1={},hasRequiredLib$1,keys,hasRequiredKeys,_function,hasRequired_function,link,hasRequiredLink,number,hasRequiredNumber,object,hasRequiredObject;function requireLib$1(){if(hasRequiredLib$1)return lib$1;hasRequiredLib$1=1;const{assert:e}=requireLib$4(),t={}
3595
+ ;return lib$1.Sorter=class{constructor(){this._items=[],this.nodes=[]}add(t,r){const n=[].concat((r=r??{}).before??[]),i=[].concat(r.after??[]),s=r.group??"?",o=r.sort??0;e(!n.includes(s),`Item cannot come before itself: ${s}`),e(!n.includes("?"),"Item cannot come before unassociated items"),e(!i.includes(s),`Item cannot come after itself: ${s}`),e(!i.includes("?"),"Item cannot come after unassociated items"),Array.isArray(t)||(t=[t]);for(const e of t){const t={seq:this._items.length,sort:o,before:n,after:i,group:s,node:e};this._items.push(t)}if(!r.manual){const t=this._sort();e(t,"item","?"!==s?`added into group ${s}`:"","created a dependencies error")}return this.nodes}merge(r){Array.isArray(r)||(r=[r]);for(const e of r)if(e)for(const t of e._items)this._items.push(Object.assign({},t));this._items.sort(t.mergeSort);for(let e=0;e<this._items.length;++e)this._items[e].seq=e;const n=this._sort();return e(n,"merge created a dependencies error"),this.nodes}sort(){const t=this._sort()
3596
+ ;return e(t,"sort created a dependencies error"),this.nodes}_sort(){const e={},t=Object.create(null),r=Object.create(null);for(const n of this._items){const i=n.seq,s=n.group;r[s]=r[s]??[],r[s].push(i),e[i]=n.before;for(const e of n.after)t[e]=t[e]??[],t[e].push(i)}for(const t in e){const n=[];for(const i in e[t]){const s=e[t][i];r[s]=r[s]??[],n.push(...r[s])}e[t]=n}for(const n in t)if(r[n])for(const i of r[n])e[i].push(...t[n]);const n={};for(const t in e){const r=e[t];for(const e of r)n[e]=n[e]??[],n[e].push(t)}const i={},s=[];for(let e=0;e<this._items.length;++e){let t=e;if(n[e]){t=null;for(let e=0;e<this._items.length;++e){if(!0===i[e])continue;n[e]||(n[e]=[]);const r=n[e].length;let s=0;for(let t=0;t<r;++t)i[n[e][t]]&&++s;if(s===r){t=e;break}}}null!==t&&(i[t]=!0,s.push(t))}if(s.length!==this._items.length)return!1;const o={};for(const e of this._items)o[e.seq]=e;this._items=[],this.nodes=[];for(const e of s){const t=o[e];this.nodes.push(t.node),this._items.push(t)}return!0}},
3597
+ t.mergeSort=(e,t)=>e.sort===t.sort?0:e.sort<t.sort?-1:1,lib$1}function requireKeys(){if(hasRequiredKeys)return keys;hasRequiredKeys=1;const{applyToDefaults:e,assert:t,clone:r}=requireLib$4(),n=requireLib$1(),i=requireAny(),s=requireCommon(),o=requireCompile(),a=requireErrors$1(),c=requireRef$1(),u=requireTemplate(),l={renameDefaults:{alias:!1,multiple:!1,override:!1}};return keys=i.extend({type:"_keys",properties:{typeof:"object"},flags:{unknown:{default:void 0}},terms:{dependencies:{init:null},keys:{init:null,manifest:{mapped:{from:"schema",to:"key"}}},patterns:{init:null},renames:{init:null}},args:(e,t)=>e.keys(t),validate(e,{schema:t,error:r,state:n,prefs:i}){if(!e||typeof e!==t.$_property("typeof")||Array.isArray(e))return{value:e,errors:r("object.base",{type:t.$_property("typeof")})};if(!(t.$_terms.renames||t.$_terms.dependencies||t.$_terms.keys||t.$_terms.patterns||t.$_terms.externals))return;e=l.clone(e,i);const s=[];if(t.$_terms.renames&&!l.rename(t,e,n,i,s))return{value:e,
3598
+ errors:s};if(!t.$_terms.keys&&!t.$_terms.patterns&&!t.$_terms.dependencies)return{value:e,errors:s};const o=new Set(Object.keys(e));if(t.$_terms.keys){const r=[e,...n.ancestors];for(const a of t.$_terms.keys){const t=a.key,c=e[t];o.delete(t);const u=n.localize([...n.path,t],r,a),l=a.schema.$_validate(c,u,i);if(l.errors){if(i.abortEarly)return{value:e,errors:l.errors};void 0!==l.value&&(e[t]=l.value),s.push(...l.errors)}else"strip"===a.schema._flags.result||void 0===l.value&&void 0!==c?delete e[t]:void 0!==l.value&&(e[t]=l.value)}}if(o.size||t._flags._hasPatternMatch){const r=l.unknown(t,e,o,s,n,i);if(r)return r}if(t.$_terms.dependencies)for(const r of t.$_terms.dependencies){if(null!==r.key&&!1===l.isPresent(r.options)(r.key.resolve(e,n,i,null,{shadow:!1})))continue;const o=l.dependencies[r.rel](t,r,e,n,i);if(o){const r=t.$_createError(o.code,e,o.context,n,i);if(i.abortEarly)return{value:e,errors:r};s.push(r)}}return{value:e,errors:s}},rules:{and:{method(...e){
3599
+ return s.verifyFlat(e,"and"),l.dependency(this,"and",null,e)}},append:{method(e){return null==e||0===Object.keys(e).length?this:this.keys(e)}},assert:{method(e,r,n){u.isTemplate(e)||(e=o.ref(e)),t(void 0===n||"string"==typeof n,"Message must be a string"),r=this.$_compile(r,{appendPath:!0});const i=this.$_addRule({name:"assert",args:{subject:e,schema:r,message:n}});return i.$_mutateRegister(e),i.$_mutateRegister(r),i},validate(e,{error:t,prefs:r,state:n},{subject:i,schema:s,message:o}){const a=i.resolve(e,n,r),u=c.isRef(i)?i.absolute(n):[];return s.$_match(a,n.localize(u,[e,...n.ancestors],s),r)?e:t("object.assert",{subject:i,message:o})},args:["subject","schema","message"],multi:!0},instance:{method(e,r){return t("function"==typeof e,"constructor must be a function"),r=r||e.name,this.$_addRule({name:"instance",args:{constructor:e,name:r}})},validate:(e,t,{constructor:r,name:n})=>e instanceof r?e:t.error("object.instance",{type:n,value:e}),args:["constructor","name"]},keys:{method(e){
3600
+ t(void 0===e||"object"==typeof e,"Object schema must be a valid object"),t(!s.isSchema(e),"Object schema cannot be a joi schema");const r=this.clone();if(e)if(Object.keys(e).length){r.$_terms.keys=r.$_terms.keys?r.$_terms.keys.filter(t=>!e.hasOwnProperty(t.key)):new l.Keys;for(const t in e)s.tryWithPath(()=>r.$_terms.keys.push({key:t,schema:this.$_compile(e[t])}),t)}else r.$_terms.keys=new l.Keys;else r.$_terms.keys=null;return r.$_mutateRebuild()}},length:{method(e){return this.$_addRule({name:"length",args:{limit:e},operator:"="})},validate:(e,t,{limit:r},{name:n,operator:i,args:o})=>s.compare(Object.keys(e).length,r,i)?e:t.error("object."+n,{limit:o.limit,value:e}),args:[{name:"limit",ref:!0,assert:s.limit,message:"must be a positive integer"}]},max:{method(e){return this.$_addRule({name:"max",method:"length",args:{limit:e},operator:"<="})}},min:{method(e){return this.$_addRule({name:"min",method:"length",args:{limit:e},operator:">="})}},nand:{method(...e){
3601
+ return s.verifyFlat(e,"nand"),l.dependency(this,"nand",null,e)}},or:{method(...e){return s.verifyFlat(e,"or"),l.dependency(this,"or",null,e)}},oxor:{method(...e){return l.dependency(this,"oxor",null,e)}},pattern:{method(e,r,n={}){const i=e instanceof RegExp;i||(e=this.$_compile(e,{appendPath:!0})),t(void 0!==r,"Invalid rule"),s.assertOptions(n,["fallthrough","matches"]),i&&t(!e.flags.includes("g")&&!e.flags.includes("y"),"pattern should not use global or sticky mode"),r=this.$_compile(r,{appendPath:!0});const o=this.clone();o.$_terms.patterns=o.$_terms.patterns||[];const a={[i?"regex":"schema"]:e,rule:r};return n.matches&&(a.matches=this.$_compile(n.matches),"array"!==a.matches.type&&(a.matches=a.matches.$_root.array().items(a.matches)),o.$_mutateRegister(a.matches),o.$_setFlag("_hasPatternMatch",!0,{clone:!1})),n.fallthrough&&(a.fallthrough=!0),o.$_terms.patterns.push(a),o.$_mutateRegister(r),o}},ref:{method(){return this.$_addRule("ref")},
3602
+ validate:(e,t)=>c.isRef(e)?e:t.error("object.refType",{value:e})},regex:{method(){return this.$_addRule("regex")},validate:(e,t)=>e instanceof RegExp?e:t.error("object.regex",{value:e})},rename:{method(r,n,i={}){t("string"==typeof r||r instanceof RegExp,"Rename missing the from argument"),t("string"==typeof n||n instanceof u,"Invalid rename to argument"),t(n!==r,"Cannot rename key to same name:",r),s.assertOptions(i,["alias","ignoreUndefined","override","multiple"]);const o=this.clone();o.$_terms.renames=o.$_terms.renames||[];for(const e of o.$_terms.renames)t(e.from!==r,"Cannot rename the same key multiple times");return n instanceof u&&o.$_mutateRegister(n),o.$_terms.renames.push({from:r,to:n,options:e(l.renameDefaults,i)}),o}},schema:{method(e="any"){return this.$_addRule({name:"schema",args:{type:e}})},validate:(e,t,{type:r})=>!s.isSchema(e)||"any"!==r&&e.type!==r?t.error("object.schema",{type:r}):e},unknown:{method(e){return this.$_setFlag("unknown",!1!==e)}},with:{
3603
+ method(e,t,r={}){return l.dependency(this,"with",e,t,r)}},without:{method(e,t,r={}){return l.dependency(this,"without",e,t,r)}},xor:{method(...e){return s.verifyFlat(e,"xor"),l.dependency(this,"xor",null,e)}}},overrides:{default(e,t){return void 0===e&&(e=s.symbols.deepDefault),this.$_parent("default",e,t)},isAsync(){if(this.$_terms.externals?.length)return!0;if(this.$_terms.keys?.length)for(const e of this.$_terms.keys)if(e.schema.isAsync())return!0;if(this.$_terms.patterns?.length)for(const e of this.$_terms.patterns)if(e.rule.isAsync())return!0;return!1}},rebuild(e){if(e.$_terms.keys){const t=new n.Sorter;for(const r of e.$_terms.keys)s.tryWithPath(()=>t.add(r,{after:r.schema.$_rootReferences(),group:r.key}),r.key);e.$_terms.keys=new l.Keys(...t.nodes)}},manifest:{build(e,t){if(t.keys&&(e=e.keys(t.keys)),t.dependencies)for(const{rel:r,key:n=null,peers:i,options:s}of t.dependencies)e=l.dependency(e,r,n,i,s)
3604
+ ;if(t.patterns)for(const{regex:r,schema:n,rule:i,fallthrough:s,matches:o}of t.patterns)e=e.pattern(r||n,i,{fallthrough:s,matches:o});if(t.renames)for(const{from:r,to:n,options:i}of t.renames)e=e.rename(r,n,i);return e}},messages:{"object.and":"{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}","object.assert":'{{#label}} is invalid because {if(#subject.key, `"` + #subject.key + `" failed to ` + (#message || "pass the assertion test"), #message || "the assertion failed")}',"object.base":"{{#label}} must be of type {{#type}}","object.instance":"{{#label}} must be an instance of {{:#type}}","object.length":'{{#label}} must have {{#limit}} key{if(#limit == 1, "", "s")}',"object.max":'{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, "", "s")}',"object.min":'{{#label}} must have at least {{#limit}} key{if(#limit == 1, "", "s")}',"object.missing":"{{#label}} must contain at least one of {{#peersWithLabels}}",
3605
+ "object.nand":"{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}","object.oxor":"{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}","object.pattern.match":"{{#label}} keys failed to match pattern requirements","object.refType":"{{#label}} must be a Joi reference","object.regex":"{{#label}} must be a RegExp object","object.rename.multiple":"{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}","object.rename.override":"{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists","object.schema":"{{#label}} must be a Joi schema of {{#type}} type","object.unknown":"{{#label}} is not allowed","object.with":"{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}","object.without":"{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}",
3606
+ "object.xor":"{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}"}}),l.clone=function(e,t){if("object"==typeof e){if(t.nonEnumerables)return r(e,{shallow:!0});const n=Object.create(Object.getPrototypeOf(e));return Object.assign(n,e),n}const n=function(...t){return e.apply(this,t)};return n.prototype=r(e.prototype),Object.defineProperty(n,"name",{value:e.name,writable:!1}),Object.defineProperty(n,"length",{value:e.length,writable:!1}),Object.assign(n,e),n},l.dependency=function(e,r,n,i,a){t(null===n||"string"==typeof n,r,"key must be a strings"),a||(a=i.length>1&&"object"==typeof i[i.length-1]?i.pop():{}),s.assertOptions(a,["separator","isPresent"]),i=[].concat(i);const c=s.default(a.separator,"."),u=[];for(const e of i)t("string"==typeof e,r,"peers must be strings"),u.push(o.ref(e,{separator:c,ancestor:0,prefix:!1}));null!==n&&(n=o.ref(n,{separator:c,ancestor:0,prefix:!1}));const d=e.clone();return d.$_terms.dependencies=d.$_terms.dependencies||[],
3607
+ d.$_terms.dependencies.push(new l.Dependency(r,n,u,i,a)),d},l.dependencies={and(e,t,r,n,i){const s=[],o=[],a=t.peers.length,c=l.isPresent(t.options);for(const e of t.peers)!1===c(e.resolve(r,n,i,null,{shadow:!1}))?s.push(e.key):o.push(e.key);if(s.length!==a&&o.length!==a)return{code:"object.and",context:{present:o,presentWithLabels:l.keysToLabels(e,o),missing:s,missingWithLabels:l.keysToLabels(e,s)}}},nand(e,t,r,n,i){const s=[],o=l.isPresent(t.options);for(const e of t.peers)o(e.resolve(r,n,i,null,{shadow:!1}))&&s.push(e.key);if(s.length!==t.peers.length)return;const a=t.paths[0],c=t.paths.slice(1);return{code:"object.nand",context:{main:a,mainWithLabel:l.keysToLabels(e,a),peers:c,peersWithLabels:l.keysToLabels(e,c)}}},or(e,t,r,n,i){const s=l.isPresent(t.options);for(const e of t.peers)if(s(e.resolve(r,n,i,null,{shadow:!1})))return;return{code:"object.missing",context:{peers:t.paths,peersWithLabels:l.keysToLabels(e,t.paths)}}},oxor(e,t,r,n,i){const s=[],o=l.isPresent(t.options)
3608
+ ;for(const e of t.peers)o(e.resolve(r,n,i,null,{shadow:!1}))&&s.push(e.key);if(!s.length||1===s.length)return;const a={peers:t.paths,peersWithLabels:l.keysToLabels(e,t.paths)};return a.present=s,a.presentWithLabels=l.keysToLabels(e,s),{code:"object.oxor",context:a}},with(e,t,r,n,i){const s=l.isPresent(t.options);for(const o of t.peers)if(!1===s(o.resolve(r,n,i,null,{shadow:!1})))return{code:"object.with",context:{main:t.key.key,mainWithLabel:l.keysToLabels(e,t.key.key),peer:o.key,peerWithLabel:l.keysToLabels(e,o.key)}}},without(e,t,r,n,i){const s=l.isPresent(t.options);for(const o of t.peers)if(s(o.resolve(r,n,i,null,{shadow:!1})))return{code:"object.without",context:{main:t.key.key,mainWithLabel:l.keysToLabels(e,t.key.key),peer:o.key,peerWithLabel:l.keysToLabels(e,o.key)}}},xor(e,t,r,n,i){const s=[],o=l.isPresent(t.options);for(const e of t.peers)o(e.resolve(r,n,i,null,{shadow:!1}))&&s.push(e.key);if(1===s.length)return;const a={peers:t.paths,peersWithLabels:l.keysToLabels(e,t.paths)}
3609
+ ;return 0===s.length?{code:"object.missing",context:a}:(a.present=s,a.presentWithLabels=l.keysToLabels(e,s),{code:"object.xor",context:a})}},l.keysToLabels=function(e,t){return Array.isArray(t)?t.map(t=>e.$_mapLabels(t)):e.$_mapLabels(t)},l.isPresent=function(e){return"function"==typeof e.isPresent?e.isPresent:e=>void 0!==e},l.rename=function(e,t,r,n,i){const s={};for(const o of e.$_terms.renames){const a=[],c="string"!=typeof o.from;if(c)for(const e in t){if(void 0===t[e]&&o.options.ignoreUndefined)continue;if(e===o.to)continue;const r=o.from.exec(e);r&&a.push({from:e,to:o.to,match:r})}else!Object.prototype.hasOwnProperty.call(t,o.from)||void 0===t[o.from]&&o.options.ignoreUndefined||a.push(o);for(const l of a){const a=l.from;let d=l.to;if(d instanceof u&&(d=d.render(t,r,n,l.match)),a!==d){if(!o.options.multiple&&s[d]&&(i.push(e.$_createError("object.rename.multiple",t,{from:a,to:d,pattern:c},r,n)),n.abortEarly))return!1
3610
+ ;if(Object.prototype.hasOwnProperty.call(t,d)&&!o.options.override&&!s[d]&&(i.push(e.$_createError("object.rename.override",t,{from:a,to:d,pattern:c},r,n)),n.abortEarly))return!1;void 0===t[a]?delete t[d]:t[d]=t[a],s[d]=!0,o.options.alias||delete t[a]}}}return!0},l.unknown=function(e,t,r,n,i,o){if(e.$_terms.patterns){let s=!1;const c=e.$_terms.patterns.map(e=>{if(e.matches)return s=!0,[]}),u=[t,...i.ancestors];for(const s of r){const a=t[s],l=[...i.path,s];for(let d=0;d<e.$_terms.patterns.length;++d){const p=e.$_terms.patterns[d];if(p.regex){const e=p.regex.test(s);if(i.mainstay.tracer.debug(i,"rule",`pattern.${d}`,e?"pass":"error"),!e)continue}else if(!p.schema.$_match(s,i.nest(p.schema,`pattern.${d}`),o))continue;r.delete(s);const h=i.localize(l,u,{schema:p.rule,key:s}),A=p.rule.$_validate(a,h,o);if(A.errors){if(o.abortEarly)return{value:t,errors:A.errors};n.push(...A.errors)}if(p.matches&&c[d].push(s),t[s]=A.value,!p.fallthrough)break}}if(s)for(let r=0;r<c.length;++r){const s=c[r]
3611
+ ;if(!s)continue;const l=e.$_terms.patterns[r].matches,d=i.localize(i.path,u,l),p=l.$_validate(s,d,o);if(p.errors){const r=a.details(p.errors,{override:!1});r.matches=s;const c=e.$_createError("object.pattern.match",t,r,i,o);if(o.abortEarly)return{value:t,errors:c};n.push(c)}}}if(!r.size||!e.$_terms.keys&&!e.$_terms.patterns)return;if(o.stripUnknown&&void 0===e._flags.unknown||o.skipFunctions){const e=!!o.stripUnknown&&(!0===o.stripUnknown||!!o.stripUnknown.objects);for(const n of r)e?(delete t[n],r.delete(n)):"function"==typeof t[n]&&r.delete(n)}if(!s.default(e._flags.unknown,o.allowUnknown))for(const s of r){const r=i.localize([...i.path,s],[]),a=e.$_createError("object.unknown",t[s],{child:s},r,o,{flags:!1});if(o.abortEarly)return{value:t,errors:a};n.push(a)}},l.Dependency=class{constructor(e,t,r,n,i){this.rel=e,this.key=t,this.peers=r,this.paths=n,this.options=i}describe(){const e={rel:this.rel,peers:this.paths};return null!==this.key&&(e.key=this.key.key),
3612
+ "."!==this.peers[0].separator&&(e.options={...e.options,separator:this.peers[0].separator}),this.options.isPresent&&(e.options={...e.options,isPresent:this.options.isPresent}),e}},l.Keys=class extends Array{concat(e){const t=this.slice(),r=new Map;for(let e=0;e<t.length;++e)r.set(t[e].key,e);for(const n of e){const e=n.key,i=r.get(e);void 0!==i?t[i]={key:e,schema:t[i].schema.concat(n.schema)}:t.push(n)}return t}},keys}function require_function(){if(hasRequired_function)return _function;hasRequired_function=1;const{assert:e}=requireLib$4(),t=requireKeys();return _function=t.extend({type:"function",properties:{typeof:"function"},rules:{arity:{method(t){return e(Number.isSafeInteger(t)&&t>=0,"n must be a positive integer"),this.$_addRule({name:"arity",args:{n:t}})},validate:(e,t,{n:r})=>e.length===r?e:t.error("function.arity",{n:r})},class:{method(){return this.$_addRule("class")},validate:(e,t)=>/^\s*class\s/.test(e.toString())?e:t.error("function.class",{value:e})},minArity:{method(t){
3613
+ return e(Number.isSafeInteger(t)&&t>0,"n must be a strict positive integer"),this.$_addRule({name:"minArity",args:{n:t}})},validate:(e,t,{n:r})=>e.length>=r?e:t.error("function.minArity",{n:r})},maxArity:{method(t){return e(Number.isSafeInteger(t)&&t>=0,"n must be a positive integer"),this.$_addRule({name:"maxArity",args:{n:t}})},validate:(e,t,{n:r})=>e.length<=r?e:t.error("function.maxArity",{n:r})}},messages:{"function.arity":"{{#label}} must have an arity of {{#n}}","function.class":"{{#label}} must be a class","function.maxArity":"{{#label}} must have an arity lesser or equal to {{#n}}","function.minArity":"{{#label}} must have an arity greater or equal to {{#n}}"}}),_function}function requireLink(){if(hasRequiredLink)return link;hasRequiredLink=1;const{assert:e}=requireLib$4(),t=requireAny(),r=requireCommon(),n=requireCompile(),i=requireErrors$1(),s={};return link=t.extend({type:"link",properties:{schemaChain:!0},terms:{link:{init:null,manifest:"single",register:!1}},
3614
+ args:(e,t)=>e.ref(t),validate(t,{schema:r,state:n,prefs:i}){e(r.$_terms.link,"Uninitialized link schema");const o=s.generate(r,t,n,i),a=r.$_terms.link[0].ref;return o.$_validate(t,n.nest(o,`link:${a.display}:${o.type}`),i)},generate:(e,t,r,n)=>s.generate(e,t,r,n),rules:{ref:{method(t){e(!this.$_terms.link,"Cannot reinitialize schema"),t=n.ref(t),e("value"===t.type||"local"===t.type,"Invalid reference type:",t.type),e("local"===t.type||"root"===t.ancestor||t.ancestor>0,"Link cannot reference itself");const r=this.clone();return r.$_terms.link=[{ref:t}],r}},relative:{method(e=!0){return this.$_setFlag("relative",e)}}},overrides:{concat(t){e(this.$_terms.link,"Uninitialized link schema"),e(r.isSchema(t),"Invalid schema object"),e("link"!==t.type,"Cannot merge type link with another link");const n=this.clone();return n.$_terms.whens||(n.$_terms.whens=[]),n.$_terms.whens.push({concat:t}),n.$_mutateRebuild()}},manifest:{build:(t,r)=>(e(r.link,"Invalid link description missing link"),
3615
+ t.ref(r.link))}}),s.generate=function(e,t,r,n){let i=r.mainstay.links.get(e);if(i)return i._generate(t,r,n).schema;const o=e.$_terms.link[0].ref,{perspective:a,path:c}=s.perspective(o,r);s.assert(a,"which is outside of schema boundaries",o,e,r,n);try{i=c.length?a.$_reach(c):a}catch{s.assert(!1,"to non-existing schema",o,e,r,n)}return s.assert("link"!==i.type,"which is another link",o,e,r,n),e._flags.relative||r.mainstay.links.set(e,i),i._generate(t,r,n).schema},s.perspective=function(e,t){if("local"===e.type){for(const{schema:r,key:n}of t.schemas){if((r._flags.id||n)===e.path[0])return{perspective:r,path:e.path.slice(1)};if(r.$_terms.shared)for(const t of r.$_terms.shared)if(t._flags.id===e.path[0])return{perspective:t,path:e.path.slice(1)}}return{perspective:null,path:null}}return"root"===e.ancestor?{perspective:t.schemas[t.schemas.length-1].schema,path:e.path}:{perspective:t.schemas[e.ancestor]&&t.schemas[e.ancestor].schema,path:e.path}},s.assert=function(t,r,n,s,o,a){
3616
+ t||e(!1,`"${i.label(s._flags,o,a)}" contains link reference "${n.display}" ${r}`)},link}function requireNumber(){if(hasRequiredNumber)return number;hasRequiredNumber=1;const{assert:e}=requireLib$4(),t=requireAny(),r=requireCommon(),n={numberRx:/^\s*[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e([+-]?\d+))?\s*$/i,precisionRx:/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/,exponentialPartRegex:/[eE][+-]?\d+$/,leadingSignAndZerosRegex:/^[+-]?(0*)?/,dotRegex:/\./,trailingZerosRegex:/0+$/,decimalPlaces(e){const t=e.toString(),r=t.indexOf("."),n=t.indexOf("e");return(r<0?0:(n<0?t.length:n)-r-1)+(n<0?0:Math.max(0,-parseInt(t.slice(n+1))))}};return number=t.extend({type:"number",flags:{unsafe:{default:!1}},coerce:{from:"string",method(e,{schema:t,error:r}){if(!e.match(n.numberRx))return;e=e.trim();const i={value:parseFloat(e)};if(0===i.value&&(i.value=0),!t._flags.unsafe)if(e.match(/e/i)){if(n.extractSignificantDigits(e)!==n.extractSignificantDigits(String(i.value)))return i.errors=r("number.unsafe"),i}else{
3617
+ const t=i.value.toString();if(t.match(/e/i))return i;if(t!==n.normalizeDecimal(e))return i.errors=r("number.unsafe"),i}return i}},validate(e,{schema:t,error:n,prefs:i}){if(e===1/0||e===-1/0)return{value:e,errors:n("number.infinity")};if(!r.isNumber(e))return{value:e,errors:n("number.base")};const s={value:e};if(i.convert){const e=t.$_getRule("precision");if(e){const t=Math.pow(10,e.args.limit);s.value=Math.round(s.value*t)/t}}return 0===s.value&&(s.value=0),!t._flags.unsafe&&(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER)&&(s.errors=n("number.unsafe")),s},rules:{compare:{method:!1,validate:(e,t,{limit:n},{name:i,operator:s,args:o})=>r.compare(e,n,s)?e:t.error("number."+i,{limit:o.limit,value:e}),args:[{name:"limit",ref:!0,assert:r.isNumber,message:"must be a number"}]},greater:{method(e){return this.$_addRule({name:"greater",method:"compare",args:{limit:e},operator:">"})}},integer:{method(){return this.$_addRule("integer")},
3618
+ validate:(e,t)=>Math.trunc(e)-e===0?e:t.error("number.integer")},less:{method(e){return this.$_addRule({name:"less",method:"compare",args:{limit:e},operator:"<"})}},max:{method(e){return this.$_addRule({name:"max",method:"compare",args:{limit:e},operator:"<="})}},min:{method(e){return this.$_addRule({name:"min",method:"compare",args:{limit:e},operator:">="})}},multiple:{method(e){const t="number"==typeof e?n.decimalPlaces(e):null,r=Math.pow(10,t);return this.$_addRule({name:"multiple",args:{base:e,baseDecimalPlace:t,pfactor:r}})},validate:(e,t,{base:r,baseDecimalPlace:i,pfactor:s},o)=>n.decimalPlaces(e)>i?t.error("number.multiple",{multiple:o.args.base,value:e}):Math.round(s*e)%Math.round(s*r)===0?e:t.error("number.multiple",{multiple:o.args.base,value:e}),args:[{name:"base",ref:!0,assert:e=>"number"==typeof e&&isFinite(e)&&e>0,message:"must be a positive number"},"baseDecimalPlace","pfactor"],multi:!0},negative:{method(){return this.sign("negative")}},port:{method(){
3619
+ return this.$_addRule("port")},validate:(e,t)=>Number.isSafeInteger(e)&&e>=0&&e<=65535?e:t.error("number.port")},positive:{method(){return this.sign("positive")}},precision:{method(t){return e(Number.isSafeInteger(t),"limit must be an integer"),this.$_addRule({name:"precision",args:{limit:t}})},validate(e,t,{limit:r}){const i=e.toString().match(n.precisionRx);return Math.max((i[1]?i[1].length:0)-(i[2]?parseInt(i[2],10):0),0)<=r?e:t.error("number.precision",{limit:r,value:e})},convert:!0},sign:{method(t){return e(["negative","positive"].includes(t),"Invalid sign",t),this.$_addRule({name:"sign",args:{sign:t}})},validate:(e,t,{sign:r})=>"negative"===r&&e<0||"positive"===r&&e>0?e:t.error(`number.${r}`)},unsafe:{method(t=!0){return e("boolean"==typeof t,"enabled must be a boolean"),this.$_setFlag("unsafe",t)}}},cast:{string:{from:e=>"number"==typeof e,to:(e,t)=>e.toString()}},messages:{"number.base":"{{#label}} must be a number","number.greater":"{{#label}} must be greater than {{#limit}}",
3620
+ "number.infinity":"{{#label}} cannot be infinity","number.integer":"{{#label}} must be an integer","number.less":"{{#label}} must be less than {{#limit}}","number.max":"{{#label}} must be less than or equal to {{#limit}}","number.min":"{{#label}} must be greater than or equal to {{#limit}}","number.multiple":"{{#label}} must be a multiple of {{#multiple}}","number.negative":"{{#label}} must be a negative number","number.port":"{{#label}} must be a valid port","number.positive":"{{#label}} must be a positive number","number.precision":"{{#label}} must have no more than {{#limit}} decimal places","number.unsafe":"{{#label}} must be a safe number"}}),n.extractSignificantDigits=function(e){return e.replace(n.exponentialPartRegex,"").replace(n.dotRegex,"").replace(n.trailingZerosRegex,"").replace(n.leadingSignAndZerosRegex,"")},n.normalizeDecimal=function(e){
3621
+ return(e=e.replace(/^\+/,"").replace(/\.0*$/,"").replace(/^(-?)\.([^\.]*)$/,"$10.$2").replace(/^(-?)0+([0-9])/,"$1$2")).includes(".")&&e.endsWith("0")&&(e=e.replace(/0+$/,"")),"-0"===e?"0":e},number}function requireObject(){if(hasRequiredObject)return object;hasRequiredObject=1;const e=requireKeys();return object=e.extend({type:"object",cast:{map:{from:e=>e&&"object"==typeof e,to:(e,t)=>new Map(Object.entries(e))}}})}const errorCodes={EMPTY_STRING:"Address must be a non-empty string",FORBIDDEN_UNICODE:"Address contains forbidden Unicode characters",MULTIPLE_AT_CHAR:"Address cannot contain more than one @ character",MISSING_AT_CHAR:"Address must contain one @ character",EMPTY_LOCAL:"Address local part cannot be empty",ADDRESS_TOO_LONG:"Address too long",LOCAL_TOO_LONG:"Address local part too long",EMPTY_LOCAL_SEGMENT:"Address local part contains empty dot-separated segment",INVALID_LOCAL_CHARS:"Address local part contains invalid character",
3622
+ DOMAIN_NON_EMPTY_STRING:"Domain must be a non-empty string",DOMAIN_TOO_LONG:"Domain too long",DOMAIN_INVALID_UNICODE_CHARS:"Domain contains forbidden Unicode characters",DOMAIN_INVALID_CHARS:"Domain contains invalid character",DOMAIN_INVALID_TLDS_CHARS:"Domain contains invalid tld character",DOMAIN_SEGMENTS_COUNT:"Domain lacks the minimum required number of segments",DOMAIN_SEGMENTS_COUNT_MAX:"Domain contains too many segments",DOMAIN_FORBIDDEN_TLDS:"Domain uses forbidden TLD",DOMAIN_EMPTY_SEGMENT:"Domain contains empty dot-separated segment",DOMAIN_LONG_SEGMENT:"Domain contains dot-separated segment that is too long"};function errorCode$1(e){return{code:e,error:errorCodes[e]}}
3623
+ const MIN_DOMAIN_SEGMENTS=2,NON_ASCII_RX$1=/[^\x00-\x7f]/,DOMAIN_CONTROL_RX=/[\x00-\x20@\:\/\\#!\$&\'\(\)\*\+,;=\?]/,TLD_SEGMENT_RX=/^[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,DOMAIN_SEGMENT_RX=/^[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,DOMAIN_UNDERSCORE_SEGMENT_RX=/^[a-zA-Z0-9_](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,URL_IMPL=Url$1.URL||URL;function isTldsAllow(e){return!!e.allow}function analyzeDomain(e,t={}){if(!e)return errorCode$1("DOMAIN_NON_EMPTY_STRING");if("string"!=typeof e)throw new Error("Invalid input: domain must be a string");if(e.length>256)return errorCode$1("DOMAIN_TOO_LONG");if(!!NON_ASCII_RX$1.test(e)){if(!1===t.allowUnicode)return errorCode$1("DOMAIN_INVALID_UNICODE_CHARS");e=e.normalize("NFC")}if(DOMAIN_CONTROL_RX.test(e))return errorCode$1("DOMAIN_INVALID_CHARS");e=punycode(e),t.allowFullyQualified&&"."===e[e.length-1]&&(e=e.slice(0,-1));const r=t.minDomainSegments||MIN_DOMAIN_SEGMENTS,n=e.split(".");if(n.length<r)return errorCode$1("DOMAIN_SEGMENTS_COUNT")
3624
+ ;if(t.maxDomainSegments&&n.length>t.maxDomainSegments)return errorCode$1("DOMAIN_SEGMENTS_COUNT_MAX");const i=t.tlds;if(i){const e=n[n.length-1].toLowerCase();if(isTldsAllow(i)){if(!i.allow.has(e))return errorCode$1("DOMAIN_FORBIDDEN_TLDS")}else if(i.deny.has(e))return errorCode$1("DOMAIN_FORBIDDEN_TLDS")}for(let e=0;e<n.length;++e){const r=n[e];if(!r.length)return errorCode$1("DOMAIN_EMPTY_SEGMENT");if(r.length>63)return errorCode$1("DOMAIN_LONG_SEGMENT");if(e<n.length-1){if(t.allowUnderscore){if(!DOMAIN_UNDERSCORE_SEGMENT_RX.test(r))return errorCode$1("DOMAIN_INVALID_CHARS")}else if(!DOMAIN_SEGMENT_RX.test(r))return errorCode$1("DOMAIN_INVALID_CHARS")}else if(!TLD_SEGMENT_RX.test(r))return errorCode$1("DOMAIN_INVALID_TLDS_CHARS")}return null}function isDomainValid(e,t){return!analyzeDomain(e,t)}function punycode(e){e.includes("%")&&(e=e.replace(/%/g,"%25"));try{return new URL_IMPL(`http://${e}`).host}catch(t){return e}}function validateDomainOptions(e){if(e){
3625
+ if("object"!=typeof e.tlds)throw new Error("Invalid options: tlds must be a boolean or an object");if(isTldsAllow(e.tlds)){if(e.tlds.allow instanceof Set==!1)throw new Error("Invalid options: tlds.allow must be a Set object or true");if(e.tlds.deny)throw new Error("Invalid options: cannot specify both tlds.allow and tlds.deny lists")}else if(e.tlds.deny instanceof Set==!1)throw new Error("Invalid options: tlds.deny must be a Set object")}}const NON_ASCII_RX=/[^\x00-\x7f]/,ENCODER_IMPL=new(require$$0$b.TextEncoder||TextEncoder);function analyzeEmail(e,t){return validateEmail(e,t)}function isEmailValid(e,t){return!validateEmail(e,t)}function validateEmail(e,t={}){if("string"!=typeof e)throw new Error("Invalid input: email must be a string");if(!e)return errorCode$1("EMPTY_STRING");const r=!NON_ASCII_RX.test(e);if(!r){if(!1===t.allowUnicode)return errorCode$1("FORBIDDEN_UNICODE");e=e.normalize("NFC")}const n=e.split("@")
3626
+ ;if(2!==n.length)return n.length>2?errorCode$1("MULTIPLE_AT_CHAR"):errorCode$1("MISSING_AT_CHAR");const[i,s]=n;if(!i)return errorCode$1("EMPTY_LOCAL");if(!t.ignoreLength){if(e.length>254)return errorCode$1("ADDRESS_TOO_LONG");if(ENCODER_IMPL.encode(i).length>64)return errorCode$1("LOCAL_TOO_LONG")}return validateLocal(i,r)||analyzeDomain(s,t)}function validateLocal(e,t){const r=e.split(".");for(const e of r){if(!e.length)return errorCode$1("EMPTY_LOCAL_SEGMENT");if(t){if(!ATEXT_RX.test(e))return errorCode$1("INVALID_LOCAL_CHARS")}else for(const t of e){if(ATEXT_RX.test(t))continue;const e=toBinary(t);if(!ATOM_RX.test(e))return errorCode$1("INVALID_LOCAL_CHARS")}}return null}function toBinary(e){return Array.from(ENCODER_IMPL.encode(e),e=>String.fromCharCode(e)).join("")}
3627
+ const ATEXT_RX=/^[\w!#\$%&'\*\+\-/=\?\^`\{\|\}~]+$/,ATOM_RX=new RegExp(["(?:[\\xc2-\\xdf][\\x80-\\xbf])","(?:\\xe0[\\xa0-\\xbf][\\x80-\\xbf])|(?:[\\xe1-\\xec][\\x80-\\xbf]{2})|(?:\\xed[\\x80-\\x9f][\\x80-\\xbf])|(?:[\\xee-\\xef][\\x80-\\xbf]{2})","(?:\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2})|(?:[\\xf1-\\xf3][\\x80-\\xbf]{3})|(?:\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})"].join("|"));requireApplyToDefaults();var assertExports=requireAssert(),assert$1=getDefaultExportFromCjs(assertExports);requireBench(),requireBlock(),requireClone(),requireContain(),requireDeepEqual(),requireAssertError(),requireEscapeHeaderAttribute(),requireEscapeHtml(),requireEscapeJson();var escapeRegexExports=requireEscapeRegex(),escapeRegex=getDefaultExportFromCjs(escapeRegexExports);function generate$1(){const e={},t="\\dA-Fa-f",r="["+t+"]",n="\\w-\\.~",i="!\\$&'\\(\\)\\*\\+,;=",s="%"+t,o=n+s+i+":@",a="["+o+"]",c="(?:0{0,2}\\d|0?[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])";e.ipv4address="(?:"+c+"\\.){3}"+c
3628
+ ;const u=r+"{1,4}",l="(?:"+u+":"+u+"|"+e.ipv4address+")",d="(?:"+u+":){6}"+l,p="::(?:"+u+":){5}"+l,h="(?:"+u+")?::(?:"+u+":){4}"+l,A="(?:(?:"+u+":){0,1}"+u+")?::(?:"+u+":){3}"+l,f="(?:(?:"+u+":){0,2}"+u+")?::(?:"+u+":){2}"+l,g="(?:(?:"+u+":){0,3}"+u+")?::"+u+":"+l,m="(?:(?:"+u+":){0,4}"+u+")?::"+l,y="(?:(?:"+u+":){0,5}"+u+")?::"+u,E="(?:(?:"+u+":){0,6}"+u+")?::";e.ipv4Cidr="(?:\\d|[1-2]\\d|3[0-2])",e.ipv6Cidr="(?:0{0,2}\\d|0?[1-9]\\d|1[01]\\d|12[0-8])",e.ipv6address="(?:"+d+"|"+p+"|"+h+"|"+A+"|"+f+"|"+g+"|"+m+"|"+y+"|"+E+")",e.ipvFuture="v"+r+"+\\.["+n+i+":]+",e.scheme="[a-zA-Z][a-zA-Z\\d+-\\.]*",e.schemeRegex=new RegExp(e.scheme);const b="["+n+s+i+":]*",C="["+n+s+i+"]{1,255}",I="(?:"+("\\[(?:"+e.ipv6address+"|"+e.ipvFuture+")\\]")+"|"+e.ipv4address+"|"+C+")",v="(?:"+b+"@)?"+I+"(?::\\d*)?",w="(?:"+b+"@)?("+I+")(?::\\d*)?",S=a+"*",_=a+"+",D="(?:\\/"+S+")*",B="\\/(?:"+_+D+")?",R=_+D,T="["+n+s+i+"@]+"+D,x="(?:\\/\\/\\/"+S+D+")";return e.hierPart="(?:(?:\\/\\/"+v+D+")|"+B+"|"+R+"|"+x+")",
3629
+ e.hierPartCapture="(?:(?:\\/\\/"+w+D+")|"+B+"|"+R+")",e.relativeRef="(?:(?:\\/\\/"+v+D+")|"+B+"|"+T+"|)",e.relativeRefCapture="(?:(?:\\/\\/"+w+D+")|"+B+"|"+T+"|)",e.query="["+o+"\\/\\?]*(?=#|$)",e.queryWithSquareBrackets="["+o+"\\[\\]\\/\\?]*(?=#|$)",e.fragment="["+o+"\\/\\?]*",e}requireFlatten(),requireIgnore(),requireIntersect(),requireIsPromise$1(),requireMerge$2(),requireOnce(),requireReach(),requireReachTemplate(),requireStringify$1(),requireWait();const rfc3986=generate$1(),ipVersions={v4Cidr:rfc3986.ipv4Cidr,v6Cidr:rfc3986.ipv6Cidr,ipv4:rfc3986.ipv4address,ipv6:rfc3986.ipv6address,ipvfuture:rfc3986.ipvFuture};function createRegex(e){const t=rfc3986,r="(?:\\?"+(e.allowQuerySquareBrackets?t.queryWithSquareBrackets:t.query)+")?(?:#"+t.fragment+")?",n=e.domain?t.relativeRefCapture:t.relativeRef;if(e.relativeOnly)return wrap(n+r);let i="";if(e.scheme){assert$1(e.scheme instanceof RegExp||"string"==typeof e.scheme||Array.isArray(e.scheme),"scheme must be a RegExp, String, or Array")
3630
+ ;const r=[].concat(e.scheme);assert$1(r.length>=1,"scheme must have at least 1 scheme specified");const n=[];for(let e=0;e<r.length;++e){const i=r[e];assert$1(i instanceof RegExp||"string"==typeof i,"scheme at position "+e+" must be a RegExp or String"),i instanceof RegExp?n.push(i.source.toString()):(assert$1(t.schemeRegex.test(i),"scheme at position "+e+" must be a valid scheme"),n.push(escapeRegex(i)))}i=n.join("|")}const s="(?:"+(i?"(?:"+i+")":t.scheme)+":"+(e.domain?t.hierPartCapture:t.hierPart)+")";return wrap((e.allowRelative?"(?:"+s+"|"+n+")":s)+r,i)}function wrap(e,t=null){return{raw:e=`(?=.)(?!https?:/(?:$|[^/]))(?!https?:///)(?!https?:[^/])${e}`,regex:new RegExp(`^${e}$`),scheme:t}}const genericUriRegex=createRegex({});function uriRegex(e={}){return e.scheme||e.allowRelative||e.relativeOnly||e.allowQuerySquareBrackets||e.domain?createRegex(e):genericUriRegex}function ipRegex(e={}){const t=e.cidr||"optional"
3631
+ ;assert$1(["required","optional","forbidden"].includes(t),"options.cidr must be one of required, optional, forbidden"),assert$1(void 0===e.version||"string"==typeof e.version||Array.isArray(e.version),"options.version must be a string or an array of string");let r=e.version||["ipv4","ipv6","ipvfuture"];Array.isArray(r)||(r=[r]),assert$1(r.length>=1,"options.version must have at least 1 version specified");for(const e of r)assert$1("string"==typeof e&&e===e.toLowerCase(),"Invalid options.version value"),assert$1(["ipv4","ipv6","ipvfuture"].includes(e),"options.version contains unknown version "+e+" - must be one of ipv4, ipv6, ipvfuture");r=Array.from(new Set(r));const n=r.map(e=>{if("forbidden"===t)return ipVersions[e];const r=`\\/${"ipv4"===e?ipVersions.v4Cidr:ipVersions.v6Cidr}`;return"required"===t?`${ipVersions[e]}${r}`:`${ipVersions[e]}(?:${r})?`}),i=`(?:${n.join("|")})`,s=new RegExp(`^${i}$`);return{cidr:t,versions:r,regex:s,raw:i}}const HEX={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,
3632
+ 9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15},UTF8={accept:12,reject:0,data:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7]};function uriDecode(e){let t=e.indexOf("%");if(-1===t)return e;let r="",n=0,i=0,s=t,o=UTF8.accept
3633
+ ;for(;t>-1&&t<e.length;){const a=resolveHex(e[t+1],4)|resolveHex(e[t+2],0),c=UTF8.data[a];if(o=UTF8.data[256+o+c],i=i<<6|a&UTF8.data[364+c],o!==UTF8.accept){if(o===UTF8.reject)return null;if(t+=3,t>=e.length||"%"!==e[t])return null}else r+=e.slice(n,s),r+=i<=65535?String.fromCharCode(i):String.fromCharCode(55232+(i>>10),56320+(1023&i)),i=0,n=t+3,t=e.indexOf("%",n),s=t}return r+e.slice(n)}function resolveHex(e,t){const r=HEX[e];return void 0===r?255:r<<t}var esm=Object.freeze({__proto__:null,analyzeDomain,analyzeEmail,errorCodes,ipRegex,isDomainValid,isEmailValid,uriDecode,uriRegex,validateDomainOptions}),require$$1=getAugmentedNamespace(esm),commonjs={},tlds={},hasRequiredTlds,hasRequiredCommonjs,string,hasRequiredString,symbol,hasRequiredSymbol,binary$1,hasRequiredBinary,lib,hasRequiredLib,delayed_stream,hasRequiredDelayed_stream,combined_stream,hasRequiredCombined_stream;function requireTlds(){return hasRequiredTlds||(hasRequiredTlds=1,Object.defineProperty(tlds,"__esModule",{
3634
+ value:!0
3635
+ }),tlds.TLDS=void 0,tlds.TLDS=["AAA","AARP","ABB","ABBOTT","ABBVIE","ABC","ABLE","ABOGADO","ABUDHABI","AC","ACADEMY","ACCENTURE","ACCOUNTANT","ACCOUNTANTS","ACO","ACTOR","AD","ADS","ADULT","AE","AEG","AERO","AETNA","AF","AFL","AFRICA","AG","AGAKHAN","AGENCY","AI","AIG","AIRBUS","AIRFORCE","AIRTEL","AKDN","AL","ALIBABA","ALIPAY","ALLFINANZ","ALLSTATE","ALLY","ALSACE","ALSTOM","AM","AMAZON","AMERICANEXPRESS","AMERICANFAMILY","AMEX","AMFAM","AMICA","AMSTERDAM","ANALYTICS","ANDROID","ANQUAN","ANZ","AO","AOL","APARTMENTS","APP","APPLE","AQ","AQUARELLE","AR","ARAB","ARAMCO","ARCHI","ARMY","ARPA","ART","ARTE","AS","ASDA","ASIA","ASSOCIATES","AT","ATHLETA","ATTORNEY","AU","AUCTION","AUDI","AUDIBLE","AUDIO","AUSPOST","AUTHOR","AUTO","AUTOS","AW","AWS","AX","AXA","AZ","AZURE","BA","BABY","BAIDU","BANAMEX","BAND","BANK","BAR","BARCELONA","BARCLAYCARD","BARCLAYS","BAREFOOT","BARGAINS","BASEBALL","BASKETBALL","BAUHAUS","BAYERN","BB","BBC","BBT","BBVA","BCG","BCN","BD","BE","BEATS","BEAUTY","BEER","BERLIN","BEST","BESTBUY","BET","BF","BG","BH","BHARTI","BI","BIBLE","BID","BIKE","BING","BINGO","BIO","BIZ","BJ","BLACK","BLACKFRIDAY","BLOCKBUSTER","BLOG","BLOOMBERG","BLUE","BM","BMS","BMW","BN","BNPPARIBAS","BO","BOATS","BOEHRINGER","BOFA","BOM","BOND","BOO","BOOK","BOOKING","BOSCH","BOSTIK","BOSTON","BOT","BOUTIQUE","BOX","BR","BRADESCO","BRIDGESTONE","BROADWAY","BROKER","BROTHER","BRUSSELS","BS","BT","BUILD","BUILDERS","BUSINESS","BUY","BUZZ","BV","BW","BY","BZ","BZH","CA","CAB","CAFE","CAL","CALL","CALVINKLEIN","CAM","CAMERA","CAMP","CANON","CAPETOWN","CAPITAL","CAPITALONE","CAR","CARAVAN","CARDS","CARE","CAREER","CAREERS","CARS","CASA","CASE","CASH","CASINO","CAT","CATERING","CATHOLIC","CBA","CBN","CBRE","CC","CD","CENTER","CEO","CERN","CF","CFA","CFD","CG","CH","CHANEL","CHANNEL","CHARITY","CHASE","CHAT","CHEAP","CHINTAI","CHRISTMAS","CHROME","CHURCH","CI","CIPRIANI","CIRCLE","CISCO","CITADEL","CITI","CITIC","CITY","CK","CL","CLAIMS","CLEANING","CLICK","CLINIC","CLINIQUE","CLOTHING","CLOUD","CLUB","CLUBMED","CM","CN","CO","COACH","CODES","COFFEE","COLLEGE","COLOGNE","COM","COMMBANK","COMMUNITY","COMPANY","COMPARE","COMPUTER","COMSEC","CONDOS","CONSTRUCTION","CONSULTING","CONTACT","CONTRACTORS","COOKING","COOL","COOP","CORSICA","COUNTRY","COUPON","COUPONS","COURSES","CPA","CR","CREDIT","CREDITCARD","CREDITUNION","CRICKET","CROWN","CRS","CRUISE","CRUISES","CU","CUISINELLA","CV","CW","CX","CY","CYMRU","CYOU","CZ","DAD","DANCE","DATA","DATE","DATING","DATSUN","DAY","DCLK","DDS","DE","DEAL","DEALER","DEALS","DEGREE","DELIVERY","DELL","DELOITTE","DELTA","DEMOCRAT","DENTAL","DENTIST","DESI","DESIGN","DEV","DHL","DIAMONDS","DIET","DIGITAL","DIRECT","DIRECTORY","DISCOUNT","DISCOVER","DISH","DIY","DJ","DK","DM","DNP","DO","DOCS","DOCTOR","DOG","DOMAINS","DOT","DOWNLOAD","DRIVE","DTV","DUBAI","DUNLOP","DUPONT","DURBAN","DVAG","DVR","DZ","EARTH","EAT","EC","ECO","EDEKA","EDU","EDUCATION","EE","EG","EMAIL","EMERCK","ENERGY","ENGINEER","ENGINEERING","ENTERPRISES","EPSON","EQUIPMENT","ER","ERICSSON","ERNI","ES","ESQ","ESTATE","ET","EU","EUROVISION","EUS","EVENTS","EXCHANGE","EXPERT","EXPOSED","EXPRESS","EXTRASPACE","FAGE","FAIL","FAIRWINDS","FAITH","FAMILY","FAN","FANS","FARM","FARMERS","FASHION","FAST","FEDEX","FEEDBACK","FERRARI","FERRERO","FI","FIDELITY","FIDO","FILM","FINAL","FINANCE","FINANCIAL","FIRE","FIRESTONE","FIRMDALE","FISH","FISHING","FIT","FITNESS","FJ","FK","FLICKR","FLIGHTS","FLIR","FLORIST","FLOWERS","FLY","FM","FO","FOO","FOOD","FOOTBALL","FORD","FOREX","FORSALE","FORUM","FOUNDATION","FOX","FR","FREE","FRESENIUS","FRL","FROGANS","FRONTIER","FTR","FUJITSU","FUN","FUND","FURNITURE","FUTBOL","FYI","GA","GAL","GALLERY","GALLO","GALLUP","GAME","GAMES","GAP","GARDEN","GAY","GB","GBIZ","GD","GDN","GE","GEA","GENT","GENTING","GEORGE","GF","GG","GGEE","GH","GI","GIFT","GIFTS","GIVES","GIVING","GL","GLASS","GLE","GLOBAL","GLOBO","GM","GMAIL","GMBH","GMO","GMX","GN","GODADDY","GOLD","GOLDPOINT","GOLF","GOO","GOODYEAR","GOOG","GOOGLE","GOP","GOT","GOV","GP","GQ","GR","GRAINGER","GRAPHICS","GRATIS","GREEN","GRIPE","GROCERY","GROUP","GS","GT","GU","GUCCI","GUGE","GUIDE","GUITARS","GURU","GW","GY","HAIR","HAMBURG","HANGOUT","HAUS","HBO","HDFC","HDFCBANK","HEALTH","HEALTHCARE","HELP","HELSINKI","HERE","HERMES","HIPHOP","HISAMITSU","HITACHI","HIV","HK","HKT","HM","HN","HOCKEY","HOLDINGS","HOLIDAY","HOMEDEPOT","HOMEGOODS","HOMES","HOMESENSE","HONDA","HORSE","HOSPITAL","HOST","HOSTING","HOT","HOTELS","HOTMAIL","HOUSE","HOW","HR","HSBC","HT","HU","HUGHES","HYATT","HYUNDAI","IBM","ICBC","ICE","ICU","ID","IE","IEEE","IFM","IKANO","IL","IM","IMAMAT","IMDB","IMMO","IMMOBILIEN","IN","INC","INDUSTRIES","INFINITI","INFO","ING","INK","INSTITUTE","INSURANCE","INSURE","INT","INTERNATIONAL","INTUIT","INVESTMENTS","IO","IPIRANGA","IQ","IR","IRISH","IS","ISMAILI","IST","ISTANBUL","IT","ITAU","ITV","JAGUAR","JAVA","JCB","JE","JEEP","JETZT","JEWELRY","JIO","JLL","JM","JMP","JNJ","JO","JOBS","JOBURG","JOT","JOY","JP","JPMORGAN","JPRS","JUEGOS","JUNIPER","KAUFEN","KDDI","KE","KERRYHOTELS","KERRYPROPERTIES","KFH","KG","KH","KI","KIA","KIDS","KIM","KINDLE","KITCHEN","KIWI","KM","KN","KOELN","KOMATSU","KOSHER","KP","KPMG","KPN","KR","KRD","KRED","KUOKGROUP","KW","KY","KYOTO","KZ","LA","LACAIXA","LAMBORGHINI","LAMER","LAND","LANDROVER","LANXESS","LASALLE","LAT","LATINO","LATROBE","LAW","LAWYER","LB","LC","LDS","LEASE","LECLERC","LEFRAK","LEGAL","LEGO","LEXUS","LGBT","LI","LIDL","LIFE","LIFEINSURANCE","LIFESTYLE","LIGHTING","LIKE","LILLY","LIMITED","LIMO","LINCOLN","LINK","LIVE","LIVING","LK","LLC","LLP","LOAN","LOANS","LOCKER","LOCUS","LOL","LONDON","LOTTE","LOTTO","LOVE","LPL","LPLFINANCIAL","LR","LS","LT","LTD","LTDA","LU","LUNDBECK","LUXE","LUXURY","LV","LY","MA","MADRID","MAIF","MAISON","MAKEUP","MAN","MANAGEMENT","MANGO","MAP","MARKET","MARKETING","MARKETS","MARRIOTT","MARSHALLS","MATTEL","MBA","MC","MCKINSEY","MD","ME","MED","MEDIA","MEET","MELBOURNE","MEME","MEMORIAL","MEN","MENU","MERCKMSD","MG","MH","MIAMI","MICROSOFT","MIL","MINI","MINT","MIT","MITSUBISHI","MK","ML","MLB","MLS","MM","MMA","MN","MO","MOBI","MOBILE","MODA","MOE","MOI","MOM","MONASH","MONEY","MONSTER","MORMON","MORTGAGE","MOSCOW","MOTO","MOTORCYCLES","MOV","MOVIE","MP","MQ","MR","MS","MSD","MT","MTN","MTR","MU","MUSEUM","MUSIC","MV","MW","MX","MY","MZ","NA","NAB","NAGOYA","NAME","NAVY","NBA","NC","NE","NEC","NET","NETBANK","NETFLIX","NETWORK","NEUSTAR","NEW","NEWS","NEXT","NEXTDIRECT","NEXUS","NF","NFL","NG","NGO","NHK","NI","NICO","NIKE","NIKON","NINJA","NISSAN","NISSAY","NL","NO","NOKIA","NORTON","NOW","NOWRUZ","NOWTV","NP","NR","NRA","NRW","NTT","NU","NYC","NZ","OBI","OBSERVER","OFFICE","OKINAWA","OLAYAN","OLAYANGROUP","OLLO","OM","OMEGA","ONE","ONG","ONL","ONLINE","OOO","OPEN","ORACLE","ORANGE","ORG","ORGANIC","ORIGINS","OSAKA","OTSUKA","OTT","OVH","PA","PAGE","PANASONIC","PARIS","PARS","PARTNERS","PARTS","PARTY","PAY","PCCW","PE","PET","PF","PFIZER","PG","PH","PHARMACY","PHD","PHILIPS","PHONE","PHOTO","PHOTOGRAPHY","PHOTOS","PHYSIO","PICS","PICTET","PICTURES","PID","PIN","PING","PINK","PIONEER","PIZZA","PK","PL","PLACE","PLAY","PLAYSTATION","PLUMBING","PLUS","PM","PN","PNC","POHL","POKER","POLITIE","PORN","POST","PR","PRAXI","PRESS","PRIME","PRO","PROD","PRODUCTIONS","PROF","PROGRESSIVE","PROMO","PROPERTIES","PROPERTY","PROTECTION","PRU","PRUDENTIAL","PS","PT","PUB","PW","PWC","PY","QA","QPON","QUEBEC","QUEST","RACING","RADIO","RE","READ","REALESTATE","REALTOR","REALTY","RECIPES","RED","REDUMBRELLA","REHAB","REISE","REISEN","REIT","RELIANCE","REN","RENT","RENTALS","REPAIR","REPORT","REPUBLICAN","REST","RESTAURANT","REVIEW","REVIEWS","REXROTH","RICH","RICHARDLI","RICOH","RIL","RIO","RIP","RO","ROCKS","RODEO","ROGERS","ROOM","RS","RSVP","RU","RUGBY","RUHR","RUN","RW","RWE","RYUKYU","SA","SAARLAND","SAFE","SAFETY","SAKURA","SALE","SALON","SAMSCLUB","SAMSUNG","SANDVIK","SANDVIKCOROMANT","SANOFI","SAP","SARL","SAS","SAVE","SAXO","SB","SBI","SBS","SC","SCB","SCHAEFFLER","SCHMIDT","SCHOLARSHIPS","SCHOOL","SCHULE","SCHWARZ","SCIENCE","SCOT","SD","SE","SEARCH","SEAT","SECURE","SECURITY","SEEK","SELECT","SENER","SERVICES","SEVEN","SEW","SEX","SEXY","SFR","SG","SH","SHANGRILA","SHARP","SHELL","SHIA","SHIKSHA","SHOES","SHOP","SHOPPING","SHOUJI","SHOW","SI","SILK","SINA","SINGLES","SITE","SJ","SK","SKI","SKIN","SKY","SKYPE","SL","SLING","SM","SMART","SMILE","SN","SNCF","SO","SOCCER","SOCIAL","SOFTBANK","SOFTWARE","SOHU","SOLAR","SOLUTIONS","SONG","SONY","SOY","SPA","SPACE","SPORT","SPOT","SR","SRL","SS","ST","STADA","STAPLES","STAR","STATEBANK","STATEFARM","STC","STCGROUP","STOCKHOLM","STORAGE","STORE","STREAM","STUDIO","STUDY","STYLE","SU","SUCKS","SUPPLIES","SUPPLY","SUPPORT","SURF","SURGERY","SUZUKI","SV","SWATCH","SWISS","SX","SY","SYDNEY","SYSTEMS","SZ","TAB","TAIPEI","TALK","TAOBAO","TARGET","TATAMOTORS","TATAR","TATTOO","TAX","TAXI","TC","TCI","TD","TDK","TEAM","TECH","TECHNOLOGY","TEL","TEMASEK","TENNIS","TEVA","TF","TG","TH","THD","THEATER","THEATRE","TIAA","TICKETS","TIENDA","TIPS","TIRES","TIROL","TJ","TJMAXX","TJX","TK","TKMAXX","TL","TM","TMALL","TN","TO","TODAY","TOKYO","TOOLS","TOP","TORAY","TOSHIBA","TOTAL","TOURS","TOWN","TOYOTA","TOYS","TR","TRADE","TRADING","TRAINING","TRAVEL","TRAVELERS","TRAVELERSINSURANCE","TRUST","TRV","TT","TUBE","TUI","TUNES","TUSHU","TV","TVS","TW","TZ","UA","UBANK","UBS","UG","UK","UNICOM","UNIVERSITY","UNO","UOL","UPS","US","UY","UZ","VA","VACATIONS","VANA","VANGUARD","VC","VE","VEGAS","VENTURES","VERISIGN","VERSICHERUNG","VET","VG","VI","VIAJES","VIDEO","VIG","VIKING","VILLAS","VIN","VIP","VIRGIN","VISA","VISION","VIVA","VIVO","VLAANDEREN","VN","VODKA","VOLVO","VOTE","VOTING","VOTO","VOYAGE","VU","WALES","WALMART","WALTER","WANG","WANGGOU","WATCH","WATCHES","WEATHER","WEATHERCHANNEL","WEBCAM","WEBER","WEBSITE","WED","WEDDING","WEIBO","WEIR","WF","WHOSWHO","WIEN","WIKI","WILLIAMHILL","WIN","WINDOWS","WINE","WINNERS","WME","WOLTERSKLUWER","WOODSIDE","WORK","WORKS","WORLD","WOW","WS","WTC","WTF","XBOX","XEROX","XIHUAN","XIN","XN--11B4C3D","XN--1CK2E1B","XN--1QQW23A","XN--2SCRJ9C","XN--30RR7Y","XN--3BST00M","XN--3DS443G","XN--3E0B707E","XN--3HCRJ9C","XN--3PXU8K","XN--42C2D9A","XN--45BR5CYL","XN--45BRJ9C","XN--45Q11C","XN--4DBRK0CE","XN--4GBRIM","XN--54B7FTA0CC","XN--55QW42G","XN--55QX5D","XN--5SU34J936BGSG","XN--5TZM5G","XN--6FRZ82G","XN--6QQ986B3XL","XN--80ADXHKS","XN--80AO21A","XN--80AQECDR1A","XN--80ASEHDB","XN--80ASWG","XN--8Y0A063A","XN--90A3AC","XN--90AE","XN--90AIS","XN--9DBQ2A","XN--9ET52U","XN--9KRT00A","XN--B4W605FERD","XN--BCK1B9A5DRE4C","XN--C1AVG","XN--C2BR7G","XN--CCK2B3B","XN--CCKWCXETD","XN--CG4BKI","XN--CLCHC0EA0B2G2A9GCD","XN--CZR694B","XN--CZRS0T","XN--CZRU2D","XN--D1ACJ3B","XN--D1ALF","XN--E1A4C","XN--ECKVDTC9D","XN--EFVY88H","XN--FCT429K","XN--FHBEI","XN--FIQ228C5HS","XN--FIQ64B","XN--FIQS8S","XN--FIQZ9S","XN--FJQ720A","XN--FLW351E","XN--FPCRJ9C3D","XN--FZC2C9E2C","XN--FZYS8D69UVGM","XN--G2XX48C","XN--GCKR3F0F","XN--GECRJ9C","XN--GK3AT1E","XN--H2BREG3EVE","XN--H2BRJ9C","XN--H2BRJ9C8C","XN--HXT814E","XN--I1B6B1A6A2E","XN--IMR513N","XN--IO0A7I","XN--J1AEF","XN--J1AMH","XN--J6W193G","XN--JLQ480N2RG","XN--JVR189M","XN--KCRX77D1X4A","XN--KPRW13D","XN--KPRY57D","XN--KPUT3I","XN--L1ACC","XN--LGBBAT1AD8J","XN--MGB9AWBF","XN--MGBA3A3EJT","XN--MGBA3A4F16A","XN--MGBA7C0BBN0A","XN--MGBAAM7A8H","XN--MGBAB2BD","XN--MGBAH1A3HJKRD","XN--MGBAI9AZGQP6J","XN--MGBAYH7GPA","XN--MGBBH1A","XN--MGBBH1A71E","XN--MGBC0A9AZCG","XN--MGBCA7DZDO","XN--MGBCPQ6GPA1A","XN--MGBERP4A5D4AR","XN--MGBGU82A","XN--MGBI4ECEXP","XN--MGBPL2FH","XN--MGBT3DHD","XN--MGBTX2B","XN--MGBX4CD0AB","XN--MIX891F","XN--MK1BU44C","XN--MXTQ1M","XN--NGBC5AZD","XN--NGBE9E0A","XN--NGBRX","XN--NODE","XN--NQV7F","XN--NQV7FS00EMA","XN--NYQY26A","XN--O3CW4H","XN--OGBPF8FL","XN--OTU796D","XN--P1ACF","XN--P1AI","XN--PGBS0DH","XN--PSSY2U","XN--Q7CE6A","XN--Q9JYB4C","XN--QCKA1PMC","XN--QXA6A","XN--QXAM","XN--RHQV96G","XN--ROVU88B","XN--RVC1E0AM3E","XN--S9BRJ9C","XN--SES554G","XN--T60B56A","XN--TCKWE","XN--TIQ49XQYJ","XN--UNUP4Y","XN--VERMGENSBERATER-CTB","XN--VERMGENSBERATUNG-PWB","XN--VHQUV","XN--VUQ861B","XN--W4R85EL8FHU5DNRA","XN--W4RS40L","XN--WGBH1C","XN--WGBL6A","XN--XHQ521B","XN--XKC2AL3HYE2A","XN--XKC2DL3A5EE0H","XN--Y9A3AQ","XN--YFRO4I67O","XN--YGBI2AMMX","XN--ZFR164B","XXX","XYZ","YACHTS","YAHOO","YAMAXUN","YANDEX","YE","YODOBASHI","YOGA","YOKOHAMA","YOU","YOUTUBE","YT","YUN","ZA","ZAPPOS","ZARA","ZERO","ZIP","ZM","ZONE","ZUERICH","ZW"]),
3636
3636
  tlds}function requireCommonjs(){if(hasRequiredCommonjs)return commonjs;hasRequiredCommonjs=1,Object.defineProperty(commonjs,"__esModule",{value:!0}),commonjs.tlds=void 0;const e=requireTlds();return commonjs.tlds=new Set(e.TLDS.map(e=>e.toLowerCase())),commonjs}function requireString(){if(hasRequiredString)return string;hasRequiredString=1;const{assert:e,escapeRegex:t}=requireLib$4(),{isDomainValid:r,isEmailValid:n,ipRegex:i,uriRegex:s}=require$$1,o=requireCommonjs(),a=requireAny(),c=requireCommon(),u={tlds:o.tlds instanceof Set&&{tlds:{allow:o.tlds,deny:null}},base64Regex:{true:{true:/^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}==|[\w\-]{3}=)?$/,false:/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/},false:{true:/^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}(==)?|[\w\-]{3}=?)?$/,false:/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/}},dataUriRegex:/^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/,hexRegex:{
3637
3637
  withPrefix:/^0x[0-9a-f]+$/i,withOptionalPrefix:/^(?:0x)?[0-9a-f]+$/i,withoutPrefix:/^[0-9a-f]+$/i},ipRegex:i({cidr:"forbidden"}).regex,isoDurationRegex:/^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/,guidBrackets:{"{":"}","[":"]","(":")","":""},guidVersions:{uuidv1:"1",uuidv2:"2",uuidv3:"3",uuidv4:"4",uuidv5:"5",uuidv6:"6",uuidv7:"7",uuidv8:"8"},guidSeparators:new Set([void 0,!0,!1,"-",":"]),normalizationForms:["NFC","NFD","NFKC","NFKD"]};return string=a.extend({type:"string",flags:{insensitive:{default:!1},truncate:{default:!1}},terms:{replacements:{init:null}},coerce:{from:"string",method(e,{schema:t,state:r,prefs:n}){const i=t.$_getRule("normalize");i&&(e=e.normalize(i.args.form));const s=t.$_getRule("case");s&&(e="upper"===s.args.direction?e.toLocaleUpperCase():e.toLocaleLowerCase());const o=t.$_getRule("trim");if(o&&o.args.enabled&&(e=e.trim()),t.$_terms.replacements)for(const r of t.$_terms.replacements)e=e.replace(r.pattern,r.replacement)
3638
3638
  ;const a=t.$_getRule("hex");if(a&&a.args.options.byteAligned&&e.length%2!=0&&(e=`0${e}`),t.$_getRule("isoDate")){const t=u.isoDate(e);t&&(e=t)}if(t._flags.truncate){const i=t.$_getRule("max");if(i){let s=i.args.limit;if(c.isResolvable(s)&&(s=s.resolve(e,r,n),!c.limit(s)))return{value:e,errors:t.$_createError("any.ref",s,{ref:i.args.limit,arg:"limit",reason:"must be a positive integer"},r,n)};e=e.slice(0,s)}}return{value:e}}},validate(e,{schema:t,error:r}){if("string"!=typeof e)return{value:e,errors:r("string.base")};if(""===e){const n=t.$_getRule("min");if(n&&0===n.args.limit)return;return{value:e,errors:r("string.empty")}}},rules:{alphanum:{method(){return this.$_addRule("alphanum")},validate:(e,t)=>/^[a-zA-Z0-9]+$/.test(e)?e:t.error("string.alphanum")},base64:{method(t={}){return c.assertOptions(t,["paddingRequired","urlSafe"]),t={urlSafe:!1,paddingRequired:!0,...t},e("boolean"==typeof t.paddingRequired,"paddingRequired must be boolean"),
@@ -4184,11 +4184,11 @@ e?e.message.startsWith(N)?A("wait-on(%s) %s; exiting with error",process.pid,e.m
4184
4184
  ...h(["auth","headers","validateStatus"],e),httpsAgent:new n.Agent({rejectUnauthorized:d,...h(["ca","cert","key","passphrase"],e)}),...s?{}:{maxRedirects:0},proxy:c,...o&&{timeout:o},...g,method:p},I=u?V(j):j;return b(i,a).pipe(v(()=>(t(`making HTTP(S) ${p} request to ${y} url:${g.url} ...`),m(I(t,E))),l),S(!1),C(),_(2))}(e,t);case"tcp:":return function({validatedOpts:{delay:e,interval:t,tcpTimeout:r,reverse:n,simultaneous:i},output:s},o){const a=U(o),c=n?V(G):G;return b(e,t).pipe(v(()=>(s(`making TCP connection to ${a} ...`),m(c(s,a,r))),i),S(!1),C(),_(2))}(e,t);case"socket:":return function({validatedOpts:{delay:e,interval:t,reverse:r,simultaneous:n},output:i},s){const o=U(s),a=r?V(H):H;return b(e,t).pipe(v(()=>(i(`making socket connection to ${o} ...`),m(a(i,o))),n),S(!1),C(),_(2))}(e,t);default:return function({validatedOpts:{delay:e,interval:t,reverse:r,simultaneous:n,window:i},output:s},o){const a=U(o),c=r?I(e=>-1===e):w((e,t)=>{if(t>-1){const{size:r,t:n}=e,o=Date.now()
4185
4185
  ;return-1!==r&&t===r?o>=n+i?(s(` file stabilized at size:${r} file:${a}`),!0):(s(` file exists, checking for size change during stability window, size:${r} file:${a}`),e):(s(` file exists, checking for size changes, size:${t} file:${a}`),{size:t,t:o})}return e},{size:-1,t:Date.now()});return b(e,t).pipe(v(()=>(s(`checking file stat for file:${a} ...`),m(async function(e){try{const{size:t}=await x(e);return t}catch{return-1}}(a))),n),c,I(e=>!R(e)&&e),S(!1),C(),_(2))}(e,t)}}function U(e){const t=F.exec(e);return t?t[3]:e}async function j(e,t){try{const r=await B(t);return e(` HTTP(S) result for ${t.url}: ${s.inspect(h(["status","statusText","headers","data"],r))}`),!0}catch(r){return e(` HTTP(S) error for ${t.url} ${r.toString()}`),!1}}async function G(e,t,r){const[,,n,s]=Q.exec(t),o=n||"localhost";return new Promise(t=>{const n=i.connect(s,o).on("error",r=>{e(` error connecting to TCP host:${o} port:${s} ${r.toString()}`),t(!1)}).on("timeout",()=>{
4186
4186
  e(` timed out connecting to TCP host:${o} port:${s} tcpTimeout:${r}ms`),n.end(),t(!1)}).on("connect",()=>{e(` TCP connection successful to host:${o} port:${s}`),n.end(),t(!0)});n.setTimeout(r)})}async function H(e,t){return new Promise(r=>{const n=i.connect(t).on("error",n=>{e(` error connecting to socket socket:${t} ${n.toString()}`),r(!1)}).on("connect",()=>{e(` connected to socket:${t}`),n.end(),r(!0)})})}function V(e){return async function(...t){return!await e(...t)}}return waitOn_1=function(e,t){return void 0!==t?O(e,t):new Promise(function(t,r){O(e,function(e){e?r(e):t()})})},waitOn_1}var waitOnExports=requireWaitOn(),waitOn=getDefaultExportFromCjs(waitOnExports);function _optionalChain$o(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}class EventTailer{__init(){
4187
- this.shouldExit=!1}constructor(e){EventTailer.prototype.__init.call(this),this.eventsFilePath=e}async waitForFileToExist(e){try{return void await fsp.access(e)}catch(e){}process.stdout.write("Waiting for first tool call…\n");let t=null;const r=new Promise(e=>{t=setInterval(()=>{this.shouldExit&&(t&&(clearInterval(t),t=null),e())},50)}),n=waitOn({resources:[`file:${e}`],interval:50,window:0,timeout:_optionalChain$o([this,"access",e=>e.options,"optionalAccess",e=>e.waitTimeoutMs])});try{await Promise.race([n,r])}catch(e){if(this.shouldExit)return;throw e}finally{t&&clearInterval(t)}}async start(e){if(this.shouldExit=!1,this.options=e,await this.waitForFileToExist(this.eventsFilePath),this.shouldExit)return;this.tail=new tailExports.Tail(this.eventsFilePath,{fromBeginning:!0,follow:!0}),this.tail.on("line",t=>{if(!this.shouldExit&&0!==t.trim().length)try{const r=JSON.parse(t);e.onEvent(r)}catch(r){
4188
- _optionalChain$o([e,"access",e=>e.onError,"optionalCall",e=>e(new Error(`Failed to parse event: ${t}`))])}}),this.tail.on("error",t=>{this.shouldExit||_optionalChain$o([e,"access",e=>e.onError,"optionalCall",e=>e(t)])});const t=()=>{this.shouldExit=!0,this.stop()};return this.cleanupHandler=t,process.on("SIGINT",t),process.on("SIGTERM",t),new Promise(e=>{const t=()=>{this.shouldExit?e():setTimeout(t,50)};t()})}stop(){this.shouldExit=!0,this.cleanupHandler&&(process.removeListener("SIGINT",this.cleanupHandler),process.removeListener("SIGTERM",this.cleanupHandler),this.cleanupHandler=void 0),this.tail&&(this.tail.unwatch(),this.tail=void 0),_optionalChain$o([this,"access",e=>e.options,"optionalAccess",e=>e.onShutdown,"optionalCall",e=>e()])}}function _nullishCoalesce$n(e,t){return null!=e?e:t()}function useExecutionTree(e){const[t,r]=reactExports.useState({});return{handleManagementEvent:async function(e){switch(e.id){case"startTool":r(t=>({...t,[e.uuid]:{uuid:e.uuid,name:e.name,
4189
- parent:_nullishCoalesce$n(e.parent,()=>null),start:new Date}}));break;case"crash":if(e.err instanceof LLMCacheMissError)throw new Error("No matching snapshot found for this LLM request");r(t=>({...t,[e.uuid]:{...t[e.uuid],end:new Date,exitCode:FAILURE,errorMessage:getMessageFromMaybeError(e.err),errorStack:getStackFromMaybeError(e.err)}}));break;case"endTool":r(t=>({...t,[e.uuid]:{...t[e.uuid],end:new Date,exitCode:e.exitCode}}));break;case"bye":r(e=>Object.fromEntries(Object.values(e).map(e=>[e.uuid,{...e,end:new Date,exitCode:FAILURE}])))}return Promise.resolve()},executionTree:reactExports.useMemo(()=>getExecutionTree(t,e),[t,e])}}function getExecutionTree(e,t){function r(e,t){return e.filter(e=>e.parentId===t).map(t=>({...t,children:r(e,t.id)}))}function n(i){const s=e[i];if(!s)throw new Error(`Execution not found for id: ${i}`);const o=r(t.filter(e=>e.toolRunId===i)),a=Object.values(e).filter(e=>e.parent===i);return{uuid:s.uuid,name:s.name,exitCode:s.exitCode,parent:s.parent,
4190
- start:s.start,end:s.end,errorMessage:s.errorMessage,errorStack:s.errorStack,children:a.map(e=>n(e.uuid)),activities:o}}return findRootToolExecutions(Object.values(e)).map(e=>n(e.uuid))}function hasEnded(e){return e.length>0&&e.every(e=>e.end)}function findRootToolExecutions(e){const t=new Set(e.map(({uuid:e})=>e));return e.filter(({parent:e})=>!e||!t.has(e))}function throttle(e,t,r){var n,i={},s=i.noTrailing,o=void 0!==s&&s,a=i.noLeading,c=void 0!==a&&a,u=i.debounceMode,l=void 0===u?void 0:u,d=!1,p=0;function h(){n&&clearTimeout(n)}function A(){for(var r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];var a=this,u=Date.now()-p;function A(){p=Date.now(),t.apply(a,i)}function f(){n=void 0}d||(c||!l||n||A(),h(),void 0===l&&u>e?c?(p=Date.now(),o||(n=setTimeout(l?f:A,e))):A():!0!==o&&(n=setTimeout(l?f:A,void 0===l?e-u:e)))}return A.cancel=function(e){var t=(e||{}).upcomingOnly,r=void 0!==t&&t;h(),d=!r},A}function _nullishCoalesce$m(e,t){return null!=e?e:t()}
4191
- function _optionalChain$n(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function isManagementTypingEvent(e){return"typingStart"===e.id||"typingDone"===e.id||"typingChunk"===e.id||"typingCountTokens"===e.id}function useTypingTracker(){const[e,t]=reactExports.useState(new Map),r=reactExports.useCallback(()=>throttle(100,(e,r)=>{t(t=>{const n=new Map(t),i=n.get(e);return i&&n.set(e,{...i,characterCount:i.characterCount+r}),n})}),[]),n=reactExports.useCallback((e,n)=>{isManagementTypingEvent(e)&&n&&("typingStart"===e.id?t(t=>{const r=new Map(t),n=r.get(e.uuid);return r.set(e.uuid,{characterCount:_optionalChain$n([n,"optionalAccess",e=>e.characterCount])||0,activeCount:(_optionalChain$n([n,"optionalAccess",e=>e.activeCount])||0)+1}),r
4187
+ this.shouldExit=!1}__init2(){this.isStarting=!1}constructor(e){EventTailer.prototype.__init.call(this),EventTailer.prototype.__init2.call(this),this.eventsFilePath=e}async waitForFileToExist(e){try{return void await fsp.access(e)}catch(e){}process.stdout.write("Waiting for first tool call…\n");let t=null;const r=new Promise(e=>{t=setInterval(()=>{this.shouldExit&&(t&&(clearInterval(t),t=null),e())},50)}),n=waitOn({resources:[`file:${e}`],interval:50,window:0,timeout:_optionalChain$o([this,"access",e=>e.options,"optionalAccess",e=>e.waitTimeoutMs])});try{await Promise.race([n,r])}catch(e){if(this.shouldExit)return;throw e}finally{t&&clearInterval(t)}}async start(e){if(this.isRunning()||this.isStarting)return Promise.resolve();this.isStarting=!0;try{if(this.shouldExit=!1,this.options=e,await this.waitForFileToExist(this.eventsFilePath),this.shouldExit)return;this.tail=new tailExports.Tail(this.eventsFilePath,{fromBeginning:!0,follow:!0})}finally{this.isStarting=!1}
4188
+ return this.tail.on("line",t=>{if(!this.shouldExit&&0!==t.trim().length)try{const r=JSON.parse(t);e.onEvent(r)}catch(r){_optionalChain$o([e,"access",e=>e.onError,"optionalCall",e=>e(new Error(`Failed to parse event: ${t}`))])}}),this.tail.on("error",t=>{this.shouldExit||_optionalChain$o([e,"access",e=>e.onError,"optionalCall",e=>e(t)])}),new Promise(e=>{const t=()=>{this.shouldExit?e():setTimeout(t,50)};t()})}stop(){this.shouldExit=!0,this.isStarting=!1,this.tail&&(this.tail.unwatch(),this.tail=void 0),_optionalChain$o([this,"access",e=>e.options,"optionalAccess",e=>e.onShutdown,"optionalCall",e=>e()])}isRunning(){return!!this.tail&&!this.shouldExit}}function _nullishCoalesce$n(e,t){return null!=e?e:t()}function useExecutionTree(e){const[t,r]=reactExports.useState({});return{handleManagementEvent:async function(e){switch(e.id){case"startTool":r(t=>({...t,[e.uuid]:{uuid:e.uuid,name:e.name,parent:_nullishCoalesce$n(e.parent,()=>null),start:new Date}}));break;case"crash":
4189
+ if(e.err instanceof LLMCacheMissError)throw new Error("No matching snapshot found for this LLM request");r(t=>({...t,[e.uuid]:{...t[e.uuid],end:new Date,exitCode:FAILURE,errorMessage:getMessageFromMaybeError(e.err),errorStack:getStackFromMaybeError(e.err)}}));break;case"endTool":r(t=>({...t,[e.uuid]:{...t[e.uuid],end:new Date,exitCode:e.exitCode}}));break;case"bye":r(e=>Object.fromEntries(Object.values(e).map(e=>[e.uuid,{...e,end:new Date,exitCode:FAILURE}])))}return Promise.resolve()},executionTree:reactExports.useMemo(()=>getExecutionTree(t,e),[t,e])}}function getExecutionTree(e,t){function r(e,t){return e.filter(e=>e.parentId===t).map(t=>({...t,children:r(e,t.id)}))}function n(i){const s=e[i];if(!s)throw new Error(`Execution not found for id: ${i}`);const o=r(t.filter(e=>e.toolRunId===i)),a=Object.values(e).filter(e=>e.parent===i);return{uuid:s.uuid,name:s.name,exitCode:s.exitCode,parent:s.parent,start:s.start,end:s.end,errorMessage:s.errorMessage,errorStack:s.errorStack,
4190
+ children:a.map(e=>n(e.uuid)),activities:o}}return findRootToolExecutions(Object.values(e)).map(e=>n(e.uuid))}function hasEnded(e){return e.length>0&&e.every(e=>e.end)}function findRootToolExecutions(e){const t=new Set(e.map(({uuid:e})=>e));return e.filter(({parent:e})=>!e||!t.has(e))}function throttle(e,t,r){var n,i={},s=i.noTrailing,o=void 0!==s&&s,a=i.noLeading,c=void 0!==a&&a,u=i.debounceMode,l=void 0===u?void 0:u,d=!1,p=0;function h(){n&&clearTimeout(n)}function A(){for(var r=arguments.length,i=new Array(r),s=0;s<r;s++)i[s]=arguments[s];var a=this,u=Date.now()-p;function A(){p=Date.now(),t.apply(a,i)}function f(){n=void 0}d||(c||!l||n||A(),h(),void 0===l&&u>e?c?(p=Date.now(),o||(n=setTimeout(l?f:A,e))):A():!0!==o&&(n=setTimeout(l?f:A,void 0===l?e-u:e)))}return A.cancel=function(e){var t=(e||{}).upcomingOnly,r=void 0!==t&&t;h(),d=!r},A}function _nullishCoalesce$m(e,t){return null!=e?e:t()}function _optionalChain$n(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,
4191
+ ("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function isManagementTypingEvent(e){return"typingStart"===e.id||"typingDone"===e.id||"typingChunk"===e.id||"typingCountTokens"===e.id}function useTypingTracker(){const[e,t]=reactExports.useState(new Map),r=reactExports.useCallback(()=>throttle(100,(e,r)=>{t(t=>{const n=new Map(t),i=n.get(e);return i&&n.set(e,{...i,characterCount:i.characterCount+r}),n})}),[]),n=reactExports.useCallback((e,n)=>{isManagementTypingEvent(e)&&n&&("typingStart"===e.id?t(t=>{const r=new Map(t),n=r.get(e.uuid);return r.set(e.uuid,{characterCount:_optionalChain$n([n,"optionalAccess",e=>e.characterCount])||0,activeCount:(_optionalChain$n([n,"optionalAccess",e=>e.activeCount])||0)+1}),r
4192
4192
  }):"typingChunk"===e.id?r()(e.uuid,_nullishCoalesce$m(_nullishCoalesce$m(e.totalTokens,()=>_optionalChain$n([e,"access",e=>e.chunk,"optionalAccess",e=>e.length])),()=>0)):"typingCountTokens"===e.id?r()(e.uuid,e.totalTokens):"typingDone"===e.id&&t(t=>{const r=new Map(t),n=r.get(e.uuid);return n&&n.activeCount>0&&r.set(e.uuid,{...n,activeCount:n.activeCount-1}),r}))},[r]),i=reactExports.useCallback(()=>{let t=0;for(const r of e.values())t+=r.characterCount;return Math.ceil(t/4)},[e]);return{handleTypingEvent:n,cleanup:reactExports.useCallback(()=>{r().cancel(),t(new Map)},[r]),getTotalTokenCount:i,activeTypers:new Map(Array.from(e.entries()).filter(([e,t])=>t.activeCount>0))}}function useReporterState(e=[]){const[t,r]=reactExports.useState({messages:e,activities:[],hideOverview:!1}),n=reactExports.useCallback(e=>{if(!isManagementTypingEvent(e))if("report"===e.id){const t=e.data;switch(t.type){case"message":r(t=>({...t,messages:[...t.messages,e]}));break;case"activityStarted":
4193
4193
  "activity"in t&&r(e=>({...e,activities:[...e.activities,t.activity]}));break;case"activityUpdated":"activity"in t&&r(e=>({...e,activities:e.activities.map(e=>e.id===t.activity.id?t.activity:e)}));break;case"hideOverview":r(e=>({...e,hideOverview:!0}))}}else r(t=>({...t,messages:[...t.messages,e]}))},[]),i=reactExports.useMemo(()=>{const e=new Map;return t.messages.forEach(t=>{if("id"in t&&!("type"in t)){const r=t;"startTool"===r.id&&e.set(r.uuid,r.parent)}}),t=>{let r=0,n=t;const i=new Set;for(;n&&!i.has(n);){i.add(n);const t=e.get(n);if(!t)break;r++,n=t}return r}},[t.messages]),{handleManagementEvent:s,executionTree:o}=useExecutionTree(t.activities);return{...t,executionTree:o,handleManagementEvent:async e=>{n(e),await s(e)},getToolDepth:i}}var dots={interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},dots2={interval:80,frames:["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},dots3={interval:80,frames:["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},dots4={interval:80,
4194
4194
  frames:["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},dots5={interval:80,frames:["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},dots6={interval:80,frames:["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},dots7={interval:80,frames:["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},dots8={interval:80,frames:["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},dots9={interval:80,frames:["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},dots10={interval:80,frames:["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},dots11={interval:100,frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},dots12={interval:80,
@@ -4228,19 +4228,19 @@ mode:e,event:t});if("message"===t.data.type){const e=t.data.message;switch(e.typ
4228
4228
  ;return jsxRuntimeExports.jsxs(Box,{flexDirection:"column",children:[jsxRuntimeExports.jsx(Heading,{children:"Overview"}),jsxRuntimeExports.jsxs(OverviewRow,{label:"Files",children:[jsxRuntimeExports.jsx(Text,{color:"green",children:a.created})," ",jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"added,"})," ",a.modified," ",jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"modified,"})," ",jsxRuntimeExports.jsx(Text,{color:"red",children:a.removed})," ",jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"deleted"})]}),jsxRuntimeExports.jsxs(OverviewRow,{label:"Lines",children:[jsxRuntimeExports.jsx(Text,{color:"green",children:o.added?`+${o.added}`:0})," ",jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"added,"})," ",jsxRuntimeExports.jsx(Text,{color:"red",children:o.removed?`-${o.removed}`:0})," ",jsxRuntimeExports.jsx(Text,{dimColor:!0,children:"removed"})]}),jsxRuntimeExports.jsx(OverviewRow,{label:"Time",children:formatDuration(s)}),jsxRuntimeExports.jsx(OverviewRow,{
4229
4229
  label:"Tokens",children:n})]})}function OverviewRow({label:e,children:t}){return jsxRuntimeExports.jsxs(Box,{flexDirection:"row",children:[jsxRuntimeExports.jsx(Box,{width:8,children:jsxRuntimeExports.jsxs(Text,{dimColor:!0,children:[e,":"]})}),jsxRuntimeExports.jsx(Text,{children:t})]})}function Summary({messages:e}){const t=e.filter(e=>"report"===e.id&&"message"===e.data.type&&"summary"===e.data.message.type).map(({data:{message:e}})=>e).map(({id:e,content:t})=>t.map(t=>({id:e,text:t}))).flat().filter(Boolean);return 0===t.length?null:jsxRuntimeExports.jsxs(Box,{flexDirection:"column",children:[jsxRuntimeExports.jsx(Heading,{children:"Summary"}),t.map(({id:e,text:t})=>jsxRuntimeExports.jsx(Box,{children:jsxRuntimeExports.jsx(Text,{dimColor:!0,children:t})},`${e}-${t}`))]})}function ToolResults({mode:e,messages:t,activities:r,getTotalTokenCount:n,activeTypers:i,executionTree:s,fsd:o,staticMessages:a=!1,hideOverview:c=!1}){const u=a?jsxRuntimeExports.jsx(Static,{items:t,
4230
4230
  children:(t,r)=>jsxRuntimeExports.jsx(MessageEntry,{mode:e,event:t},r)}):jsxRuntimeExports.jsx(Box,{flexDirection:"column",children:t.map((t,r)=>jsxRuntimeExports.jsx(MessageEntry,{mode:e,event:t},r))});return jsxRuntimeExports.jsxs(Box,{flexDirection:"column",children:[u,jsxRuntimeExports.jsx(Activities,{activities:r,activeTypers:i}),hasEnded(s)&&jsxRuntimeExports.jsxs(Box,{flexDirection:"column",children:[!c&&jsxRuntimeExports.jsx(Overview,{getTotalTokenCount:n,executionTree:s,fileDiff:isFsDiff(o)?o.diff():void 0}),jsxRuntimeExports.jsx(Summary,{messages:t})]})]})}function Sidecar({tailer:e}){const[t,r]=reactExports.useState(null),{messages:n,activities:i,hideOverview:s,handleManagementEvent:o,executionTree:a}=useReporterState(),c=reactExports.useRef(!1);return reactExports.useEffect(()=>{if(c.current)return;c.current=!0;(async()=>{try{await e.start({onEvent:e=>{o(e).catch(e=>{r(`Error handling event: ${String(e)}`)})},onError:e=>{r(`Error while tailing events: ${String(e)}`)},
4231
- onShutdown:()=>{}})}catch(e){r(`Failed to start event observation: ${String(e)}`)}})().catch(e=>{r(`Failed to start tailing: ${String(e)}`)})},[e,o]),t?jsxRuntimeExports.jsx(Text,{children:t}):jsxRuntimeExports.jsx(ToolResults,{mode:"observe",messages:n,activities:i,getTotalTokenCount:()=>0,activeTypers:new Map,executionTree:a,fsd:null,staticMessages:!0,hideOverview:s})}reactExports.createContext({marker:figures.line}),reactExports.createContext({marker:""}),chalk.inverse(" "),chalk.inverse(" ");const observeCommand=new Command$1({name:"observe",summary:"[Experimental] Provides a real-time view of Tessl activity for the current project. Run in a directory initialized with Tessl. Best used in a separate window.",requiresConfig:!1,flags:{},handler:async()=>{const e=getSessionDataPath(),t=path__default$1.join(e,"events.jsonl"),r=new EventTailer(t);return await render(jsxRuntimeExports.jsx(Sidecar,{tailer:r})).waitUntilExit(),SUCCESS}});function createSpinner(e){return ora({hideCursor:!1,
4232
- discardStdin:!1}).start(e)}const registryArchiveCommand=new Command$1({name:"registry-archive",summary:"Archive specs in the Tessl registry",allowArbitraryFlags:!1,flags:{spec:{type:String,description:"The full name of the spec to archive"},reason:{type:String,description:"The reason for archiving the specs"}},requiresLogin:!0,requiresConfig:!1,handler:async({monitoring:{logger:e},args:t})=>{const{spec:r,reason:n}=t;if(!r)throw new ExpectedError('A --spec argument is required, in the format "workspace/spec@version"');if(!n)throw new ExpectedError("A --reason argument is required");const[i,s]=r.split("@");if(!i||!s)throw new ExpectedError('The spec must be in the format "workspace/spec@version"');const[o,a]=i.split("/");if(!o||!a)throw new ExpectedError('The spec must be in the format "workspace/tile"');const c=createSpinner("Archiving"),u=getTesslClient(e,validateBaseEnv(process.env)),l=await u.POST("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{
4233
- workspaceName:o,tileName:a,version:s}},body:{archived:!0,archivedReason:n}});return l.error?(e.error({err:l.error},"Failed to archive spec"),c.fail(apiErrToString(l.error)),FAILURE):(c.succeed(`Archived ${o}/${a}@${s}`),SUCCESS)}});function _nullishCoalesce$i(e,t){return null!=e?e:t()}const installCommand=new Command$1({name:"registry-install",summary:"Install usage specs into your project",positionals:[{name:"name",description:"The name of the usage spec to install"}],allowArbitraryFlags:!1,requiresLogin:!1,handler:async({positionals:{name:e},monitoring:{logger:t},projectDir:r,isInteractive:n})=>{if(!n)throw new ExpectedError('"install" does not support non-interactive mode');const i=openFsd(r),s=getTesslClient(t,validateBaseEnv(process.env));if(!e){const e=ora({hideCursor:!1,discardStdin:!1}).start("Installing usage specs"),n=await syncUsageSpecs(r,i,s);return n.success?(e.succeed("Installed usage specs"),SUCCESS):(t.error({err:n.error},"Failed to sync usage specs"),e.fail(n.error),
4234
- FAILURE)}const o=ora({hideCursor:!1,discardStdin:!1}).start("Retrieving spec data"),a=e.split("@"),c=a[0];let u=a[1];const[l,d]=_nullishCoalesce$i(c,()=>"").split("/");if(!l||!d)return t.error({name:e},'The name argument must be in the format "workspace/tile" (or "workspace/tile@version")'),o.fail('The name argument must be in the format "workspace/tile" (or "workspace/tile@version")'),FAILURE;const p=await s.GET("/v1/tiles/{workspaceName}/{tileName}",{params:{path:{workspaceName:l,tileName:d}}});if(p.error)return t.error({name:e,err:p.error},"Failed to get tile"),o.fail(apiErrToString(p.error)),FAILURE;const h=p.data.data;if(!u){const e=h.attributes.latestVersion;if(!e)return t.error({fullName:c},"The tile does not have a latest version. Please specify a version"),o.fail("The tile does not have a latest version. Please specify a version"),FAILURE;u=e}const A=await s.GET("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:l,tileName:d,version:u}}})
4235
- ;if(A.error)return t.error({fullName:c,version:u,err:A.error},"Failed to get tile version"),o.fail(apiErrToString(A.error)),FAILURE;const f=A.data.data;if(!f.attributes.describes)return t.error({name:e,version:u},"Invalid usage spec; does not describe a package"),o.fail("Invalid usage spec; does not describe a package"),FAILURE;o.text=`Installing ${h.attributes.fullName}@${u}`;const g=await updateTesslJsonDependencies(i,{add:[{workspaceName:l,tileName:d,newVersion:f.attributes.version}]});if(!g.success)return t.error({name:e,version:u,err:g.error},"Failed to update Tessl JSON dependencies"),o.fail(g.error),FAILURE;const m=await syncUsageSpecs(r,i,s);return m.success?(t.info({name:e,version:u},"Usage spec installed"),o.succeed(`Installed ${h.attributes.fullName}@${u}`),SUCCESS):(t.error({name:e,err:m.error},"Failed to sync usage specs"),o.fail(m.error),FAILURE)}}),registryPublishCommand=new Command$1({name:"registry-publish",summary:"Publish specs to the Tessl registry",
4236
- allowArbitraryFlags:!1,positionals:[{name:"path",description:"The path to the spec files to publish"}],requiresLogin:!0,requiresConfig:!1,handler:async({projectDir:e,monitoring:{logger:t},positionals:{path:r}})=>{if(!r)throw new ExpectedError("A path to the spec files is required");const n=ora({hideCursor:!1,discardStdin:!1}).start("Publishing"),i=getTesslClient(t,validateBaseEnv(process.env));try{const s=(await readdir(join(e,r),{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>join(e.parentPath,e.name)),o=createGzip(),a=tar.pack();await Promise.all(s.map(async e=>{const t=await readFile$1(e),n=relative$1(r,e);a.entry({name:n},t)})),a.finalize();const c=a.pipe(o),u=await i.POST("/v1/tiles",{params:{header:{"content-type":"application/x-tar"}},bodySerializer:e=>e,duplex:"half",body:c});if(u.error)return t.error({err:u.error},"Failed to publish specs"),n.fail(apiErrToString(u.error)),FAILURE;const{fullName:l,version:d}=u.data.data.attributes
4237
- ;return n.succeed(`Spec published as ${l}@${d}`),SUCCESS}catch(e){return t.error({err:e},"Failed to publish specs"),n.fail(e instanceof Error?e.message:"Failed to publish specs"),FAILURE}}});var ansiEscapes$3={exports:{}},hasRequiredAnsiEscapes$1;function requireAnsiEscapes$1(){return hasRequiredAnsiEscapes$1||(hasRequiredAnsiEscapes$1=1,function(e){const t=e.exports;e.exports.default=t;const r="[",n="]",i="",s=";",o="Apple_Terminal"===process.env.TERM_PROGRAM;t.cursorTo=(e,t)=>{if("number"!=typeof e)throw new TypeError("The `x` argument is required");return"number"!=typeof t?r+(e+1)+"G":r+(t+1)+";"+(e+1)+"H"},t.cursorMove=(e,t)=>{if("number"!=typeof e)throw new TypeError("The `x` argument is required");let n="";return e<0?n+=r+-e+"D":e>0&&(n+=r+e+"C"),t<0?n+=r+-t+"A":t>0&&(n+=r+t+"B"),n},t.cursorUp=(e=1)=>r+e+"A",t.cursorDown=(e=1)=>r+e+"B",t.cursorForward=(e=1)=>r+e+"C",t.cursorBackward=(e=1)=>r+e+"D",t.cursorLeft="",t.cursorSavePosition=o?"7":"",
4238
- t.cursorRestorePosition=o?"8":"",t.cursorGetPosition="",t.cursorNextLine="",t.cursorPrevLine="",t.cursorHide="[?25l",t.cursorShow="[?25h",t.eraseLines=e=>{let r="";for(let n=0;n<e;n++)r+=t.eraseLine+(n<e-1?t.cursorUp():"");return e&&(r+=t.cursorLeft),r},t.eraseEndLine="",t.eraseStartLine="",t.eraseLine="",t.eraseDown="",t.eraseUp="",t.eraseScreen="",t.scrollUp="",t.scrollDown="",t.clearScreen="c",t.clearTerminal="win32"===process.platform?`${t.eraseScreen}${r}0f`:`${t.eraseScreen}${r}3J${r}H`,t.beep=i,t.link=(e,t)=>[n,"8",s,s,t,i,e,n,"8",s,s,i].join(""),t.image=(e,t={})=>{let r=`${n}1337;File=inline=1`;return t.width&&(r+=`;width=${t.width}`),t.height&&(r+=`;height=${t.height}`),!1===t.preserveAspectRatio&&(r+=";preserveAspectRatio=0"),r+":"+e.toString("base64")+i},t.iTerm={setCwd:(e=process.cwd())=>`${n}50;CurrentDir=${e}${i}`,annotation:(e,t={})=>{let r=`${n}1337;`;const s=void 0!==t.x,o=void 0!==t.y
4239
- ;if((s||o)&&(!s||!o||void 0===t.length))throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");return e=e.replace(/\|/g,""),r+=t.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",t.length>0?r+=(s?[e,t.length,t.x,t.y]:[t.length,e]).join("|"):r+=e,r+i}}}(ansiEscapes$3)),ansiEscapes$3.exports}var ansiEscapesExports$1=requireAnsiEscapes$1(),ansiEscapes$2=getDefaultExportFromCjs(ansiEscapesExports$1);const checkboxTheme={icon:{checked:colors.green(figures$1.circleFilled),unchecked:figures$1.circle,cursor:figures$1.pointer},style:{disabledChoice:e=>colors.dim(`- ${e}`),renderSelectedChoices:e=>e.map(e=>e.short).join(", "),description:e=>colors.cyan(e)},helpMode:"auto"};function isSelectable$1(e){return!Separator.isSeparator(e)&&!e.disabled}function isChecked(e){return isSelectable$1(e)&&Boolean(e.checked)}function toggle(e){return isSelectable$1(e)?{...e,checked:!e.checked}:e}function check(e){return function(t){return isSelectable$1(t)?{...t,checked:e}:t}}
4240
- function normalizeChoices$1(e){return e.map(e=>{if(Separator.isSeparator(e))return e;if("string"==typeof e)return{value:e,name:e,short:e,disabled:!1,checked:!1};const t=e.name??String(e.value),r={value:e.value,name:t,short:e.short??t,disabled:e.disabled??!1,checked:e.checked??!1};return e.description&&(r.description=e.description),r})}var checkbox=createPrompt((e,t)=>{const{instructions:r,pageSize:n=7,loop:i=!0,required:s,validate:o=()=>!0}=e,a={all:"a",invert:"i",...e.shortcuts},c=makeTheme(checkboxTheme,e.theme),u=useRef(!0),[l,d]=useState("idle"),p=usePrefix({status:l,theme:c}),[h,A]=useState(normalizeChoices$1(e.choices)),f=useMemo(()=>{const e=h.findIndex(isSelectable$1),t=h.findLastIndex(isSelectable$1);if(-1===e)throw new ValidationError$1("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[h]),[g,m]=useState(f.first),[y,E]=useState(!0),[b,C]=useState();useKeypress(async e=>{if(isEnterKey(e)){
4241
- const e=h.filter(isChecked),r=await o([...e]);s&&!h.some(isChecked)?C("At least one choice must be selected"):!0===r?(d("done"),t(e.map(e=>e.value))):C(r||"You must select a valid value")}else if(isUpKey(e)||isDownKey(e)){if(i||isUpKey(e)&&g!==f.first||isDownKey(e)&&g!==f.last){const t=isUpKey(e)?-1:1;let r=g;do{r=(r+t+h.length)%h.length}while(!isSelectable$1(h[r]));m(r)}}else if(isSpaceKey(e))C(void 0),E(!1),A(h.map((e,t)=>t===g?toggle(e):e));else if(e.name===a.all){const e=h.some(e=>isSelectable$1(e)&&!e.checked);A(h.map(check(e)))}else if(e.name===a.invert)A(h.map(toggle));else if(isNumberKey(e)){const t=Number(e.name)-1;let r=-1;const n=h.findIndex(e=>!Separator.isSeparator(e)&&(r++,r===t)),i=h[n];i&&isSelectable$1(i)&&(m(n),A(h.map((e,t)=>t===n?toggle(e):e)))}});const I=c.style.message(e.message,l);let v;const w=usePagination({items:h,active:g,renderItem({item:e,isActive:t}){if(Separator.isSeparator(e))return` ${e.separator}`;if(e.disabled){
4242
- const t="string"==typeof e.disabled?e.disabled:"(disabled)";return c.style.disabledChoice(`${e.name} ${t}`)}t&&(v=e.description);const r=e.checked?c.icon.checked:c.icon.unchecked;return(t?c.style.highlight:e=>e)(`${t?c.icon.cursor:" "}${r} ${e.name}`)},pageSize:n,loop:i});if("done"===l){const e=h.filter(isChecked);return`${p} ${I} ${c.style.answer(c.style.renderSelectedChoices(e,h))}`}let S="",_="";if("always"===c.helpMode||"auto"===c.helpMode&&y&&(void 0===r||r)){if("string"==typeof r)S=r;else{S=` (Press ${[`${c.style.key("space")} to select`,a.all?`${c.style.key(a.all)} to toggle all`:"",a.invert?`${c.style.key(a.invert)} to invert selection`:"",`and ${c.style.key("enter")} to proceed`].filter(e=>""!==e).join(", ")})`}h.length>n&&("always"===c.helpMode||"auto"===c.helpMode&&u.current)&&(_=`\n${c.style.help("(Use arrow keys to reveal more choices)")}`,u.current=!1)}const D=v?`\n${c.style.description(v)}`:"";let B="";return b&&(B=`\n${c.style.error(b)}`),
4243
- `${p} ${I}${S}\n${w}${_}${D}${B}${ansiEscapes$2.cursorHide}`});function getBooleanValue(e,t){let r=!1!==t;return/^(y|yes)/i.test(e)?r=!0:/^(n|no)/i.test(e)&&(r=!1),r}function boolToString(e){return e?"Yes":"No"}var confirm=createPrompt((e,t)=>{const{transformer:r=boolToString}=e,[n,i]=useState("idle"),[s,o]=useState(""),a=makeTheme(e.theme),c=usePrefix({status:n,theme:a});useKeypress((n,a)=>{if(isEnterKey(n)){const n=getBooleanValue(s,e.default);o(r(n)),i("done"),t(n)}else if("tab"===n.name){const t=boolToString(!getBooleanValue(s,e.default));a.clearLine(0),a.write(t),o(t)}else o(a.line)});let u=s,l="";"done"===n?u=a.style.answer(s):l=` ${a.style.defaultAnswer(!1===e.default?"y/N":"Y/n")}`;return`${c} ${a.style.message(e.message,n)}${l} ${u}`}),ansiEscapes$1={exports:{}},hasRequiredAnsiEscapes;function requireAnsiEscapes(){return hasRequiredAnsiEscapes||(hasRequiredAnsiEscapes=1,function(e){const t=e.exports;e.exports.default=t
4231
+ onShutdown:()=>{}})}catch(e){r(`Failed to start event observation: ${String(e)}`)}})().catch(e=>{r(`Failed to start tailing: ${String(e)}`)})},[e,o]),t?jsxRuntimeExports.jsx(Text,{children:t}):jsxRuntimeExports.jsx(ToolResults,{mode:"observe",messages:n,activities:i,getTotalTokenCount:()=>0,activeTypers:new Map,executionTree:a,fsd:null,staticMessages:!0,hideOverview:s})}reactExports.createContext({marker:figures.line}),reactExports.createContext({marker:""}),chalk.inverse(" "),chalk.inverse(" ");const observeCommand=new Command$1({name:"observe",summary:"[Experimental] Provides a real-time view of Tessl activity for the current project. Run in a directory initialized with Tessl. Best used in a separate window.",requiresConfig:!1,flags:{},handler:async()=>{const e=getSessionDataPath(),t=path__default$1.join(e,"events.jsonl"),r=new EventTailer(t),n=render(jsxRuntimeExports.jsx(Sidecar,{tailer:r})),i=()=>{r.stop(),n.unmount()};process.on("SIGINT",i),process.on("SIGTERM",i);try{
4232
+ await n.waitUntilExit()}finally{process.removeListener("SIGINT",i),process.removeListener("SIGTERM",i)}return SUCCESS}});function createSpinner(e){return ora({hideCursor:!1,discardStdin:!1}).start(e)}const registryArchiveCommand=new Command$1({name:"registry-archive",summary:"Archive specs in the Tessl registry",allowArbitraryFlags:!1,flags:{spec:{type:String,description:"The full name of the spec to archive"},reason:{type:String,description:"The reason for archiving the specs"}},requiresLogin:!0,requiresConfig:!1,handler:async({monitoring:{logger:e},args:t})=>{const{spec:r,reason:n}=t;if(!r)throw new ExpectedError('A --spec argument is required, in the format "workspace/spec@version"');if(!n)throw new ExpectedError("A --reason argument is required");const[i,s]=r.split("@");if(!i||!s)throw new ExpectedError('The spec must be in the format "workspace/spec@version"');const[o,a]=i.split("/");if(!o||!a)throw new ExpectedError('The spec must be in the format "workspace/tile"')
4233
+ ;const c=createSpinner("Archiving"),u=getTesslClient(e,validateBaseEnv(process.env)),l=await u.POST("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:o,tileName:a,version:s}},body:{archived:!0,archivedReason:n}});return l.error?(e.error({err:l.error},"Failed to archive spec"),c.fail(apiErrToString(l.error)),FAILURE):(c.succeed(`Archived ${o}/${a}@${s}`),SUCCESS)}});function _nullishCoalesce$i(e,t){return null!=e?e:t()}const installCommand=new Command$1({name:"registry-install",summary:"Install usage specs into your project",positionals:[{name:"name",description:"The name of the usage spec to install"}],allowArbitraryFlags:!1,requiresLogin:!1,handler:async({positionals:{name:e},monitoring:{logger:t},projectDir:r,isInteractive:n})=>{if(!n)throw new ExpectedError('"install" does not support non-interactive mode');const i=openFsd(r),s=getTesslClient(t,validateBaseEnv(process.env));if(!e){const e=ora({hideCursor:!1,discardStdin:!1
4234
+ }).start("Installing usage specs"),n=await syncUsageSpecs(r,i,s);return n.success?(e.succeed("Installed usage specs"),SUCCESS):(t.error({err:n.error},"Failed to sync usage specs"),e.fail(n.error),FAILURE)}const o=ora({hideCursor:!1,discardStdin:!1}).start("Retrieving spec data"),a=e.split("@"),c=a[0];let u=a[1];const[l,d]=_nullishCoalesce$i(c,()=>"").split("/");if(!l||!d)return t.error({name:e},'The name argument must be in the format "workspace/tile" (or "workspace/tile@version")'),o.fail('The name argument must be in the format "workspace/tile" (or "workspace/tile@version")'),FAILURE;const p=await s.GET("/v1/tiles/{workspaceName}/{tileName}",{params:{path:{workspaceName:l,tileName:d}}});if(p.error)return t.error({name:e,err:p.error},"Failed to get tile"),o.fail(apiErrToString(p.error)),FAILURE;const h=p.data.data;if(!u){const e=h.attributes.latestVersion;if(!e)return t.error({fullName:c},"The tile does not have a latest version. Please specify a version"),
4235
+ o.fail("The tile does not have a latest version. Please specify a version"),FAILURE;u=e}const A=await s.GET("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:l,tileName:d,version:u}}});if(A.error)return t.error({fullName:c,version:u,err:A.error},"Failed to get tile version"),o.fail(apiErrToString(A.error)),FAILURE;const f=A.data.data;if(!f.attributes.describes)return t.error({name:e,version:u},"Invalid usage spec; does not describe a package"),o.fail("Invalid usage spec; does not describe a package"),FAILURE;o.text=`Installing ${h.attributes.fullName}@${u}`;const g=await updateTesslJsonDependencies(i,{add:[{workspaceName:l,tileName:d,newVersion:f.attributes.version}]});if(!g.success)return t.error({name:e,version:u,err:g.error},"Failed to update Tessl JSON dependencies"),o.fail(g.error),FAILURE;const m=await syncUsageSpecs(r,i,s);return m.success?(t.info({name:e,version:u},"Usage spec installed"),o.succeed(`Installed ${h.attributes.fullName}@${u}`),
4236
+ SUCCESS):(t.error({name:e,err:m.error},"Failed to sync usage specs"),o.fail(m.error),FAILURE)}}),registryPublishCommand=new Command$1({name:"registry-publish",summary:"Publish specs to the Tessl registry",allowArbitraryFlags:!1,positionals:[{name:"path",description:"The path to the spec files to publish"}],requiresLogin:!0,requiresConfig:!1,handler:async({projectDir:e,monitoring:{logger:t},positionals:{path:r}})=>{if(!r)throw new ExpectedError("A path to the spec files is required");const n=ora({hideCursor:!1,discardStdin:!1}).start("Publishing"),i=getTesslClient(t,validateBaseEnv(process.env));try{const s=(await readdir(join(e,r),{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>join(e.parentPath,e.name)),o=createGzip(),a=tar.pack();await Promise.all(s.map(async e=>{const t=await readFile$1(e),n=relative$1(r,e);a.entry({name:n},t)})),a.finalize();const c=a.pipe(o),u=await i.POST("/v1/tiles",{params:{header:{"content-type":"application/x-tar"}},bodySerializer:e=>e,
4237
+ duplex:"half",body:c});if(u.error)return t.error({err:u.error},"Failed to publish specs"),n.fail(apiErrToString(u.error)),FAILURE;const{fullName:l,version:d}=u.data.data.attributes;return n.succeed(`Spec published as ${l}@${d}`),SUCCESS}catch(e){return t.error({err:e},"Failed to publish specs"),n.fail(e instanceof Error?e.message:"Failed to publish specs"),FAILURE}}});var ansiEscapes$3={exports:{}},hasRequiredAnsiEscapes$1;function requireAnsiEscapes$1(){return hasRequiredAnsiEscapes$1||(hasRequiredAnsiEscapes$1=1,function(e){const t=e.exports;e.exports.default=t;const r="[",n="]",i="",s=";",o="Apple_Terminal"===process.env.TERM_PROGRAM;t.cursorTo=(e,t)=>{if("number"!=typeof e)throw new TypeError("The `x` argument is required");return"number"!=typeof t?r+(e+1)+"G":r+(t+1)+";"+(e+1)+"H"},t.cursorMove=(e,t)=>{if("number"!=typeof e)throw new TypeError("The `x` argument is required");let n="";return e<0?n+=r+-e+"D":e>0&&(n+=r+e+"C"),t<0?n+=r+-t+"A":t>0&&(n+=r+t+"B"),n},
4238
+ t.cursorUp=(e=1)=>r+e+"A",t.cursorDown=(e=1)=>r+e+"B",t.cursorForward=(e=1)=>r+e+"C",t.cursorBackward=(e=1)=>r+e+"D",t.cursorLeft="",t.cursorSavePosition=o?"7":"",t.cursorRestorePosition=o?"8":"",t.cursorGetPosition="",t.cursorNextLine="",t.cursorPrevLine="",t.cursorHide="[?25l",t.cursorShow="[?25h",t.eraseLines=e=>{let r="";for(let n=0;n<e;n++)r+=t.eraseLine+(n<e-1?t.cursorUp():"");return e&&(r+=t.cursorLeft),r},t.eraseEndLine="",t.eraseStartLine="",t.eraseLine="",t.eraseDown="",t.eraseUp="",t.eraseScreen="",t.scrollUp="",t.scrollDown="",t.clearScreen="c",t.clearTerminal="win32"===process.platform?`${t.eraseScreen}${r}0f`:`${t.eraseScreen}${r}3J${r}H`,t.beep=i,t.link=(e,t)=>[n,"8",s,s,t,i,e,n,"8",s,s,i].join(""),t.image=(e,t={})=>{let r=`${n}1337;File=inline=1`;return t.width&&(r+=`;width=${t.width}`),t.height&&(r+=`;height=${t.height}`),!1===t.preserveAspectRatio&&(r+=";preserveAspectRatio=0"),r+":"+e.toString("base64")+i},t.iTerm={
4239
+ setCwd:(e=process.cwd())=>`${n}50;CurrentDir=${e}${i}`,annotation:(e,t={})=>{let r=`${n}1337;`;const s=void 0!==t.x,o=void 0!==t.y;if((s||o)&&(!s||!o||void 0===t.length))throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");return e=e.replace(/\|/g,""),r+=t.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",t.length>0?r+=(s?[e,t.length,t.x,t.y]:[t.length,e]).join("|"):r+=e,r+i}}}(ansiEscapes$3)),ansiEscapes$3.exports}var ansiEscapesExports$1=requireAnsiEscapes$1(),ansiEscapes$2=getDefaultExportFromCjs(ansiEscapesExports$1);const checkboxTheme={icon:{checked:colors.green(figures$1.circleFilled),unchecked:figures$1.circle,cursor:figures$1.pointer},style:{disabledChoice:e=>colors.dim(`- ${e}`),renderSelectedChoices:e=>e.map(e=>e.short).join(", "),description:e=>colors.cyan(e)},helpMode:"auto"};function isSelectable$1(e){return!Separator.isSeparator(e)&&!e.disabled}function isChecked(e){return isSelectable$1(e)&&Boolean(e.checked)}function toggle(e){
4240
+ return isSelectable$1(e)?{...e,checked:!e.checked}:e}function check(e){return function(t){return isSelectable$1(t)?{...t,checked:e}:t}}function normalizeChoices$1(e){return e.map(e=>{if(Separator.isSeparator(e))return e;if("string"==typeof e)return{value:e,name:e,short:e,disabled:!1,checked:!1};const t=e.name??String(e.value),r={value:e.value,name:t,short:e.short??t,disabled:e.disabled??!1,checked:e.checked??!1};return e.description&&(r.description=e.description),r})}var checkbox=createPrompt((e,t)=>{const{instructions:r,pageSize:n=7,loop:i=!0,required:s,validate:o=()=>!0}=e,a={all:"a",invert:"i",...e.shortcuts},c=makeTheme(checkboxTheme,e.theme),u=useRef(!0),[l,d]=useState("idle"),p=usePrefix({status:l,theme:c}),[h,A]=useState(normalizeChoices$1(e.choices)),f=useMemo(()=>{const e=h.findIndex(isSelectable$1),t=h.findLastIndex(isSelectable$1);if(-1===e)throw new ValidationError$1("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}
4241
+ },[h]),[g,m]=useState(f.first),[y,E]=useState(!0),[b,C]=useState();useKeypress(async e=>{if(isEnterKey(e)){const e=h.filter(isChecked),r=await o([...e]);s&&!h.some(isChecked)?C("At least one choice must be selected"):!0===r?(d("done"),t(e.map(e=>e.value))):C(r||"You must select a valid value")}else if(isUpKey(e)||isDownKey(e)){if(i||isUpKey(e)&&g!==f.first||isDownKey(e)&&g!==f.last){const t=isUpKey(e)?-1:1;let r=g;do{r=(r+t+h.length)%h.length}while(!isSelectable$1(h[r]));m(r)}}else if(isSpaceKey(e))C(void 0),E(!1),A(h.map((e,t)=>t===g?toggle(e):e));else if(e.name===a.all){const e=h.some(e=>isSelectable$1(e)&&!e.checked);A(h.map(check(e)))}else if(e.name===a.invert)A(h.map(toggle));else if(isNumberKey(e)){const t=Number(e.name)-1;let r=-1;const n=h.findIndex(e=>!Separator.isSeparator(e)&&(r++,r===t)),i=h[n];i&&isSelectable$1(i)&&(m(n),A(h.map((e,t)=>t===n?toggle(e):e)))}});const I=c.style.message(e.message,l);let v;const w=usePagination({items:h,active:g,renderItem({item:e,isActive:t}){
4242
+ if(Separator.isSeparator(e))return` ${e.separator}`;if(e.disabled){const t="string"==typeof e.disabled?e.disabled:"(disabled)";return c.style.disabledChoice(`${e.name} ${t}`)}t&&(v=e.description);const r=e.checked?c.icon.checked:c.icon.unchecked;return(t?c.style.highlight:e=>e)(`${t?c.icon.cursor:" "}${r} ${e.name}`)},pageSize:n,loop:i});if("done"===l){const e=h.filter(isChecked);return`${p} ${I} ${c.style.answer(c.style.renderSelectedChoices(e,h))}`}let S="",_="";if("always"===c.helpMode||"auto"===c.helpMode&&y&&(void 0===r||r)){if("string"==typeof r)S=r;else{S=` (Press ${[`${c.style.key("space")} to select`,a.all?`${c.style.key(a.all)} to toggle all`:"",a.invert?`${c.style.key(a.invert)} to invert selection`:"",`and ${c.style.key("enter")} to proceed`].filter(e=>""!==e).join(", ")})`}h.length>n&&("always"===c.helpMode||"auto"===c.helpMode&&u.current)&&(_=`\n${c.style.help("(Use arrow keys to reveal more choices)")}`,u.current=!1)}const D=v?`\n${c.style.description(v)}`:"";let B=""
4243
+ ;return b&&(B=`\n${c.style.error(b)}`),`${p} ${I}${S}\n${w}${_}${D}${B}${ansiEscapes$2.cursorHide}`});function getBooleanValue(e,t){let r=!1!==t;return/^(y|yes)/i.test(e)?r=!0:/^(n|no)/i.test(e)&&(r=!1),r}function boolToString(e){return e?"Yes":"No"}var confirm=createPrompt((e,t)=>{const{transformer:r=boolToString}=e,[n,i]=useState("idle"),[s,o]=useState(""),a=makeTheme(e.theme),c=usePrefix({status:n,theme:a});useKeypress((n,a)=>{if(isEnterKey(n)){const n=getBooleanValue(s,e.default);o(r(n)),i("done"),t(n)}else if("tab"===n.name){const t=boolToString(!getBooleanValue(s,e.default));a.clearLine(0),a.write(t),o(t)}else o(a.line)});let u=s,l="";"done"===n?u=a.style.answer(s):l=` ${a.style.defaultAnswer(!1===e.default?"y/N":"Y/n")}`;return`${c} ${a.style.message(e.message,n)}${l} ${u}`}),ansiEscapes$1={exports:{}},hasRequiredAnsiEscapes;function requireAnsiEscapes(){return hasRequiredAnsiEscapes||(hasRequiredAnsiEscapes=1,function(e){const t=e.exports;e.exports.default=t
4244
4244
  ;const r="[",n="]",i="",s=";",o="Apple_Terminal"===process.env.TERM_PROGRAM;t.cursorTo=(e,t)=>{if("number"!=typeof e)throw new TypeError("The `x` argument is required");return"number"!=typeof t?r+(e+1)+"G":r+(t+1)+";"+(e+1)+"H"},t.cursorMove=(e,t)=>{if("number"!=typeof e)throw new TypeError("The `x` argument is required");let n="";return e<0?n+=r+-e+"D":e>0&&(n+=r+e+"C"),t<0?n+=r+-t+"A":t>0&&(n+=r+t+"B"),n},t.cursorUp=(e=1)=>r+e+"A",t.cursorDown=(e=1)=>r+e+"B",t.cursorForward=(e=1)=>r+e+"C",t.cursorBackward=(e=1)=>r+e+"D",t.cursorLeft="",t.cursorSavePosition=o?"7":"",t.cursorRestorePosition=o?"8":"",t.cursorGetPosition="",t.cursorNextLine="",t.cursorPrevLine="",t.cursorHide="[?25l",t.cursorShow="[?25h",t.eraseLines=e=>{let r="";for(let n=0;n<e;n++)r+=t.eraseLine+(n<e-1?t.cursorUp():"");return e&&(r+=t.cursorLeft),r},t.eraseEndLine="",t.eraseStartLine="",t.eraseLine="",t.eraseDown="",t.eraseUp="",t.eraseScreen="",t.scrollUp="",
4245
4245
  t.scrollDown="",t.clearScreen="c",t.clearTerminal="win32"===process.platform?`${t.eraseScreen}${r}0f`:`${t.eraseScreen}${r}3J${r}H`,t.beep=i,t.link=(e,t)=>[n,"8",s,s,t,i,e,n,"8",s,s,i].join(""),t.image=(e,t={})=>{let r=`${n}1337;File=inline=1`;return t.width&&(r+=`;width=${t.width}`),t.height&&(r+=`;height=${t.height}`),!1===t.preserveAspectRatio&&(r+=";preserveAspectRatio=0"),r+":"+e.toString("base64")+i},t.iTerm={setCwd:(e=process.cwd())=>`${n}50;CurrentDir=${e}${i}`,annotation:(e,t={})=>{let r=`${n}1337;`;const s=void 0!==t.x,o=void 0!==t.y;if((s||o)&&(!s||!o||void 0===t.length))throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");return e=e.replace(/\|/g,""),r+=t.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",t.length>0?r+=(s?[e,t.length,t.x,t.y]:[t.length,e]).join("|"):r+=e,r+i}}}(ansiEscapes$1)),ansiEscapes$1.exports}var ansiEscapesExports=requireAnsiEscapes(),ansiEscapes=getDefaultExportFromCjs(ansiEscapesExports);const selectTheme={icon:{
4246
4246
  cursor:figures$1.pointer},style:{disabled:e=>colors.dim(`- ${e}`),description:e=>colors.cyan(e)},helpMode:"auto",indexMode:"hidden"};function isSelectable(e){return!Separator.isSeparator(e)&&!e.disabled}function normalizeChoices(e){return e.map(e=>{if(Separator.isSeparator(e))return e;if("string"==typeof e)return{value:e,name:e,short:e,disabled:!1};const t=e.name??String(e.value),r={value:e.value,name:t,short:e.short??t,disabled:e.disabled??!1};return e.description&&(r.description=e.description),r})}var select=createPrompt((e,t)=>{const{loop:r=!0,pageSize:n=7}=e,i=useRef(!0),s=makeTheme(selectTheme,e.theme),[o,a]=useState("idle"),c=usePrefix({status:o,theme:s}),u=useRef(),l=useMemo(()=>normalizeChoices(e.choices),[e.choices]),d=useMemo(()=>{const e=l.findIndex(isSelectable),t=l.findLastIndex(isSelectable);if(-1===e)throw new ValidationError$1("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}
@@ -4250,35 +4250,35 @@ const r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf(
4250
4250
  ;return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in env)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in env)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in env)||"codeship"===env.CI_NAME?1:s;if("TEAMCITY_VERSION"in env)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION)?1:0;if("truecolor"===env.COLORTERM)return 3;if("xterm-kitty"===env.TERM)return 3;if("xterm-ghostty"===env.TERM)return 3;if("wezterm"===env.TERM)return 3;if("TERM_PROGRAM"in env){const e=Number.parseInt((env.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(env.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(env.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)||"COLORTERM"in env?1:s}function createSupportsColor(e,t={}){return translateLevel(_supportsColor(e,{streamIsTTY:e&&e.isTTY,...t}))}function hasFlag(e,t=process__default.argv){
4251
4251
  const r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return-1!==n&&(-1===i||n<i)}function parseVersion(e=""){if(/^\d{3,4}$/.test(e)){const t=/(\d{1,2})(\d{2})/.exec(e)??[];return{major:0,minor:Number.parseInt(t[1],10),patch:Number.parseInt(t[2],10)}}const t=(e??"").split(".").map(e=>Number.parseInt(e,10));return{major:t[0],minor:t[1],patch:t[2]}}function createSupportsHyperlinks(e){const{CI:t,CURSOR_TRACE_ID:r,FORCE_HYPERLINK:n,NETLIFY:i,TEAMCITY_VERSION:s,TERM_PROGRAM:o,TERM_PROGRAM_VERSION:a,VTE_VERSION:c,TERM:u}=process$5.env;if(n)return!(n.length>0&&0===Number.parseInt(n,10));if(hasFlag("no-hyperlink")||hasFlag("no-hyperlinks")||hasFlag("hyperlink=false")||hasFlag("hyperlink=never"))return!1;if(hasFlag("hyperlink=true")||hasFlag("hyperlink=always"))return!0;if(i)return!0;if(!createSupportsColor(e))return!1;if(e&&!e.isTTY)return!1;if("WT_SESSION"in process$5.env)return!0;if("win32"===process$5.platform)return!1;if(t)return!1;if(s)return!1;if(o){
4252
4252
  const e=parseVersion(a);switch(o){case"iTerm.app":return 3===e.major?e.minor>=1:e.major>3;case"WezTerm":return e.major>=20200620;case"vscode":return!!r||(e.major>1||1===e.major&&e.minor>=72);case"ghostty":return!0}}if(c){if("0.50.0"===c)return!1;const e=parseVersion(c);return e.major>0||e.minor>=50}return"alacritty"===u}hasFlag$1("no-color")||hasFlag$1("no-colors")||hasFlag$1("color=false")||hasFlag$1("color=never")?flagForceColor=0:(hasFlag$1("color")||hasFlag$1("colors")||hasFlag$1("color=true")||hasFlag$1("color=always"))&&(flagForceColor=1),createSupportsColor({isTTY:tty$2.isatty(1)}),createSupportsColor({isTTY:tty$2.isatty(2)});const supportsHyperlinks={stdout:createSupportsHyperlinks(process$5.stdout),stderr:createSupportsHyperlinks(process$5.stderr)};function terminalLink(e,t,{target:r="stdout",...n}={}){return supportsHyperlinks[r]?link$2(e,t):!1===n.fallback?e:"function"==typeof n.fallback?n.fallback(e,t):`${e} ${t}`}terminalLink.isSupported=supportsHyperlinks.stdout,
4253
- terminalLink.stderr=(e,t,r={})=>terminalLink(e,t,{target:"stderr",...r}),terminalLink.stderr.isSupported=supportsHyperlinks.stderr;const searchCommand=new Command$1({name:"registry-search",summary:"Search Tessl's Spec Registry for usage specs, by name, package-url, or package registry web url",positionals:[{name:"name",description:"A name, package-url, or package registry web url"}],allowArbitraryFlags:!0,requiresLogin:!1,handler:async({monitoring:{logger:e},args:t,projectDir:r,isInteractive:n})=>{if(!n)throw new ExpectedError('"search" does not support non-interactive mode');const i=ora({hideCursor:!1,discardStdin:!1}).start("Searching for specs"),s=[...t._].join(" ");if(!s)return e.error({},"A name, package-url, or package registry web url is required"),i.fail("A name, package-url, or package registry web url is required"),FAILURE;const o=getTesslClient(e,validateBaseEnv(process.env)),a=[];if(maybeName(s)){const[t,r]=await Promise.all([o.GET("/v1/tiles",{params:{query:{
4254
- "filter[name][like]":s,include:"versions","page[size]":10}}}),o.GET("/v1/tiles",{params:{query:{"filter[describes]":s,include:"versions","page[size]":10}}})]);if(t.error)return e.error({err:t.error},"Failed to search the knowledge base"),i.fail("Failed to search the knowledge base: "+apiErrToString(t.error)),FAILURE;if(r.error)return e.error({err:r.error},"Failed to search the knowledge base"),i.fail("Failed to search the knowledge base: "+apiErrToString(r.error)),FAILURE;const n=new Map;for(const e of t.data.data)n.set(e.id,e);for(const e of r.data.data)n.set(e.id,e);a.push(...Array.from(n.values()))}else{const t=await o.GET("/v1/tiles",{params:{query:{"filter[describes]":s,include:"versions","page[size]":10}}});if(t.error)return e.error({err:t.error},"Failed to search the knowledge base"),i.fail("Failed to search the knowledge base: "+apiErrToString(t.error)),FAILURE;a.push(...t.data.data)}if(0===a.length)return i.fail(`No usage specs found for ${chalk.cyan(s)}`),FAILURE;i.succeed()
4255
- ;const c=formatTileChoices(a);let u;try{u=await select({message:"Select a usage spec to add",choices:c,pageSize:20,loop:!1})}catch(t){return t instanceof ExitPromptError?(i.stop(),SUCCESS):(e.error({err:t},"Unexpected error selecting a usage spec to add"),i.fail("Unexpected error selecting a usage spec to add"),FAILURE)}const{workspaceName:l,tileName:d,version:p}=u;i.start(`Downloading usage spec: ${l}/${d}@${p}`);const h=await o.GET("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:l,tileName:d,version:p}}});if(h.error)return e.error({err:h.error,workspaceName:l,tileName:d,version:p},"Failed to download usage spec"),i.fail(apiErrToString(h.error)),FAILURE;const A=h.data.data,f=openFsd(r);if(!A.attributes.describes)return e.error({workspaceName:l,tileName:d,version:p},"Invalid usage spec; does not describe a package"),i.fail("Invalid usage spec; does not describe a package"),FAILURE;const g=await updateTesslJsonDependencies(f,{add:[{workspaceName:l,
4256
- tileName:d,newVersion:p}]});if(!g.success)return e.error({workspaceName:l,tileName:d,version:p},"Failed to update knowledge index dependencies"),i.fail(g.error),FAILURE;const m=await syncUsageSpecs(r,f,o);return m.success?(i.succeed(`Installed ${l}/${d}@${p}`),SUCCESS):(e.error({workspaceName:l,tileName:d,version:p},"Failed to sync usage specs"),i.fail(m.error),FAILURE)}});function maybeName(e){const t=e.trim();return!t.startsWith("http:")&&!t.startsWith("https:")&&!t.startsWith("pkg:")}function formatTileChoices(e){const t=[];return e.forEach(e=>{const r=e.attributes.fullName,n=e.attributes.describes;if(!n)return;const{name:i,link:s}=purlToNameAndLink(n),[o,a]=r.split("/");t.push(new Separator(`${r} (describes ${s?terminalLink(i,s):i})`)),e.attributes.versions.forEach(({version:e})=>{t.push({name:e,value:{workspaceName:o,tileName:a,version:e}})})}),t}const syncCommand=new Command$1({name:"registry-sync",
4257
- summary:"Check for newer versions of usage specs and install them into your project",allowArbitraryFlags:!1,requiresLogin:!1,handler:async({monitoring:{logger:e},projectDir:t,isInteractive:r})=>{if(!r)throw new ExpectedError('"sync" does not support non-interactive mode');const n=ora({hideCursor:!1,discardStdin:!1}).start("Checking for usage spec upgrades"),i=openFsd(t),s=getTesslClient(e,validateBaseEnv(process.env)),o=await readTesslJson(i);if(!o.success)throw new ExpectedError(o.error);const a=o.data,{majorUpdates:c,minorUpdates:u,patchUpdates:l,updateCheckFailures:d}=await getSpecUpdates(a,s);if(d.length>0){const t=d.map(e=>e.tileName&&e.tileVersion?`- ${e.tileName}@${e.tileVersion}: ${e.error}`:`- ${e.error}`).join("\n");return e.error({updateCheckFailures:d},"Received errors while checking for updates"),n.fail(`Received ${d.length} errors while checking for updates:\n${t}`),FAILURE}const p=[];if(l.length>0&&(p.push(new Separator("Patch updates")),
4258
- p.push(...formatUpdateChoice(l))),u.length>0&&(p.push(new Separator("Minor updates")),p.push(...formatUpdateChoice(u))),c.length>0&&(p.push(new Separator("Major updates")),p.push(...formatUpdateChoice(c))),0===p.length)return n.succeed("No updates found"),SUCCESS;n.stop();let h=[];try{h=await checkbox({message:"Select the updates you want to apply",choices:p})}catch(t){return t instanceof ExitPromptError?(n.stop(),SUCCESS):(e.error({err:t},"Unexpected error selecting updates to apply"),n.fail("Unexpected error selecting updates to apply"),FAILURE)}if(n.start("Applying updates"),0===h.length)return e.info({},"No updates selected"),n.warn("No updates selected"),SUCCESS;const A=await updateTesslJsonDependencies(i,{add:h});if(!A.success)return e.error({err:A.error},"Failed to update Tessl JSON dependencies"),n.fail(A.error),FAILURE;const f=await syncUsageSpecs(t,i,s);return f.success?(n.succeed(`Updated ${h.length} usage ${1===h.length?"spec":"specs"}`),SUCCESS):(e.error({err:f.error
4259
- },"Failed to sync usage specs"),n.fail(f.error),FAILURE)}});function formatUpdateChoice(e){return e.map(e=>({name:`${e.tileName.padEnd(35)} ${e.tileVersion} > ${e.newVersion}`,value:{workspaceName:e.workspaceName,tileName:e.tileName,newVersion:e.newVersion,docPath:e.docPath}}))}const registryUnpublishCommand=new Command$1({name:"registry-unpublish",summary:"Unpublish specs in the Tessl registry",allowArbitraryFlags:!1,positionals:[{name:"spec",description:'The spec to unpublish, in the format "workspace/spec@version"'}],requiresLogin:!0,requiresConfig:!1,handler:async({monitoring:{logger:e},positionals:{spec:t}})=>{if(!t)throw new ExpectedError("A spec must be provided as the first argument");const[r,n]=t.split("@");if(!r||!n)throw new ExpectedError('The spec must be in the format "workspace/spec@version"');const[i,s]=r.split("/");if(!i||!s)throw new ExpectedError('The spec must be in the format "workspace/tile"')
4260
- ;const o=createSpinner("Unpublishing"),a=getTesslClient(e,validateBaseEnv(process.env)),c=await a.DELETE("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:i,tileName:s,version:n}}});return c.error?(e.error({err:c.error},"Failed to unpublish spec"),o.fail(apiErrToString(c.error)),FAILURE):(o.succeed(`Unpublished ${i}/${s}@${n}`),SUCCESS)}}),safeNormalizeFileUrl=(e,t)=>{const r=normalizeFileUrl(normalizeDenoExecPath(e));if("string"!=typeof r)throw new TypeError(`${t} must be a string or a file URL: ${r}.`);return r},normalizeDenoExecPath=e=>isDenoExecPath(e)?e.toString():e,isDenoExecPath=e=>"string"!=typeof e&&e&&Object.getPrototypeOf(e)===String.prototype,normalizeFileUrl=e=>e instanceof URL?fileURLToPath$1(e):e,normalizeParameters=(e,t=[],r={})=>{const n=safeNormalizeFileUrl(e,"First argument"),[i,s]=isPlainObject$2(t)?[[],t]:[t,r]
4261
- ;if(!Array.isArray(i))throw new TypeError(`Second argument must be either an array of arguments or an options object: ${i}`);if(i.some(e=>"object"==typeof e&&null!==e))throw new TypeError(`Second argument must be an array of strings: ${i}`);const o=i.map(String),a=o.find(e=>e.includes("\0"));if(void 0!==a)throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${a}`);if(!isPlainObject$2(s))throw new TypeError(`Last argument must be an options object: ${s}`);return[n,o,s]},{toString:objectToString$1}=Object.prototype,isArrayBuffer=e=>"[object ArrayBuffer]"===objectToString$1.call(e),isUint8Array=e=>"[object Uint8Array]"===objectToString$1.call(e),bufferToUint8Array=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),textEncoder$1=new TextEncoder,stringToUint8Array=e=>textEncoder$1.encode(e),textDecoder=new TextDecoder,uint8ArrayToString=e=>textDecoder.decode(e),joinToString=(e,t)=>uint8ArraysToStrings(e,t).join(""),uint8ArraysToStrings=(e,t)=>{
4262
- if("utf8"===t&&e.every(e=>"string"==typeof e))return e;const r=new StringDecoder(t),n=e.map(e=>"string"==typeof e?stringToUint8Array(e):e).map(e=>r.write(e)),i=r.end();return""===i?n:[...n,i]},joinToUint8Array=e=>1===e.length&&isUint8Array(e[0])?e[0]:concatUint8Arrays(stringsToUint8Arrays(e)),stringsToUint8Arrays=e=>e.map(e=>"string"==typeof e?stringToUint8Array(e):e),concatUint8Arrays=e=>{const t=new Uint8Array(getJoinLength(e));let r=0;for(const n of e)t.set(n,r),r+=n.length;return t},getJoinLength=e=>{let t=0;for(const r of e)t+=r.length;return t},isTemplateString=e=>Array.isArray(e)&&Array.isArray(e.raw),parseTemplates=(e,t)=>{let r=[];for(const[n,i]of e.entries())r=parseTemplate({templates:e,expressions:t,tokens:r,index:n,template:i});if(0===r.length)throw new TypeError("Template script must not be empty");const[n,...i]=r;return[n,i,{}]},parseTemplate=({templates:e,expressions:t,tokens:r,index:n,template:i})=>{
4263
- if(void 0===i)throw new TypeError(`Invalid backslash sequence: ${e.raw[n]}`);const{nextTokens:s,leadingWhitespaces:o,trailingWhitespaces:a}=splitByWhitespaces(i,e.raw[n]),c=concatTokens(r,s,o);if(n===t.length)return c;const u=t[n],l=Array.isArray(u)?u.map(e=>parseExpression(e)):[parseExpression(u)];return concatTokens(c,l,a)},splitByWhitespaces=(e,t)=>{if(0===t.length)return{nextTokens:[],leadingWhitespaces:!1,trailingWhitespaces:!1};const r=[];let n=0;const i=DELIMITERS.has(t[0]);for(let i=0,s=0;i<e.length;i+=1,s+=1){const o=t[s];if(DELIMITERS.has(o))n!==i&&r.push(e.slice(n,i)),n=i+1;else if("\\"===o){const e=t[s+1];"\n"===e?(i-=1,s+=1):"u"===e&&"{"===t[s+2]?s=t.indexOf("}",s+3):s+=ESCAPE_LENGTH[e]??1}}const s=n===e.length;return s||r.push(e.slice(n)),{nextTokens:r,leadingWhitespaces:i,trailingWhitespaces:s}},DELIMITERS=new Set([" ","\t","\r","\n"]),ESCAPE_LENGTH={x:3,u:5
4264
- },concatTokens=(e,t,r)=>r||0===e.length||0===t.length?[...e,...t]:[...e.slice(0,-1),`${e.at(-1)}${t[0]}`,...t.slice(1)],parseExpression=e=>{const t=typeof e;if("string"===t)return e;if("number"===t)return String(e);if(isPlainObject$2(e)&&("stdout"in e||"isMaxBuffer"in e))return getSubprocessResult(e);if(e instanceof ChildProcess||"[object Promise]"===Object.prototype.toString.call(e))throw new TypeError("Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.");throw new TypeError(`Unexpected "${t}" in template expression`)},getSubprocessResult=({stdout:e})=>{if("string"==typeof e)return e;if(isUint8Array(e))return uint8ArrayToString(e);if(void 0===e)throw new TypeError('Missing result.stdout in template expression. This is probably due to the previous subprocess\' "stdout" option.');throw new TypeError(`Unexpected "${typeof e}" stdout in template expression`)
4265
- },isStandardStream=e=>STANDARD_STREAMS.includes(e),STANDARD_STREAMS=[process$5.stdin,process$5.stdout,process$5.stderr],STANDARD_STREAMS_ALIASES=["stdin","stdout","stderr"],getStreamName=e=>STANDARD_STREAMS_ALIASES[e]??`stdio[${e}]`,normalizeFdSpecificOptions=e=>{const t={...e};for(const r of FD_SPECIFIC_OPTIONS)t[r]=normalizeFdSpecificOption(e,r);return t},normalizeFdSpecificOption=(e,t)=>{const r=Array.from({length:getStdioLength(e)+1}),n=normalizeFdSpecificValue(e[t],r,t);return addDefaultValue$1(n,t)},getStdioLength=({stdio:e})=>Array.isArray(e)?Math.max(e.length,STANDARD_STREAMS_ALIASES.length):STANDARD_STREAMS_ALIASES.length,normalizeFdSpecificValue=(e,t,r)=>isPlainObject$2(e)?normalizeOptionObject(e,t,r):t.fill(e),normalizeOptionObject=(e,t,r)=>{for(const n of Object.keys(e).sort(compareFdName))for(const i of parseFdName(n,r,t))t[i]=e[n];return t
4266
- },compareFdName=(e,t)=>getFdNameOrder(e)<getFdNameOrder(t)?1:-1,getFdNameOrder=e=>"stdout"===e||"stderr"===e?0:"all"===e?2:1,parseFdName=(e,t,r)=>{if("ipc"===e)return[r.length-1];const n=parseFd(e);if(void 0===n||0===n)throw new TypeError(`"${t}.${e}" is invalid.\nIt must be "${t}.stdout", "${t}.stderr", "${t}.all", "${t}.ipc", or "${t}.fd3", "${t}.fd4" (and so on).`);if(n>=r.length)throw new TypeError(`"${t}.${e}" is invalid: that file descriptor does not exist.\nPlease set the "stdio" option to ensure that file descriptor exists.`);return"all"===n?[1,2]:[n]},parseFd=e=>{if("all"===e)return e;if(STANDARD_STREAMS_ALIASES.includes(e))return STANDARD_STREAMS_ALIASES.indexOf(e);const t=FD_REGEXP.exec(e);return null!==t?Number(t[1]):void 0},FD_REGEXP=/^fd(\d+)$/,addDefaultValue$1=(e,t)=>e.map(e=>void 0===e?DEFAULT_OPTIONS[t]:e),verboseDefault=debuglog("execa").enabled?"full":"none",DEFAULT_OPTIONS={lines:!1,buffer:!0,maxBuffer:1e8,verbose:verboseDefault,stripFinalNewline:!0
4267
- },FD_SPECIFIC_OPTIONS=["lines","buffer","maxBuffer","verbose","stripFinalNewline"],getFdSpecificValue=(e,t)=>"ipc"===t?e.at(-1):e[t],isVerbose=({verbose:e},t)=>"none"!==getFdVerbose(e,t),isFullVerbose=({verbose:e},t)=>!["none","short"].includes(getFdVerbose(e,t)),getVerboseFunction=({verbose:e},t)=>{const r=getFdVerbose(e,t);return isVerboseFunction(r)?r:void 0},getFdVerbose=(e,t)=>void 0===t?getFdGenericVerbose(e):getFdSpecificValue(e,t),getFdGenericVerbose=e=>e.find(e=>isVerboseFunction(e))??VERBOSE_VALUES.findLast(t=>e.includes(t)),isVerboseFunction=e=>"function"==typeof e,VERBOSE_VALUES=["none","short","full"],joinCommand=(e,t)=>{const r=[e,...t];return{command:r.join(" "),escapedCommand:r.map(e=>quoteString(escapeControlCharacters(e))).join(" ")}},escapeLines=e=>stripVTControlCharacters(e).split("\n").map(e=>escapeControlCharacters(e)).join("\n"),escapeControlCharacters=e=>e.replaceAll(SPECIAL_CHAR_REGEXP,e=>escapeControlCharacter(e)),escapeControlCharacter=e=>{
4268
- const t=COMMON_ESCAPES[e];if(void 0!==t)return t;const r=e.codePointAt(0),n=r.toString(16);return r<=ASTRAL_START?`\\u${n.padStart(4,"0")}`:`\\U${n}`},getSpecialCharRegExp=()=>{try{return new RegExp("\\p{Separator}|\\p{Other}","gu")}catch{return/[\s\u0000-\u001F\u007F-\u009F\u00AD]/g}},SPECIAL_CHAR_REGEXP=getSpecialCharRegExp(),COMMON_ESCAPES={" ":" ","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"},ASTRAL_START=65535,quoteString=e=>NO_ESCAPE_REGEXP.test(e)?e:"win32"===platform$2?`"${e.replaceAll('"','""')}"`:`'${e.replaceAll("'","'\\''")}'`,NO_ESCAPE_REGEXP=/^[\w./-]+$/,defaultVerboseFunction=({type:e,message:t,timestamp:r,piped:n,commandId:i,result:{failed:s=!1}={},options:{reject:o=!0}})=>{const a=serializeTimestamp(r),c=ICONS[e]({failed:s,reject:o,piped:n}),u=COLORS[e]({reject:o});return`${gray(`[${a}]`)} ${gray(`[${i}]`)} ${u(c)} ${u(t)}`
4269
- },serializeTimestamp=e=>`${padField(e.getHours(),2)}:${padField(e.getMinutes(),2)}:${padField(e.getSeconds(),2)}.${padField(e.getMilliseconds(),3)}`,padField=(e,t)=>String(e).padStart(t,"0"),getFinalIcon=({failed:e,reject:t})=>e?t?figures.cross:figures.warning:figures.tick,ICONS={command:({piped:e})=>e?"|":"$",output:()=>" ",ipc:()=>"*",error:getFinalIcon,duration:getFinalIcon},identity$1=e=>e,COLORS={command:()=>bold,output:()=>identity$1,ipc:()=>identity$1,error:({reject:e})=>e?redBright:yellowBright,duration:()=>gray},applyVerboseOnLines=(e,t,r)=>{const n=getVerboseFunction(t,r);return e.map(({verboseLine:e,verboseObject:t})=>applyVerboseFunction(e,t,n)).filter(e=>void 0!==e).map(e=>appendNewline(e)).join("")},applyVerboseFunction=(e,t,r)=>{if(void 0===r)return e;const n=r(e,t);return"string"==typeof n?n:void 0},appendNewline=e=>e.endsWith("\n")?e:`${e}\n`,verboseLog=({type:e,verboseMessage:t,fdNumber:r,verboseInfo:n,result:i})=>{const s=getVerboseObject({type:e,result:i,
4270
- verboseInfo:n}),o=getPrintedLines(t,s),a=applyVerboseOnLines(o,n,r);""!==a&&console.warn(a.slice(0,-1))},getVerboseObject=({type:e,result:t,verboseInfo:{escapedCommand:r,commandId:n,rawOptions:{piped:i=!1,...s}}})=>({type:e,escapedCommand:r,commandId:`${n}`,timestamp:new Date,piped:i,result:t,options:s}),getPrintedLines=(e,t)=>e.split("\n").map(e=>getPrintedLine({...t,message:e})),getPrintedLine=e=>({verboseLine:defaultVerboseFunction(e),verboseObject:e}),serializeVerboseMessage=e=>{const t="string"==typeof e?e:inspect$1(e);return escapeLines(t).replaceAll("\t"," ".repeat(TAB_SIZE))},TAB_SIZE=2,logCommand=(e,t)=>{isVerbose(t)&&verboseLog({type:"command",verboseMessage:e,verboseInfo:t})},getVerboseInfo=(e,t,r)=>{validateVerbose(e);return{verbose:e,escapedCommand:t,commandId:getCommandId(e),rawOptions:r}},getCommandId=e=>isVerbose({verbose:e})?COMMAND_ID++:void 0;let COMMAND_ID=0n;const validateVerbose=e=>{for(const t of e){
4271
- if(!1===t)throw new TypeError('The "verbose: false" option was renamed to "verbose: \'none\'".');if(!0===t)throw new TypeError('The "verbose: true" option was renamed to "verbose: \'short\'".');if(!VERBOSE_VALUES.includes(t)&&!isVerboseFunction(t)){const e=VERBOSE_VALUES.map(e=>`'${e}'`).join(", ");throw new TypeError(`The "verbose" option must not be ${t}. Allowed values are: ${e} or a function.`)}}},getStartTime=()=>hrtime.bigint(),getDurationMs=e=>Number(hrtime.bigint()-e)/1e6,handleCommand=(e,t,r)=>{const n=getStartTime(),{command:i,escapedCommand:s}=joinCommand(e,t),o=normalizeFdSpecificOption(r,"verbose"),a=getVerboseInfo(o,s,{...r});return logCommand(s,a),{command:i,escapedCommand:s,startTime:n,verboseInfo:a}};var crossSpawn$1={exports:{}},windows,hasRequiredWindows,mode,hasRequiredMode,isexe_1,hasRequiredIsexe,which_1,hasRequiredWhich;function requireWindows(){if(hasRequiredWindows)return windows;hasRequiredWindows=1,windows=r,r.sync=function(r,n){return t(e.statSync(r),r,n)}
4272
- ;var e=fs$4;function t(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var i=r[n].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}(t,r)}function r(r,n,i){e.stat(r,function(e,s){i(e,!e&&t(s,r,n))})}return windows}function requireMode(){if(hasRequiredMode)return mode;hasRequiredMode=1,mode=t,t.sync=function(t,n){return r(e.statSync(t),n)};var e=fs$4;function t(t,n,i){e.stat(t,function(e,t){i(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,i=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),o=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),u=parseInt("001",8),l=a|c,d=r&u||r&c&&i===o||r&a&&n===s||r&l&&0===s;return d}(e,t)}return mode}function requireIsexe(){if(hasRequiredIsexe)return isexe_1;var e
4273
- ;function t(r,n,i){if("function"==typeof n&&(i=n,n={}),!i){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,i){t(r,n||{},function(t,r){t?i(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),i(e,t)})}return hasRequiredIsexe=1,e="win32"===process.platform||commonjsGlobal.TESTING_WINDOWS?requireWindows():requireMode(),isexe_1=t,t.sync=function(t,r){try{return e.sync(t,r||{})}catch(e){if(r&&r.ignoreErrors||"EACCES"===e.code)return!1;throw e}},isexe_1}function requireWhich(){if(hasRequiredWhich)return which_1;hasRequiredWhich=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=path__default,r=e?";":":",n=requireIsexe(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),s=(t,n)=>{
4274
- const i=n.colon||r,s=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(n.path||process.env.PATH||"").split(i)],o=e?n.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?o.split(i):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:o}},o=(e,r,o)=>{"function"==typeof r&&(o=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:u}=s(e,r),l=[],d=n=>new Promise((s,o)=>{if(n===a.length)return r.all&&l.length?s(l):o(i(e));const c=a[n],u=/^".*"$/.test(c)?c.slice(1,-1):c,d=t.join(u,e),h=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;s(p(h,n,0))}),p=(e,t,i)=>new Promise((s,o)=>{if(i===c.length)return s(d(t+1));const a=c[i];n(e+a,{pathExt:u},(n,o)=>{if(!n&&o){if(!r.all)return s(e+a);l.push(e+a)}return s(p(e,t,i+1))})});return o?d(0).then(e=>o(null,e),o):d(0)};return which_1=o,o.sync=(e,r)=>{r=r||{};const{pathEnv:o,pathExt:a,pathExtExe:c}=s(e,r),u=[];for(let i=0;i<o.length;i++){
4275
- const s=o[i],l=/^".*"$/.test(s)?s.slice(1,-1):s,d=t.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<a.length;e++){const t=p+a[e];try{if(n.sync(t,{pathExt:c})){if(!r.all)return t;u.push(t)}}catch(e){}}}if(r.all&&u.length)return u;if(r.nothrow)return null;throw i(e)},which_1}var pathKey$1={exports:{}},hasRequiredPathKey,resolveCommand_1,hasRequiredResolveCommand;function requirePathKey(){if(hasRequiredPathKey)return pathKey$1.exports;hasRequiredPathKey=1;const e=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};return pathKey$1.exports=e,pathKey$1.exports.default=e,pathKey$1.exports}function requireResolveCommand(){if(hasRequiredResolveCommand)return resolveCommand_1;hasRequiredResolveCommand=1;const e=path__default,t=requireWhich(),r=requirePathKey();function n(n,i){
4276
- const s=n.options.env||process.env,o=process.cwd(),a=null!=n.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(n.options.cwd)}catch(e){}let u;try{u=t.sync(n.command,{path:s[r({env:s})],pathExt:i?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(o)}return u&&(u=e.resolve(a?n.options.cwd:"",u)),u}return resolveCommand_1=function(e){return n(e)||n(e,!0)}}var _escape={},hasRequired_escape,shebangRegex,hasRequiredShebangRegex,shebangCommand,hasRequiredShebangCommand,readShebang_1,hasRequiredReadShebang,parse_1,hasRequiredParse,enoent,hasRequiredEnoent,hasRequiredCrossSpawn;function require_escape(){if(hasRequired_escape)return _escape;hasRequired_escape=1;const e=/([()\][%!^"`<>&|;, *?])/g;return _escape.command=function(t){return t=t.replace(e,"^$1")},_escape.argument=function(t,r){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),r&&(t=t.replace(e,"^$1")),t},_escape}
4277
- function requireShebangRegex(){return hasRequiredShebangRegex?shebangRegex:(hasRequiredShebangRegex=1,shebangRegex=/^#!(.*)/)}function requireShebangCommand(){if(hasRequiredShebangCommand)return shebangCommand;hasRequiredShebangCommand=1;const e=requireShebangRegex();return shebangCommand=(t="")=>{const r=t.match(e);if(!r)return null;const[n,i]=r[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return"env"===s?i:i?`${s} ${i}`:s},shebangCommand}function requireReadShebang(){if(hasRequiredReadShebang)return readShebang_1;hasRequiredReadShebang=1;const e=fs$4,t=requireShebangCommand();return readShebang_1=function(r){const n=Buffer.alloc(150);let i;try{i=e.openSync(r,"r"),e.readSync(i,n,0,150,0),e.closeSync(i)}catch(e){}return t(n.toString())},readShebang_1}function requireParse(){if(hasRequiredParse)return parse_1;hasRequiredParse=1
4278
- ;const e=path__default,t=requireResolveCommand(),r=require_escape(),n=requireReadShebang(),i="win32"===process.platform,s=/\.(?:com|exe)$/i,o=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function a(a){if(!i)return a;const c=function(e){e.file=t(e);const r=e.file&&n(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(a),u=!s.test(c);if(a.options.forceShell||u){const t=o.test(c);a.command=e.normalize(a.command),a.command=r.command(a.command),a.args=a.args.map(e=>r.argument(e,t));const n=[a.command].concat(a.args).join(" ");a.args=["/d","/s","/c",`"${n}"`],a.command=process.env.comspec||"cmd.exe",a.options.windowsVerbatimArguments=!0}return a}return parse_1=function(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null);const n={command:e,args:t=t?t.slice(0):[],options:r=Object.assign({},r),file:void 0,original:{command:e,args:t}};return r.shell?n:a(n)},parse_1}function requireEnoent(){if(hasRequiredEnoent)return enoent;hasRequiredEnoent=1;const e="win32"===process.platform
4279
- ;function t(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function r(r,n){return e&&1===r&&!n.file?t(n.original,"spawn"):null}return enoent={hookChildProcess:function(t,n){if(!e)return;const i=t.emit;t.emit=function(e,s){if("exit"===e){const e=r(s,n);if(e)return i.call(t,"error",e)}return i.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},enoent}function requireCrossSpawn(){if(hasRequiredCrossSpawn)return crossSpawn$1.exports;hasRequiredCrossSpawn=1;const e=require$$0__default$2,t=requireParse(),r=requireEnoent();function n(n,i,s){const o=t(n,i,s),a=e.spawn(o.command,o.args,o.options);return r.hookChildProcess(a,o),a}return crossSpawn$1.exports=n,crossSpawn$1.exports.spawn=n,crossSpawn$1.exports.sync=function(n,i,s){const o=t(n,i,s),a=e.spawnSync(o.command,o.args,o.options)
4280
- ;return a.error=a.error||r.verifyENOENTSync(a.status,o),a},crossSpawn$1.exports._parse=t,crossSpawn$1.exports._enoent=r,crossSpawn$1.exports}var crossSpawnExports=requireCrossSpawn(),crossSpawn=getDefaultExportFromCjs(crossSpawnExports);function pathKey(e={}){const{env:t=process.env,platform:r=process.platform}=e;return"win32"!==r?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}function toPath(e){return e instanceof URL?fileURLToPath$1(e):e}function traversePathUp(e){return{*[Symbol.iterator](){let t,r=path__default$1.resolve(toPath(e));for(;t!==r;)yield r,t=r,r=path__default$1.resolve(r,"..")}}}promisify(execFile);const npmRunPath=({cwd:e=process$5.cwd(),path:t=process$5.env[pathKey()],preferLocal:r=!0,execPath:n=process$5.execPath,addExecPath:i=!0}={})=>{const s=path__default$1.resolve(toPath(e)),o=[],a=t.split(path__default$1.delimiter);return r&&applyPreferLocal(o,a,s),i&&applyExecPath(o,a,n,s),
4281
- ""===t||t===path__default$1.delimiter?`${o.join(path__default$1.delimiter)}${t}`:[...o,t].join(path__default$1.delimiter)},applyPreferLocal=(e,t,r)=>{for(const n of traversePathUp(r)){const r=path__default$1.join(n,"node_modules/.bin");t.includes(r)||e.push(r)}},applyExecPath=(e,t,r,n)=>{const i=path__default$1.resolve(n,toPath(r),"..");t.includes(i)||e.push(i)},npmRunPathEnv=({env:e=process$5.env,...t}={})=>{const r=pathKey({env:e={...e}});return t.path=e[r],e[r]=npmRunPath(t),e},getFinalError=(e,t,r)=>new(r?ExecaSyncError:ExecaError)(t,e instanceof DiscardedError?{}:{cause:e});class DiscardedError extends Error{}const setErrorName=(e,t)=>{Object.defineProperty(e.prototype,"name",{value:t,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,execaErrorSymbol,{value:!0,writable:!1,enumerable:!1,configurable:!1})
4253
+ terminalLink.stderr=(e,t,r={})=>terminalLink(e,t,{target:"stderr",...r}),terminalLink.stderr.isSupported=supportsHyperlinks.stderr;const searchCommand=new Command$1({name:"registry-search",summary:"Search Tessl's Spec Registry for usage specs, by name, package-url, or package registry web url",positionals:[{name:"name",description:"A name, package-url, or package registry web url"}],allowArbitraryFlags:!0,requiresLogin:!1,handler:async({monitoring:{logger:e,analytics:t},args:r,projectDir:n,isInteractive:i})=>{if(!i)throw new ExpectedError('"search" does not support non-interactive mode');const s=ora({hideCursor:!1,discardStdin:!1}).start("Searching for specs"),o=[...r._].join(" ");if(!o)return e.error({},"A name, package-url, or package registry web url is required"),s.fail("A name, package-url, or package registry web url is required"),FAILURE;const a=getTesslClient(e,validateBaseEnv(process.env)),c=[];if(maybeName(o)){const[t,r]=await Promise.all([a.GET("/v1/tiles",{params:{query:{
4254
+ "filter[name][like]":o,include:"versions","page[size]":10}}}),a.GET("/v1/tiles",{params:{query:{"filter[describes]":o,include:"versions","page[size]":10}}})]);if(t.error)return e.error({err:t.error},"Failed to search the knowledge base"),s.fail("Failed to search the knowledge base: "+apiErrToString(t.error)),FAILURE;if(r.error)return e.error({err:r.error},"Failed to search the knowledge base"),s.fail("Failed to search the knowledge base: "+apiErrToString(r.error)),FAILURE;const n=new Map;for(const e of t.data.data)n.set(e.id,e);for(const e of r.data.data)n.set(e.id,e);c.push(...Array.from(n.values()))}else{const t=await a.GET("/v1/tiles",{params:{query:{"filter[describes]":o,include:"versions","page[size]":10}}});if(t.error)return e.error({err:t.error},"Failed to search the knowledge base"),s.fail("Failed to search the knowledge base: "+apiErrToString(t.error)),FAILURE;c.push(...t.data.data)}if(0===c.length)return s.fail(`No usage specs found for ${chalk.cyan(o)}`),FAILURE;s.stop()
4255
+ ;const u=formatTileChoices(c),l=u.filter(e=>"value"in e).map(e=>e.value);let d;try{const e=await selectWithExit("Select a usage spec to add (Press Esc to exit)",u);if(e.exit)return t.specsSearch({searchTerm:o,choices:l}),SUCCESS;d=e.choice}catch(t){return e.error({err:t},"Unexpected error selecting a usage spec to add"),s.fail("Unexpected error selecting a usage spec to add"),FAILURE}t.specsSearch({searchTerm:o,choices:l,chosen:d});const{workspaceName:p,tileName:h,version:A}=d;s.start(`Downloading usage spec: ${p}/${h}@${A}`);const f=await a.GET("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:p,tileName:h,version:A}}});if(f.error)return e.error({err:f.error,workspaceName:p,tileName:h,version:A},"Failed to download usage spec"),s.fail(apiErrToString(f.error)),FAILURE;const g=f.data.data,m=openFsd(n);if(!g.attributes.describes)return e.error({workspaceName:p,tileName:h,version:A},"Invalid usage spec; does not describe a package"),
4256
+ s.fail("Invalid usage spec; does not describe a package"),FAILURE;const y=await updateTesslJsonDependencies(m,{add:[{workspaceName:p,tileName:h,newVersion:A}]});if(!y.success)return e.error({workspaceName:p,tileName:h,version:A},"Failed to update knowledge index dependencies"),s.fail(y.error),FAILURE;const E=await syncUsageSpecs(n,m,a);return E.success?(s.succeed(`Installed ${p}/${h}@${A}`),SUCCESS):(e.error({workspaceName:p,tileName:h,version:A},"Failed to sync usage specs"),s.fail(E.error),FAILURE)}});async function selectWithExit(e,t){const r=new AbortController,{signal:n}=r;process.stdin.listenerCount("keypress")||readline$4.emitKeypressEvents(process.stdin);const i=(e,t)=>{"object"==typeof t&&null!==t&&"name"in t&&"escape"===t.name&&r.abort()};process.stdin.on("keypress",i);const s=process.stdin.isTTY&&!process.stdin.isRaw;try{s&&process.stdin.setRawMode(!0);return{exit:!1,choice:await select({message:e,choices:t,pageSize:20,loop:!1},{signal:n})}}catch(e){
4257
+ if(e instanceof ExitPromptError||e instanceof Error&&"AbortPromptError"===e.name)return{exit:!0};throw e}finally{s&&process.stdin.setRawMode(!1),process.stdin.off("keypress",i)}}function maybeName(e){const t=e.trim();return!t.startsWith("http:")&&!t.startsWith("https:")&&!t.startsWith("pkg:")}function formatTileChoices(e){const t=[];return e.forEach(e=>{const r=e.attributes.fullName,n=e.attributes.describes;if(!n||!n.startsWith("pkg:"))return;const[i,s]=r.split("/"),o=new URL(`registry/${i}/${s}`,"https://tessl.io").toString(),a=terminalLink(r,o,{fallback:()=>`${r} - ${o}`});t.push(new Separator(a)),e.attributes.versions.forEach(({version:e})=>{t.push({name:e,value:{workspaceName:i,tileName:s,version:e}})})}),t}const syncCommand=new Command$1({name:"registry-sync",summary:"Check for newer versions of usage specs and install them into your project",allowArbitraryFlags:!1,requiresLogin:!1,handler:async({monitoring:{logger:e},projectDir:t,isInteractive:r})=>{
4258
+ if(!r)throw new ExpectedError('"sync" does not support non-interactive mode');const n=ora({hideCursor:!1,discardStdin:!1}).start("Checking for usage spec upgrades"),i=openFsd(t),s=getTesslClient(e,validateBaseEnv(process.env)),o=await readTesslJson(i);if(!o.success)throw new ExpectedError(o.error);const a=o.data,{majorUpdates:c,minorUpdates:u,patchUpdates:l,updateCheckFailures:d}=await getSpecUpdates(a,s);if(d.length>0){const t=d.map(e=>e.tileName&&e.tileVersion?`- ${e.tileName}@${e.tileVersion}: ${e.error}`:`- ${e.error}`).join("\n");return e.error({updateCheckFailures:d},"Received errors while checking for updates"),n.fail(`Received ${d.length} errors while checking for updates:\n${t}`),FAILURE}const p=[];if(l.length>0&&(p.push(new Separator("Patch updates")),p.push(...formatUpdateChoice(l))),u.length>0&&(p.push(new Separator("Minor updates")),p.push(...formatUpdateChoice(u))),c.length>0&&(p.push(new Separator("Major updates")),p.push(...formatUpdateChoice(c))),
4259
+ 0===p.length)return n.succeed("No updates found"),SUCCESS;n.stop();let h=[];try{h=await checkbox({message:"Select the updates you want to apply",choices:p})}catch(t){return t instanceof ExitPromptError?(n.stop(),SUCCESS):(e.error({err:t},"Unexpected error selecting updates to apply"),n.fail("Unexpected error selecting updates to apply"),FAILURE)}if(n.start("Applying updates"),0===h.length)return e.info({},"No updates selected"),n.warn("No updates selected"),SUCCESS;const A=await updateTesslJsonDependencies(i,{add:h});if(!A.success)return e.error({err:A.error},"Failed to update Tessl JSON dependencies"),n.fail(A.error),FAILURE;const f=await syncUsageSpecs(t,i,s);return f.success?(n.succeed(`Updated ${h.length} usage ${1===h.length?"spec":"specs"}`),SUCCESS):(e.error({err:f.error},"Failed to sync usage specs"),n.fail(f.error),FAILURE)}});function formatUpdateChoice(e){return e.map(e=>({name:`${e.tileName.padEnd(35)} ${e.tileVersion} > ${e.newVersion}`,value:{
4260
+ workspaceName:e.workspaceName,tileName:e.tileName,newVersion:e.newVersion,docPath:e.docPath}}))}const registryUnpublishCommand=new Command$1({name:"registry-unpublish",summary:"Unpublish specs in the Tessl registry",allowArbitraryFlags:!1,positionals:[{name:"spec",description:'The spec to unpublish, in the format "workspace/spec@version"'}],requiresLogin:!0,requiresConfig:!1,handler:async({monitoring:{logger:e},positionals:{spec:t}})=>{if(!t)throw new ExpectedError("A spec must be provided as the first argument");const[r,n]=t.split("@");if(!r||!n)throw new ExpectedError('The spec must be in the format "workspace/spec@version"');const[i,s]=r.split("/");if(!i||!s)throw new ExpectedError('The spec must be in the format "workspace/tile"');const o=createSpinner("Unpublishing"),a=getTesslClient(e,validateBaseEnv(process.env)),c=await a.DELETE("/v1/tiles/{workspaceName}/{tileName}/versions/{version}",{params:{path:{workspaceName:i,tileName:s,version:n}}});return c.error?(e.error({err:c.error
4261
+ },"Failed to unpublish spec"),o.fail(apiErrToString(c.error)),FAILURE):(o.succeed(`Unpublished ${i}/${s}@${n}`),SUCCESS)}}),safeNormalizeFileUrl=(e,t)=>{const r=normalizeFileUrl(normalizeDenoExecPath(e));if("string"!=typeof r)throw new TypeError(`${t} must be a string or a file URL: ${r}.`);return r},normalizeDenoExecPath=e=>isDenoExecPath(e)?e.toString():e,isDenoExecPath=e=>"string"!=typeof e&&e&&Object.getPrototypeOf(e)===String.prototype,normalizeFileUrl=e=>e instanceof URL?fileURLToPath$1(e):e,normalizeParameters=(e,t=[],r={})=>{const n=safeNormalizeFileUrl(e,"First argument"),[i,s]=isPlainObject$2(t)?[[],t]:[t,r];if(!Array.isArray(i))throw new TypeError(`Second argument must be either an array of arguments or an options object: ${i}`);if(i.some(e=>"object"==typeof e&&null!==e))throw new TypeError(`Second argument must be an array of strings: ${i}`);const o=i.map(String),a=o.find(e=>e.includes("\0"))
4262
+ ;if(void 0!==a)throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${a}`);if(!isPlainObject$2(s))throw new TypeError(`Last argument must be an options object: ${s}`);return[n,o,s]},{toString:objectToString$1}=Object.prototype,isArrayBuffer=e=>"[object ArrayBuffer]"===objectToString$1.call(e),isUint8Array=e=>"[object Uint8Array]"===objectToString$1.call(e),bufferToUint8Array=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),textEncoder$1=new TextEncoder,stringToUint8Array=e=>textEncoder$1.encode(e),textDecoder=new TextDecoder,uint8ArrayToString=e=>textDecoder.decode(e),joinToString=(e,t)=>uint8ArraysToStrings(e,t).join(""),uint8ArraysToStrings=(e,t)=>{if("utf8"===t&&e.every(e=>"string"==typeof e))return e;const r=new StringDecoder(t),n=e.map(e=>"string"==typeof e?stringToUint8Array(e):e).map(e=>r.write(e)),i=r.end();return""===i?n:[...n,i]
4263
+ },joinToUint8Array=e=>1===e.length&&isUint8Array(e[0])?e[0]:concatUint8Arrays(stringsToUint8Arrays(e)),stringsToUint8Arrays=e=>e.map(e=>"string"==typeof e?stringToUint8Array(e):e),concatUint8Arrays=e=>{const t=new Uint8Array(getJoinLength(e));let r=0;for(const n of e)t.set(n,r),r+=n.length;return t},getJoinLength=e=>{let t=0;for(const r of e)t+=r.length;return t},isTemplateString=e=>Array.isArray(e)&&Array.isArray(e.raw),parseTemplates=(e,t)=>{let r=[];for(const[n,i]of e.entries())r=parseTemplate({templates:e,expressions:t,tokens:r,index:n,template:i});if(0===r.length)throw new TypeError("Template script must not be empty");const[n,...i]=r;return[n,i,{}]},parseTemplate=({templates:e,expressions:t,tokens:r,index:n,template:i})=>{if(void 0===i)throw new TypeError(`Invalid backslash sequence: ${e.raw[n]}`);const{nextTokens:s,leadingWhitespaces:o,trailingWhitespaces:a}=splitByWhitespaces(i,e.raw[n]),c=concatTokens(r,s,o);if(n===t.length)return c
4264
+ ;const u=t[n],l=Array.isArray(u)?u.map(e=>parseExpression(e)):[parseExpression(u)];return concatTokens(c,l,a)},splitByWhitespaces=(e,t)=>{if(0===t.length)return{nextTokens:[],leadingWhitespaces:!1,trailingWhitespaces:!1};const r=[];let n=0;const i=DELIMITERS.has(t[0]);for(let i=0,s=0;i<e.length;i+=1,s+=1){const o=t[s];if(DELIMITERS.has(o))n!==i&&r.push(e.slice(n,i)),n=i+1;else if("\\"===o){const e=t[s+1];"\n"===e?(i-=1,s+=1):"u"===e&&"{"===t[s+2]?s=t.indexOf("}",s+3):s+=ESCAPE_LENGTH[e]??1}}const s=n===e.length;return s||r.push(e.slice(n)),{nextTokens:r,leadingWhitespaces:i,trailingWhitespaces:s}},DELIMITERS=new Set([" ","\t","\r","\n"]),ESCAPE_LENGTH={x:3,u:5},concatTokens=(e,t,r)=>r||0===e.length||0===t.length?[...e,...t]:[...e.slice(0,-1),`${e.at(-1)}${t[0]}`,...t.slice(1)],parseExpression=e=>{const t=typeof e;if("string"===t)return e;if("number"===t)return String(e);if(isPlainObject$2(e)&&("stdout"in e||"isMaxBuffer"in e))return getSubprocessResult(e)
4265
+ ;if(e instanceof ChildProcess||"[object Promise]"===Object.prototype.toString.call(e))throw new TypeError("Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.");throw new TypeError(`Unexpected "${t}" in template expression`)},getSubprocessResult=({stdout:e})=>{if("string"==typeof e)return e;if(isUint8Array(e))return uint8ArrayToString(e);if(void 0===e)throw new TypeError('Missing result.stdout in template expression. This is probably due to the previous subprocess\' "stdout" option.');throw new TypeError(`Unexpected "${typeof e}" stdout in template expression`)},isStandardStream=e=>STANDARD_STREAMS.includes(e),STANDARD_STREAMS=[process$5.stdin,process$5.stdout,process$5.stderr],STANDARD_STREAMS_ALIASES=["stdin","stdout","stderr"],getStreamName=e=>STANDARD_STREAMS_ALIASES[e]??`stdio[${e}]`,normalizeFdSpecificOptions=e=>{const t={...e};for(const r of FD_SPECIFIC_OPTIONS)t[r]=normalizeFdSpecificOption(e,r);return t
4266
+ },normalizeFdSpecificOption=(e,t)=>{const r=Array.from({length:getStdioLength(e)+1}),n=normalizeFdSpecificValue(e[t],r,t);return addDefaultValue$1(n,t)},getStdioLength=({stdio:e})=>Array.isArray(e)?Math.max(e.length,STANDARD_STREAMS_ALIASES.length):STANDARD_STREAMS_ALIASES.length,normalizeFdSpecificValue=(e,t,r)=>isPlainObject$2(e)?normalizeOptionObject(e,t,r):t.fill(e),normalizeOptionObject=(e,t,r)=>{for(const n of Object.keys(e).sort(compareFdName))for(const i of parseFdName(n,r,t))t[i]=e[n];return t},compareFdName=(e,t)=>getFdNameOrder(e)<getFdNameOrder(t)?1:-1,getFdNameOrder=e=>"stdout"===e||"stderr"===e?0:"all"===e?2:1,parseFdName=(e,t,r)=>{if("ipc"===e)return[r.length-1];const n=parseFd(e);if(void 0===n||0===n)throw new TypeError(`"${t}.${e}" is invalid.\nIt must be "${t}.stdout", "${t}.stderr", "${t}.all", "${t}.ipc", or "${t}.fd3", "${t}.fd4" (and so on).`)
4267
+ ;if(n>=r.length)throw new TypeError(`"${t}.${e}" is invalid: that file descriptor does not exist.\nPlease set the "stdio" option to ensure that file descriptor exists.`);return"all"===n?[1,2]:[n]},parseFd=e=>{if("all"===e)return e;if(STANDARD_STREAMS_ALIASES.includes(e))return STANDARD_STREAMS_ALIASES.indexOf(e);const t=FD_REGEXP.exec(e);return null!==t?Number(t[1]):void 0},FD_REGEXP=/^fd(\d+)$/,addDefaultValue$1=(e,t)=>e.map(e=>void 0===e?DEFAULT_OPTIONS[t]:e),verboseDefault=debuglog("execa").enabled?"full":"none",DEFAULT_OPTIONS={lines:!1,buffer:!0,maxBuffer:1e8,verbose:verboseDefault,stripFinalNewline:!0},FD_SPECIFIC_OPTIONS=["lines","buffer","maxBuffer","verbose","stripFinalNewline"],getFdSpecificValue=(e,t)=>"ipc"===t?e.at(-1):e[t],isVerbose=({verbose:e},t)=>"none"!==getFdVerbose(e,t),isFullVerbose=({verbose:e},t)=>!["none","short"].includes(getFdVerbose(e,t)),getVerboseFunction=({verbose:e},t)=>{const r=getFdVerbose(e,t);return isVerboseFunction(r)?r:void 0
4268
+ },getFdVerbose=(e,t)=>void 0===t?getFdGenericVerbose(e):getFdSpecificValue(e,t),getFdGenericVerbose=e=>e.find(e=>isVerboseFunction(e))??VERBOSE_VALUES.findLast(t=>e.includes(t)),isVerboseFunction=e=>"function"==typeof e,VERBOSE_VALUES=["none","short","full"],joinCommand=(e,t)=>{const r=[e,...t];return{command:r.join(" "),escapedCommand:r.map(e=>quoteString(escapeControlCharacters(e))).join(" ")}},escapeLines=e=>stripVTControlCharacters(e).split("\n").map(e=>escapeControlCharacters(e)).join("\n"),escapeControlCharacters=e=>e.replaceAll(SPECIAL_CHAR_REGEXP,e=>escapeControlCharacter(e)),escapeControlCharacter=e=>{const t=COMMON_ESCAPES[e];if(void 0!==t)return t;const r=e.codePointAt(0),n=r.toString(16);return r<=ASTRAL_START?`\\u${n.padStart(4,"0")}`:`\\U${n}`},getSpecialCharRegExp=()=>{try{return new RegExp("\\p{Separator}|\\p{Other}","gu")}catch{return/[\s\u0000-\u001F\u007F-\u009F\u00AD]/g}},SPECIAL_CHAR_REGEXP=getSpecialCharRegExp(),COMMON_ESCAPES={" ":" ","\b":"\\b","\f":"\\f",
4269
+ "\n":"\\n","\r":"\\r","\t":"\\t"},ASTRAL_START=65535,quoteString=e=>NO_ESCAPE_REGEXP.test(e)?e:"win32"===platform$2?`"${e.replaceAll('"','""')}"`:`'${e.replaceAll("'","'\\''")}'`,NO_ESCAPE_REGEXP=/^[\w./-]+$/,defaultVerboseFunction=({type:e,message:t,timestamp:r,piped:n,commandId:i,result:{failed:s=!1}={},options:{reject:o=!0}})=>{const a=serializeTimestamp(r),c=ICONS[e]({failed:s,reject:o,piped:n}),u=COLORS[e]({reject:o});return`${gray(`[${a}]`)} ${gray(`[${i}]`)} ${u(c)} ${u(t)}`},serializeTimestamp=e=>`${padField(e.getHours(),2)}:${padField(e.getMinutes(),2)}:${padField(e.getSeconds(),2)}.${padField(e.getMilliseconds(),3)}`,padField=(e,t)=>String(e).padStart(t,"0"),getFinalIcon=({failed:e,reject:t})=>e?t?figures.cross:figures.warning:figures.tick,ICONS={command:({piped:e})=>e?"|":"$",output:()=>" ",ipc:()=>"*",error:getFinalIcon,duration:getFinalIcon},identity$1=e=>e,COLORS={command:()=>bold,output:()=>identity$1,ipc:()=>identity$1,error:({reject:e})=>e?redBright:yellowBright,
4270
+ duration:()=>gray},applyVerboseOnLines=(e,t,r)=>{const n=getVerboseFunction(t,r);return e.map(({verboseLine:e,verboseObject:t})=>applyVerboseFunction(e,t,n)).filter(e=>void 0!==e).map(e=>appendNewline(e)).join("")},applyVerboseFunction=(e,t,r)=>{if(void 0===r)return e;const n=r(e,t);return"string"==typeof n?n:void 0},appendNewline=e=>e.endsWith("\n")?e:`${e}\n`,verboseLog=({type:e,verboseMessage:t,fdNumber:r,verboseInfo:n,result:i})=>{const s=getVerboseObject({type:e,result:i,verboseInfo:n}),o=getPrintedLines(t,s),a=applyVerboseOnLines(o,n,r);""!==a&&console.warn(a.slice(0,-1))},getVerboseObject=({type:e,result:t,verboseInfo:{escapedCommand:r,commandId:n,rawOptions:{piped:i=!1,...s}}})=>({type:e,escapedCommand:r,commandId:`${n}`,timestamp:new Date,piped:i,result:t,options:s}),getPrintedLines=(e,t)=>e.split("\n").map(e=>getPrintedLine({...t,message:e})),getPrintedLine=e=>({verboseLine:defaultVerboseFunction(e),verboseObject:e}),serializeVerboseMessage=e=>{
4271
+ const t="string"==typeof e?e:inspect$1(e);return escapeLines(t).replaceAll("\t"," ".repeat(TAB_SIZE))},TAB_SIZE=2,logCommand=(e,t)=>{isVerbose(t)&&verboseLog({type:"command",verboseMessage:e,verboseInfo:t})},getVerboseInfo=(e,t,r)=>{validateVerbose(e);return{verbose:e,escapedCommand:t,commandId:getCommandId(e),rawOptions:r}},getCommandId=e=>isVerbose({verbose:e})?COMMAND_ID++:void 0;let COMMAND_ID=0n;const validateVerbose=e=>{for(const t of e){if(!1===t)throw new TypeError('The "verbose: false" option was renamed to "verbose: \'none\'".');if(!0===t)throw new TypeError('The "verbose: true" option was renamed to "verbose: \'short\'".');if(!VERBOSE_VALUES.includes(t)&&!isVerboseFunction(t)){const e=VERBOSE_VALUES.map(e=>`'${e}'`).join(", ");throw new TypeError(`The "verbose" option must not be ${t}. Allowed values are: ${e} or a function.`)}}},getStartTime=()=>hrtime.bigint(),getDurationMs=e=>Number(hrtime.bigint()-e)/1e6,handleCommand=(e,t,r)=>{
4272
+ const n=getStartTime(),{command:i,escapedCommand:s}=joinCommand(e,t),o=normalizeFdSpecificOption(r,"verbose"),a=getVerboseInfo(o,s,{...r});return logCommand(s,a),{command:i,escapedCommand:s,startTime:n,verboseInfo:a}};var crossSpawn$1={exports:{}},windows,hasRequiredWindows,mode,hasRequiredMode,isexe_1,hasRequiredIsexe,which_1,hasRequiredWhich;function requireWindows(){if(hasRequiredWindows)return windows;hasRequiredWindows=1,windows=r,r.sync=function(r,n){return t(e.statSync(r),r,n)};var e=fs$4;function t(e,t,r){return!(!e.isSymbolicLink()&&!e.isFile())&&function(e,t){var r=void 0!==t.pathExt?t.pathExt:process.env.PATHEXT;if(!r)return!0;if(-1!==(r=r.split(";")).indexOf(""))return!0;for(var n=0;n<r.length;n++){var i=r[n].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}(t,r)}function r(r,n,i){e.stat(r,function(e,s){i(e,!e&&t(s,r,n))})}return windows}function requireMode(){if(hasRequiredMode)return mode;hasRequiredMode=1,mode=t,t.sync=function(t,n){
4273
+ return r(e.statSync(t),n)};var e=fs$4;function t(t,n,i){e.stat(t,function(e,t){i(e,!e&&r(t,n))})}function r(e,t){return e.isFile()&&function(e,t){var r=e.mode,n=e.uid,i=e.gid,s=void 0!==t.uid?t.uid:process.getuid&&process.getuid(),o=void 0!==t.gid?t.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),u=parseInt("001",8),l=a|c,d=r&u||r&c&&i===o||r&a&&n===s||r&l&&0===s;return d}(e,t)}return mode}function requireIsexe(){if(hasRequiredIsexe)return isexe_1;var e;function t(r,n,i){if("function"==typeof n&&(i=n,n={}),!i){if("function"!=typeof Promise)throw new TypeError("callback not provided");return new Promise(function(e,i){t(r,n||{},function(t,r){t?i(t):e(r)})})}e(r,n||{},function(e,t){e&&("EACCES"===e.code||n&&n.ignoreErrors)&&(e=null,t=!1),i(e,t)})}return hasRequiredIsexe=1,e="win32"===process.platform||commonjsGlobal.TESTING_WINDOWS?requireWindows():requireMode(),isexe_1=t,t.sync=function(t,r){try{return e.sync(t,r||{})}catch(e){
4274
+ if(r&&r.ignoreErrors||"EACCES"===e.code)return!1;throw e}},isexe_1}function requireWhich(){if(hasRequiredWhich)return which_1;hasRequiredWhich=1;const e="win32"===process.platform||"cygwin"===process.env.OSTYPE||"msys"===process.env.OSTYPE,t=path__default,r=e?";":":",n=requireIsexe(),i=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),s=(t,n)=>{const i=n.colon||r,s=t.match(/\//)||e&&t.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(n.path||process.env.PATH||"").split(i)],o=e?n.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",a=e?o.split(i):[""];return e&&-1!==t.indexOf(".")&&""!==a[0]&&a.unshift(""),{pathEnv:s,pathExt:a,pathExtExe:o}},o=(e,r,o)=>{"function"==typeof r&&(o=r,r={}),r||(r={});const{pathEnv:a,pathExt:c,pathExtExe:u}=s(e,r),l=[],d=n=>new Promise((s,o)=>{if(n===a.length)return r.all&&l.length?s(l):o(i(e));const c=a[n],u=/^".*"$/.test(c)?c.slice(1,-1):c,d=t.join(u,e),h=!u&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;s(p(h,n,0))}),p=(e,t,i)=>new Promise((s,o)=>{
4275
+ if(i===c.length)return s(d(t+1));const a=c[i];n(e+a,{pathExt:u},(n,o)=>{if(!n&&o){if(!r.all)return s(e+a);l.push(e+a)}return s(p(e,t,i+1))})});return o?d(0).then(e=>o(null,e),o):d(0)};return which_1=o,o.sync=(e,r)=>{r=r||{};const{pathEnv:o,pathExt:a,pathExtExe:c}=s(e,r),u=[];for(let i=0;i<o.length;i++){const s=o[i],l=/^".*"$/.test(s)?s.slice(1,-1):s,d=t.join(l,e),p=!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d;for(let e=0;e<a.length;e++){const t=p+a[e];try{if(n.sync(t,{pathExt:c})){if(!r.all)return t;u.push(t)}}catch(e){}}}if(r.all&&u.length)return u;if(r.nothrow)return null;throw i(e)},which_1}var pathKey$1={exports:{}},hasRequiredPathKey,resolveCommand_1,hasRequiredResolveCommand;function requirePathKey(){if(hasRequiredPathKey)return pathKey$1.exports;hasRequiredPathKey=1;const e=(e={})=>{const t=e.env||process.env;return"win32"!==(e.platform||process.platform)?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"};return pathKey$1.exports=e,
4276
+ pathKey$1.exports.default=e,pathKey$1.exports}function requireResolveCommand(){if(hasRequiredResolveCommand)return resolveCommand_1;hasRequiredResolveCommand=1;const e=path__default,t=requireWhich(),r=requirePathKey();function n(n,i){const s=n.options.env||process.env,o=process.cwd(),a=null!=n.options.cwd,c=a&&void 0!==process.chdir&&!process.chdir.disabled;if(c)try{process.chdir(n.options.cwd)}catch(e){}let u;try{u=t.sync(n.command,{path:s[r({env:s})],pathExt:i?e.delimiter:void 0})}catch(e){}finally{c&&process.chdir(o)}return u&&(u=e.resolve(a?n.options.cwd:"",u)),u}return resolveCommand_1=function(e){return n(e)||n(e,!0)}}var _escape={},hasRequired_escape,shebangRegex,hasRequiredShebangRegex,shebangCommand,hasRequiredShebangCommand,readShebang_1,hasRequiredReadShebang,parse_1,hasRequiredParse,enoent,hasRequiredEnoent,hasRequiredCrossSpawn;function require_escape(){if(hasRequired_escape)return _escape;hasRequired_escape=1;const e=/([()\][%!^"`<>&|;, *?])/g
4277
+ ;return _escape.command=function(t){return t=t.replace(e,"^$1")},_escape.argument=function(t,r){return t=(t=`"${t=(t=(t=`${t}`).replace(/(?=(\\+?)?)\1"/g,'$1$1\\"')).replace(/(?=(\\+?)?)\1$/,"$1$1")}"`).replace(e,"^$1"),r&&(t=t.replace(e,"^$1")),t},_escape}function requireShebangRegex(){return hasRequiredShebangRegex?shebangRegex:(hasRequiredShebangRegex=1,shebangRegex=/^#!(.*)/)}function requireShebangCommand(){if(hasRequiredShebangCommand)return shebangCommand;hasRequiredShebangCommand=1;const e=requireShebangRegex();return shebangCommand=(t="")=>{const r=t.match(e);if(!r)return null;const[n,i]=r[0].replace(/#! ?/,"").split(" "),s=n.split("/").pop();return"env"===s?i:i?`${s} ${i}`:s},shebangCommand}function requireReadShebang(){if(hasRequiredReadShebang)return readShebang_1;hasRequiredReadShebang=1;const e=fs$4,t=requireShebangCommand();return readShebang_1=function(r){const n=Buffer.alloc(150);let i;try{i=e.openSync(r,"r"),e.readSync(i,n,0,150,0),e.closeSync(i)}catch(e){}
4278
+ return t(n.toString())},readShebang_1}function requireParse(){if(hasRequiredParse)return parse_1;hasRequiredParse=1;const e=path__default,t=requireResolveCommand(),r=require_escape(),n=requireReadShebang(),i="win32"===process.platform,s=/\.(?:com|exe)$/i,o=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function a(a){if(!i)return a;const c=function(e){e.file=t(e);const r=e.file&&n(e.file);return r?(e.args.unshift(e.file),e.command=r,t(e)):e.file}(a),u=!s.test(c);if(a.options.forceShell||u){const t=o.test(c);a.command=e.normalize(a.command),a.command=r.command(a.command),a.args=a.args.map(e=>r.argument(e,t));const n=[a.command].concat(a.args).join(" ");a.args=["/d","/s","/c",`"${n}"`],a.command=process.env.comspec||"cmd.exe",a.options.windowsVerbatimArguments=!0}return a}return parse_1=function(e,t,r){t&&!Array.isArray(t)&&(r=t,t=null);const n={command:e,args:t=t?t.slice(0):[],options:r=Object.assign({},r),file:void 0,original:{command:e,args:t}};return r.shell?n:a(n)},parse_1}
4279
+ function requireEnoent(){if(hasRequiredEnoent)return enoent;hasRequiredEnoent=1;const e="win32"===process.platform;function t(e,t){return Object.assign(new Error(`${t} ${e.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function r(r,n){return e&&1===r&&!n.file?t(n.original,"spawn"):null}return enoent={hookChildProcess:function(t,n){if(!e)return;const i=t.emit;t.emit=function(e,s){if("exit"===e){const e=r(s,n);if(e)return i.call(t,"error",e)}return i.apply(t,arguments)}},verifyENOENT:r,verifyENOENTSync:function(r,n){return e&&1===r&&!n.file?t(n.original,"spawnSync"):null},notFoundError:t},enoent}function requireCrossSpawn(){if(hasRequiredCrossSpawn)return crossSpawn$1.exports;hasRequiredCrossSpawn=1;const e=require$$0__default$2,t=requireParse(),r=requireEnoent();function n(n,i,s){const o=t(n,i,s),a=e.spawn(o.command,o.args,o.options);return r.hookChildProcess(a,o),a}return crossSpawn$1.exports=n,crossSpawn$1.exports.spawn=n,
4280
+ crossSpawn$1.exports.sync=function(n,i,s){const o=t(n,i,s),a=e.spawnSync(o.command,o.args,o.options);return a.error=a.error||r.verifyENOENTSync(a.status,o),a},crossSpawn$1.exports._parse=t,crossSpawn$1.exports._enoent=r,crossSpawn$1.exports}var crossSpawnExports=requireCrossSpawn(),crossSpawn=getDefaultExportFromCjs(crossSpawnExports);function pathKey(e={}){const{env:t=process.env,platform:r=process.platform}=e;return"win32"!==r?"PATH":Object.keys(t).reverse().find(e=>"PATH"===e.toUpperCase())||"Path"}function toPath(e){return e instanceof URL?fileURLToPath$1(e):e}function traversePathUp(e){return{*[Symbol.iterator](){let t,r=path__default$1.resolve(toPath(e));for(;t!==r;)yield r,t=r,r=path__default$1.resolve(r,"..")}}}promisify(execFile);const npmRunPath=({cwd:e=process$5.cwd(),path:t=process$5.env[pathKey()],preferLocal:r=!0,execPath:n=process$5.execPath,addExecPath:i=!0}={})=>{const s=path__default$1.resolve(toPath(e)),o=[],a=t.split(path__default$1.delimiter)
4281
+ ;return r&&applyPreferLocal(o,a,s),i&&applyExecPath(o,a,n,s),""===t||t===path__default$1.delimiter?`${o.join(path__default$1.delimiter)}${t}`:[...o,t].join(path__default$1.delimiter)},applyPreferLocal=(e,t,r)=>{for(const n of traversePathUp(r)){const r=path__default$1.join(n,"node_modules/.bin");t.includes(r)||e.push(r)}},applyExecPath=(e,t,r,n)=>{const i=path__default$1.resolve(n,toPath(r),"..");t.includes(i)||e.push(i)},npmRunPathEnv=({env:e=process$5.env,...t}={})=>{const r=pathKey({env:e={...e}});return t.path=e[r],e[r]=npmRunPath(t),e},getFinalError=(e,t,r)=>new(r?ExecaSyncError:ExecaError)(t,e instanceof DiscardedError?{}:{cause:e});class DiscardedError extends Error{}const setErrorName=(e,t)=>{Object.defineProperty(e.prototype,"name",{value:t,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,execaErrorSymbol,{value:!0,writable:!1,enumerable:!1,configurable:!1})
4282
4282
  },isExecaError=e=>isErrorInstance(e)&&execaErrorSymbol in e,execaErrorSymbol=Symbol("isExecaError"),isErrorInstance=e=>"[object Error]"===Object.prototype.toString.call(e);class ExecaError extends Error{}setErrorName(ExecaError,ExecaError.name);class ExecaSyncError extends Error{}setErrorName(ExecaSyncError,ExecaSyncError.name);const getRealtimeSignals=()=>{const e=SIGRTMAX-SIGRTMIN+1;return Array.from({length:e},getRealtimeSignal)},getRealtimeSignal=(e,t)=>({name:`SIGRT${t+1}`,number:SIGRTMIN+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}),SIGRTMIN=34,SIGRTMAX=64,SIGNALS=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",
4283
4283
  description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,
4284
4284
  action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{
@@ -4401,9 +4401,9 @@ i?console.log(`To perform the actual update, run ${chalk.blue("tessl update --no
4401
4401
  error:apiErrToString(n.error)};const i=n.data.data[0];return i?{success:!0,user:{id:i.id,username:i.attributes.username}}:{success:!1,error:`User not found: ${r}`}}async function resolveWorkspace(e,t,r){if(!r){t.text="Fetching workspaces";const r=await e.GET("/v1/workspaces");if(r.error)return{success:!1,error:apiErrToString(r.error)};const n=r.data.data.map(e=>{const t=e.attributes.name;return{name:t,value:{id:e.id,name:t}}}),i=t.isSpinning;t.stop();const s=await select({message:"Select a workspace",choices:n});return i&&t.start(),{success:!0,workspace:s}}if(t.text="Fetching workspace",validate$1(r)){const t=await e.GET("/v1/workspaces/{workspaceId}",{params:{path:{workspaceId:r}}});if(t.error)return{success:!1,error:apiErrToString(t.error)};const n=t.data.data;return{success:!0,workspace:{id:n.id,name:n.attributes.name}}}const n=await e.GET("/v1/workspaces",{params:{query:{"filter[name]":r,"page[size]":1}}});if(n.error)return{success:!1,error:apiErrToString(n.error)}
4402
4402
  ;const i=n.data.data[0];return i?{success:!0,workspace:{id:i.id,name:i.attributes.name}}:{success:!1,error:`Workspace not found: ${r}`}}const roles=["viewer","member","owner"],roleChoices=roles.map(e=>({name:e,value:e})),addWorkspaceMemberCommand=new Command$1({name:"workspace-add-member",summary:"Add a member to a workspace",allowArbitraryFlags:!1,requiresLogin:!0,requiresConfig:!1,flags:{workspace:{type:String,description:"The name or ID of the workspace"},user:{type:String,description:"The name or ID user to add"},role:{type:String,description:`The role of the user to add. Can be one of "${roles.join('", "')}"`}},handler:async({monitoring:{logger:e},args:t})=>{let r=t.role;if(r&&!roles.includes(r))throw new ExpectedError(`Invalid role: ${r}. Must be one of: ${roles.join(", ")}`);const n=createSpinner(),i=getTesslClient(e,validateBaseEnv(process.env));if(!t.user)return n.fail("--user must be provided as a user ID or username"),FAILURE;const s=await resolveUser(i,n,t.user)
4403
4403
  ;if(!s.success)return e.error({args:t},s.error),n.fail(s.error),FAILURE;const o=s.user,a=await resolveWorkspace(i,n,t.workspace);if(!a.success)return e.error({args:t},a.error),n.fail(a.error),FAILURE;const c=a.workspace;if(!r)try{r=await select({message:"What role should the user have?",choices:roleChoices,default:"viewer"})}catch(e){if(e instanceof ExitPromptError)return SUCCESS;throw e}n.start(`Adding ${o.username} as ${r} to ${c.name}`);const u=await i.POST("/v1/workspaces/{workspaceId}/members",{params:{path:{workspaceId:c.id}},body:{userId:o.id,role:r}});return u.error?(n.fail(apiErrToString(u.error)),e.error({err:u.error},"Failed to add member"),FAILURE):(e.info({workspaceId:c.id,workspaceName:c.name,role:r},"Added member to workspace"),n.succeed(`Added ${o.username} as ${r} to ${c.name}`),SUCCESS)}}),createWorkspaceCommand=new Command$1({name:"workspace-create",summary:"Create a new workspace",positionals:[{name:"name",description:"The name of the workspace"}],requiresConfig:!1,
4404
- allowArbitraryFlags:!1,requiresLogin:!0,handler:async({positionals:{name:e},monitoring:t})=>{if(!e)return process.stderr.write(`${styleText("red",figures.cross)} --name is required\n`),FAILURE;const r=createSpinner("Creating workspace"),n=validateBaseEnv(process.env),i=getTesslClient(t.logger,n),s=await i.POST("/v1/workspaces",{body:{name:e}});return s.error?(r.fail(apiErrToString(s.error)),FAILURE):(r.succeed(`Created workspace ${e} (${s.data.data.id})`),SUCCESS)}}),deleteWorkspaceCommand=new Command$1({name:"workspace-delete",summary:"Delete a workspace",positionals:[{name:"workspace",description:"The name or ID of the workspace"}],allowArbitraryFlags:!1,requiresConfig:!1,requiresLogin:!0,handler:async({positionals:e,monitoring:{logger:t}})=>{const r=ora({hideCursor:!1,discardStdin:!1}).start("Deleting workspace"),n=getTesslClient(t,validateBaseEnv(process.env)),i=await resolveWorkspace(n,r,e.workspace);if(!i.success)return t.error({positionals:e},i.error),r.fail(i.error),FAILURE
4405
- ;const s=i.workspace;r.text=`Deleting workspace ${s.name}`;const o=await n.DELETE("/v1/workspaces/{workspaceId}",{params:{path:{workspaceId:s.id}}});return o.error?(r.fail(apiErrToString(o.error)),FAILURE):(r.succeed(`Deleted workspace ${s.name}`),SUCCESS)}});var src={},createStream={},alignTableData={},alignString={},stringWidth={exports:{}},ansiRegex,hasRequiredAnsiRegex,stripAnsi,hasRequiredStripAnsi;function requireAnsiRegex(){return hasRequiredAnsiRegex||(hasRequiredAnsiRegex=1,ansiRegex=({onlyFirst:e=!1}={})=>{const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}),ansiRegex}function requireStripAnsi(){if(hasRequiredStripAnsi)return stripAnsi;hasRequiredStripAnsi=1;const e=requireAnsiRegex();return stripAnsi=t=>"string"==typeof t?t.replace(e(),""):t,stripAnsi}var isFullwidthCodePoint={exports:{}
4406
- },hasRequiredIsFullwidthCodePoint,emojiRegex,hasRequiredEmojiRegex,hasRequiredStringWidth;function requireIsFullwidthCodePoint(){if(hasRequiredIsFullwidthCodePoint)return isFullwidthCodePoint.exports;hasRequiredIsFullwidthCodePoint=1;const e=e=>!Number.isNaN(e)&&(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&12351!==e||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141));return isFullwidthCodePoint.exports=e,isFullwidthCodePoint.exports.default=e,isFullwidthCodePoint.exports}function requireEmojiRegex(){return hasRequiredEmojiRegex?emojiRegex:(hasRequiredEmojiRegex=1,emojiRegex=function(){
4404
+ allowArbitraryFlags:!1,requiresLogin:!0,handler:async({positionals:{name:e},monitoring:t})=>{if(!e)return process.stderr.write(`${styleText("red",figures.cross)} A name is required as the first argument\n`),FAILURE;const r=createSpinner("Creating workspace"),n=validateBaseEnv(process.env),i=getTesslClient(t.logger,n),s=await i.POST("/v1/workspaces",{body:{name:e}});return s.error?(r.fail(apiErrToString(s.error)),FAILURE):(r.succeed(`Created workspace ${e} (${s.data.data.id})`),SUCCESS)}}),deleteWorkspaceCommand=new Command$1({name:"workspace-delete",summary:"Delete a workspace",positionals:[{name:"workspace",description:"The name or ID of the workspace"}],allowArbitraryFlags:!1,requiresConfig:!1,requiresLogin:!0,handler:async({positionals:e,monitoring:{logger:t}})=>{const r=ora({hideCursor:!1,discardStdin:!1}).start("Deleting workspace"),n=getTesslClient(t,validateBaseEnv(process.env)),i=await resolveWorkspace(n,r,e.workspace);if(!i.success)return t.error({positionals:e},i.error),
4405
+ r.fail(i.error),FAILURE;const s=i.workspace;r.text=`Deleting workspace ${s.name}`;const o=await n.DELETE("/v1/workspaces/{workspaceId}",{params:{path:{workspaceId:s.id}}});return o.error?(r.fail(apiErrToString(o.error)),FAILURE):(r.succeed(`Deleted workspace ${s.name}`),SUCCESS)}});var src={},createStream={},alignTableData={},alignString={},stringWidth={exports:{}},ansiRegex,hasRequiredAnsiRegex,stripAnsi,hasRequiredStripAnsi;function requireAnsiRegex(){return hasRequiredAnsiRegex||(hasRequiredAnsiRegex=1,ansiRegex=({onlyFirst:e=!1}={})=>{const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(t,e?void 0:"g")}),ansiRegex}function requireStripAnsi(){if(hasRequiredStripAnsi)return stripAnsi;hasRequiredStripAnsi=1;const e=requireAnsiRegex();return stripAnsi=t=>"string"==typeof t?t.replace(e(),""):t,stripAnsi}
4406
+ var isFullwidthCodePoint={exports:{}},hasRequiredIsFullwidthCodePoint,emojiRegex,hasRequiredEmojiRegex,hasRequiredStringWidth;function requireIsFullwidthCodePoint(){if(hasRequiredIsFullwidthCodePoint)return isFullwidthCodePoint.exports;hasRequiredIsFullwidthCodePoint=1;const e=e=>!Number.isNaN(e)&&(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&12351!==e||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141));return isFullwidthCodePoint.exports=e,isFullwidthCodePoint.exports.default=e,isFullwidthCodePoint.exports}function requireEmojiRegex(){return hasRequiredEmojiRegex?emojiRegex:(hasRequiredEmojiRegex=1,emojiRegex=function(){
4407
4407
  return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g
4408
4408
  })}function requireStringWidth(){if(hasRequiredStringWidth)return stringWidth.exports;hasRequiredStringWidth=1;const e=requireStripAnsi(),t=requireIsFullwidthCodePoint(),r=requireEmojiRegex(),n=n=>{if("string"!=typeof n||0===n.length)return 0;if(0===(n=e(n)).length)return 0;n=n.replace(r()," ");let i=0;for(let e=0;e<n.length;e++){const r=n.codePointAt(e);r<=31||r>=127&&r<=159||(r>=768&&r<=879||(r>65535&&e++,i+=t(r)?2:1))}return i};return stringWidth.exports=n,stringWidth.exports.default=n,stringWidth.exports}var utils={},astralRegex_1,hasRequiredAstralRegex;function requireAstralRegex(){if(hasRequiredAstralRegex)return astralRegex_1;hasRequiredAstralRegex=1;const e="[\ud800-\udbff][\udc00-\udfff]";return astralRegex_1=t=>t&&t.exact?new RegExp(`^${e}$`):new RegExp(e,"g")}var ansiStyles={exports:{}},hasRequiredAnsiStyles,sliceAnsi,hasRequiredSliceAnsi;function requireAnsiStyles(){return hasRequiredAnsiStyles||(hasRequiredAnsiStyles=1,function(e){
4409
4409
  const t=(e,t)=>(...r)=>`[${e(...r)+t}m`,r=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};5;${n}m`},n=(e,t)=>(...r)=>{const n=e(...r);return`[${38+t};2;${n[0]};${n[1]};${n[2]}m`},i=e=>e,s=(e,t,r)=>[e,t,r],o=(e,t,r)=>{Object.defineProperty(e,t,{get:()=>{const n=r();return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0}),n},enumerable:!0,configurable:!0})};let a;const c=(e,t,r,n)=>{void 0===a&&(a=requireColorConvert());const i=n?10:0,s={};for(const[n,o]of Object.entries(a)){const a="ansi16"===n?"ansi":n;n===t?s[a]=e(r,i):"object"==typeof o&&(s[a]=e(o[t],i))}return s};Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,a={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],
@@ -4558,9 +4558,9 @@ await e(t,_nullishCoalesce$d(r,()=>i.emitMgmt))}),i={uuid:r,parent:t.parent,lfTr
4558
4558
  const CLI_SESSION_KEY="cli-session-id",SESSION_EXPIRY_KEY="cli-session-expiry",MCP_PARENT_RUN_KEY="mcp-parent-run-id",SESSION_INACTIVITY_MS=18e5;class SessionManager{static async getCliSessionId(){const e=Date.now(),t=await projectCache().readText(CLI_SESSION_KEY),r=await projectCache().readText(SESSION_EXPIRY_KEY),n=r?parseInt(r,10):0;if(t&&n>e)return await this.extendCliSessionExpiry(),t;const i=v4();return await projectCache().writeText(CLI_SESSION_KEY,i),await this.extendCliSessionExpiry(),i}static async extendCliSessionExpiry(){const e=Date.now()+SESSION_INACTIVITY_MS;await projectCache().writeText(SESSION_EXPIRY_KEY,e.toString())}static generateMcpRunId(){return v4()}static async getCliSessionInfo(){return{sessionId:await this.getCliSessionId()}}static async setMcpParentRunId(e){await projectCache().writeText(MCP_PARENT_RUN_KEY,e)}static async getMcpToolInfo(){const e=await this.getCliSessionId(),t=await projectCache().readText(MCP_PARENT_RUN_KEY);return{
4559
4559
  runId:this.generateMcpRunId(),sessionId:e,parentRunId:t}}static async endCliSession(){try{await projectCache().writeText(SESSION_EXPIRY_KEY,"0")}catch(e){}}}function _nullishCoalesce$c(e,t){return null!=e?e:t()}function _optionalChain$f(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}async function createCliRequestContext(e,t){const{logger:r,langfuse:n}=e.monitoring,i=logManagementEvents(r.originalLogger,!0),s=createJsonlEventConsumer(),o=await SessionManager.getCliSessionInfo(),a=e.monitoring.analytics.getProjectId(),c=n.trace({name:"cli",userId:userIdentifier(e.monitoring.user),sessionId:o.sessionId,metadata:{...getSysinfo(),sessionId:o.sessionId,projectId:a}}),u=DEFAULT_TESSL_DIRS.customToolDirectory,l=u?[path__default.resolve(e.projectDir,u)]:[],d=await makeLookupTool({
4560
4560
  customToolDirs:l}),p=validateBaseEnv(process.env),h=[];e.inputDir&&h.push(nodeImportResolver(e.inputDir));const A=chainImportResolvers(h),f=getTesslClient(r,p,e.globalConfigDir),g={keys:{openAi:process.env.TESSL_LLM_API_KEY,fireworks:process.env.FIREWORKS_API_KEY,cerebras:process.env.CEREBRAS_API_KEY},cacheWith:{fs:await considerFsCaching()},apiEndpoint:{fireworks:process.env.FIREWORKS_API_ENDPOINT,openAi:process.env.TESSL_LLM_BASE_URL,cerebras:process.env.CEREBRAS_API_ENDPOINT},shareUsageData:_nullishCoalesce$c(e.monitoring.shareUsageData,()=>!0)},m=createRequestContext(async t=>{await i(t,m.emitMgmt),await s(t,m.emitMgmt),await _optionalChain$f([e,"access",e=>e.handleManagementEvent,"optionalCall",e=>e(t,m.emitMgmt)])},{lfTrace:c,logger:r,abortSignal:t.signal,lookupTool:d,resolveImport:A,llmFactory:g,tesslClient:f,projectConfig:e.projectConfig,projectDir:e.projectDir,userFeatureFlags:FeatureFlagsAlwaysReturnTrue,waitForInput:e.waitForInput,shutdown:s.shutdown});return m}
4561
- function _nullishCoalesce$b(e,t){return null!=e?e:t()}function _optionalChain$e(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function getErrorProperty(e,t){return e&&"object"==typeof e&&t in e?e[t]:void 0}const executeToolInCli=async e=>{const{toolName:t,params:r,onStart:n,monitoring:{analytics:i}}=e,s=reqSchema.parse({steps:[{name:t,params:r}]});let o;if(1===s.steps.length){o=performance$2.now();const e=s.steps[0],t=builtInTools().every(t=>t.name!==e.name);i.toolStart({toolName:e.name,isAliased:!1,isCustom:t,executionMode:"local",params:_nullishCoalesce$b(e.params,()=>({}))})}const a=e.fsd?void 0:openFsd(e.projectDir);const c=a?fsdiff(a):e.fsd,u=_nullishCoalesce$b(_optionalChain$e([a,"optionalAccess",e=>e.root]),()=>e.inputDir);_optionalChain$e([n,"optionalCall",e=>e({fsd:c,
4562
- req:s})]);const l=new AbortController,d=()=>{l.abort()};process.once("SIGINT",d),process.once("SIGTERM",d);const p=await createCliRequestContext({...e,inputDir:u,fsd:c,req:s},l),h=await bindTools(p.lookupTool,s);for(const{tool:e}of h)checkToolCanRun(e,!0);let A=SUCCESS;try{A=await withHeartbeat(p,l,async e=>executeToolList(h,{rc:p,fsd:c},e))}catch(e){await p.emitMgmt({id:"crash",err:l.signal.aborted?{message:"Operation cancelled by user",name:"AbortError"}:serializeError(e),uuid:_nullishCoalesce$b(getErrorProperty(e,"uuid"),()=>p.uuid),parent:_nullishCoalesce$b(getErrorProperty(e,"parent"),()=>p.parent)}),A=FAILURE}finally{process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d)}if(await finishWorkflowAndKillRequest(p),void 0!==o){const e=performance$2.now()-o;i.toolEnd({toolName:s.steps[0].name,success:A===SUCCESS,exitCode:A,durationMs:e,result:{}})}return A};async function finishWorkflowAndKillRequest(e){await e.emitMgmt({id:"bye",traceUrl:e.lfTrace.getTraceUrl()}),
4563
- await e.shutdown()}function hasUnwantedTesslMd(e){return fs__default.existsSync(join(e,"TESSL.md"))?stripIndent`
4561
+ function _nullishCoalesce$b(e,t){return null!=e?e:t()}function _optionalChain$e(e){let t,r=e[0],n=1;for(;n<e.length;){const i=e[n],s=e[n+1];if(n+=2,("optionalAccess"===i||"optionalCall"===i)&&null==r)return;"access"===i||"optionalAccess"===i?(t=r,r=s(r)):"call"!==i&&"optionalCall"!==i||(r=s((...e)=>r.call(t,...e)),t=void 0)}return r}function getErrorProperty(e,t){return e&&"object"==typeof e&&t in e?e[t]:void 0}const executeToolInCli=async e=>{const{toolName:t,params:r,onStart:n,monitoring:{analytics:i},projectDir:s}=e;if("spec-registry"===getExistingFrameworkType(s))throw new ExpectedError("To run this command, you need to install the Tessl framework first. Re-run `tessl init` to install it.");const o=reqSchema.parse({steps:[{name:t,params:r}]});let a;if(1===o.steps.length){a=performance$2.now();const e=o.steps[0],t=builtInTools().every(t=>t.name!==e.name);i.toolStart({toolName:e.name,isAliased:!1,isCustom:t,executionMode:"local",params:_nullishCoalesce$b(e.params,()=>({}))})}
4562
+ const c=e.fsd?void 0:function(e){return openFsd(e)}(e.projectDir),u=c?fsdiff(c):e.fsd,l=_nullishCoalesce$b(_optionalChain$e([c,"optionalAccess",e=>e.root]),()=>e.inputDir);_optionalChain$e([n,"optionalCall",e=>e({fsd:u,req:o})]);const d=new AbortController,p=()=>{d.abort()};process.once("SIGINT",p),process.once("SIGTERM",p);const h=await createCliRequestContext({...e,inputDir:l,fsd:u,req:o},d),A=await bindTools(h.lookupTool,o);for(const{tool:e}of A)checkToolCanRun(e,!0);let f=SUCCESS;try{f=await withHeartbeat(h,d,async e=>executeToolList(A,{rc:h,fsd:u},e))}catch(e){await h.emitMgmt({id:"crash",err:d.signal.aborted?{message:"Operation cancelled by user",name:"AbortError"}:serializeError(e),uuid:_nullishCoalesce$b(getErrorProperty(e,"uuid"),()=>h.uuid),parent:_nullishCoalesce$b(getErrorProperty(e,"parent"),()=>h.parent)}),f=FAILURE}finally{process.removeListener("SIGINT",p),process.removeListener("SIGTERM",p)}if(await finishWorkflowAndKillRequest(h),void 0!==a){
4563
+ const e=performance$2.now()-a;i.toolEnd({toolName:o.steps[0].name,success:f===SUCCESS,exitCode:f,durationMs:e,result:{}})}return f};async function finishWorkflowAndKillRequest(e){await e.emitMgmt({id:"bye",traceUrl:e.lfTrace.getTraceUrl()}),await e.shutdown()}function hasUnwantedTesslMd(e){return fs__default.existsSync(join(e,"TESSL.md"))?stripIndent`
4564
4564
  TESSL.md file found in project directory, which is no longer supported.
4565
4565
 
4566
4566
  To migrate your project, please follow these steps in your project directory:
@@ -4729,11 +4729,11 @@ function wrapLoggerWithEmitter(e,t,r){function n(r,n,i){return e.emit("log",{con
4729
4729
  return null!=e?e:t()}const CLI_PROJECT_GROUP_TYPE="CLI Project";class PosthogAnalytics{__init(){this.toolSessionMap=new Map}constructor(e,t,r,n){PosthogAnalytics.prototype.__init.call(this),this.posthog=e,this.distinctId=t,this.projectCache=n,this.runId=null,this.sessionId="",this.shareUsageData=r,this.cliVersion="unknown",this.osType="unknown",this.osRelease="unknown",this.nodeVersion="unknown",this.platformInfo=_nullishCoalesce(platform$1(),()=>"unknown"),this.archInfo=_nullishCoalesce(arch(),()=>"unknown"),this.projectId=""}async initialize(){this.projectId=await getCurrentProjectId(this.projectCache,this.distinctId);const e=getSysinfo();this.cliVersion=_nullishCoalesce(e.version,()=>"unknown"),this.osType=_nullishCoalesce(e.osImplementation,()=>"unknown"),this.osRelease=_nullishCoalesce(e.osRelease,()=>"unknown"),this.nodeVersion=_nullishCoalesce(e.nodeVersion,()=>"unknown");const t=await SessionManager.getCliSessionInfo();this.sessionId=t.sessionId}static async create(e,t,r,n){
4730
4730
  const i=new PosthogAnalytics(e,t,r,n);return await i.initialize(),i}captureEvent(e,t){this.runId||(this.runId=v4()),this.captureEventBase(e,{source:"cli",runId:this.runId,sessionId:this.sessionId,...t})}captureEventBase(e,t){if(!this.shareUsageData)return;const r={...t,source:"cli",cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease,nodeVersion:this.nodeVersion,platform:this.platformInfo,arch:this.archInfo,timestamp:(new Date).toISOString()};this.posthog.capture({distinctId:this.distinctId,event:e,properties:r,groups:{[CLI_PROJECT_GROUP_TYPE]:this.projectId}})}capture(e,t){this.captureEvent(e,t)}async refreshCliSession(){const e=await SessionManager.getCliSessionInfo();this.sessionId=e.sessionId}mcpServerStart(){this.captureEvent("cli:mcp:server:start",{})}mcpServerEnd(e){this.captureEvent("cli:mcp:server:end",{...e})}async mcpToolStart(e){const t=await SessionManager.getMcpToolInfo();await this.refreshCliSession();const r={...e,runId:t.runId,sessionId:t.sessionId,
4731
4731
  parentRunId:t.parentRunId};return this.captureEventBase("cli:mcp:tool:start",r),t.runId}mcpToolEnd(e){this.captureEventBase("cli:mcp:tool:end",e)}cliStart(e){this.runId=v4(),this.captureEvent("cli:start",e)}runCommand(e,t){this.captureEvent("cli:run",{commandName:e,...t})}getDistinctId(){return this.distinctId}getRunId(){return this.runId}getSessionId(){return this.sessionId}getProjectId(){return this.projectId}runTool(e,t,r){const n=String(e);this.captureEvent("cli:run",{commandName:"tool",toolName:n,params:t,...r})}toolStart(e){const t=`${e.toolName}:${this.runId}`;this.toolSessionMap.set(t,this.sessionId),this.captureEvent("cli:tool:start",e)}toolEnd(e){const t=`${e.toolName}:${this.runId}`,r=this.toolSessionMap.get(t);if(r){const n={...e,originalSessionId:r};this.captureEventBase("cli:tool:end",{source:"cli",runId:this.runId,sessionId:r,...n,timestamp:(new Date).toISOString()}),this.toolSessionMap.delete(t)}else this.captureEvent("cli:tool:end",e)}cliEnd(e){
4732
- this.captureEvent("cli:end",e),this.runId=null}cliError(e){this.captureEvent("cli:error",e)}runHelp(e){this.captureEvent("cli:run",{commandName:"help",...e})}runVersion(e){this.captureEvent("cli:run",{commandName:"version",...e})}init(e){this.captureEvent("cli:project:init",e)}agentSetup(e){this.captureEvent("cli:agent:setup",e)}mcpSetup(e){this.captureEvent("cli:mcp:setup",e)}trackProjectGroup(e){this.shareUsageData&&this.posthog.groupIdentify({groupType:CLI_PROJECT_GROUP_TYPE,groupKey:e.projectId,properties:{customToolCount:e.customToolCount,isInitialized:e.isInitialized,ciCommand:e.ciCommand,$group_set_once:{firstSeenAt:e.firstSeenAt},lastEditedAt:(new Date).toISOString(),nodeVersion:this.nodeVersion,platform:this.platformInfo,arch:this.archInfo,cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease}})}projectMetadata(e){this.captureEventBase("cli:project:metadata",e)}trackProject(e){const t={projectId:this.projectId,...e,nodeVersion:this.nodeVersion,
4733
- platform:this.platformInfo,arch:this.archInfo,cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease,firstSeenAt:(new Date).toISOString(),lastEditedAt:(new Date).toISOString()};this.trackProjectGroup(t),this.projectMetadata(t)}}async function createPosthogAnalytics(e,t,r,n){return PosthogAnalytics.create(e,t,r,n)}async function _asyncNullishCoalesce(e,t){return null!=e?e:await t()}async function startMonitoring(e){const t=getProvisionedEnvPath("production");if(fs__default.existsSync(t))try{validateEnv(cliMonitoringSchema,process.env)}catch(e){e instanceof Error?console.error(formatValidationError(e)):console.error("Failed to validate environment variables: please review the install instructions."),process.exit(FAILURE)}const r=getDefaultGlobalConfigDir(),n=new ConfigManager(join(r,GLOBAL_CONFIG_FILE_NAME),GlobalConfigSchema),{logger:i,logBus:s}=await constructLogger("cli",n),o=await _asyncNullishCoalesce(await n.get("shareUsageData"),async()=>!0);let a,c;try{
4734
- a=(await readAuth(i)).user}catch(e){i.debug({err:e},"failed to read auth")}if(o&&process.env.LANGFUSE_PROXY_TOKEN){const[e,t]=process.env.LANGFUSE_PROXY_TOKEN.split(":");c=quietLangfuse({publicKey:e,secretKey:t,baseUrl:"https://42957.tessl.io/",flushAt:1,flushInterval:0})}else c=quietLangfuse();const u=new PostHog("phc_S8tHJaPxa5ORnP0RVyyTaJHeCcft6XMqfjx9ZlJWvkO",{host:process.env.POSTHOG_HOST||"https://app.posthog.com"});"yes"===process.env.TESSL_DEBUG_MONITORING&&u.debug(!0);const l=userIdentifier(a);setOtelUser(a),u.identify({distinctId:l,properties:{...o?getSysinfo():{},email:a?a.email:void 0}}),a&&u.alias({distinctId:a.id,alias:loggedOutUserIdentifier()});const d=await createPosthogAnalytics(u,l,o,e);return{monitoring:{shareUsageData:o,user:a?{id:a.id,email:a.email}:void 0,langfuse:c,logger:i,logBus:s,reporter:new ReportEmitter,posthogCapture:e=>{o&&u.capture({distinctId:l,event:e.event,properties:e.properties})},analytics:d,shutdown:async()=>{
4735
- i.debug({},"Shutting down monitoring services");const e=async()=>new Promise((e,t)=>setTimeout(()=>t(new Error("Monitoring shutdown timed out")),2e3));try{await Promise.race([u.flush(),e()])}catch(e){i.error({err:e},"Failed to flush PostHog events")}try{await Promise.race([c.flushAsync(),e()]),i.debug({},"Successfully flushed Langfuse events")}catch(e){i.error({err:e},"Failed to flush Langfuse events")}try{await flushLogger(i.originalLogger),i.debug({},"Successfully flushed logger")}catch(e){}}},globalConfig:n}}async function entry(){if(!await checkLegal())return 145;initSysinfo();const e=await checkDeprecationStatusWithCache();if(e)return console.error(e.message),console.error(e.installUrl),DEPRECATED_EXIT_CODE;const t=sessionData(),r=projectCache(),{monitoring:n,globalConfig:i}=await startMonitoring(r);try{return await withSpan("cli.entry",async()=>main(n,i,t,r))}catch(e){return n.logger.error({err:e},"critical error during startup"),n.analytics.cliError({
4736
- command:process.argv.slice(2).join(" "),message:e instanceof Error?e.message:String(e),stack:e instanceof Error&&e.stack||"",expected:e instanceof ExpectedError}),144}finally{await n.shutdown(),await sdk.shutdown(),showCursor()}}entry().then(e=>{process.exit(e)}).catch(e=>{console.error("Error occurred during exit:",e),process.exit(1)});const execAsync=require$$0$b.promisify(require$$0$c.exec);async function getMachineId$4(){try{const e=(await execAsync('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split("\n").find(e=>e.includes("IOPlatformUUID"));if(!e)return;const t=e.split('" = "');if(2===t.length)return t[1].slice(0,-1)}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdDarwin=Object.freeze({__proto__:null,getMachineId:getMachineId$4});async function getMachineId$3(){const e=["/etc/machine-id","/var/lib/dbus/machine-id"];for(const t of e)try{return(await promises.readFile(t,{encoding:"utf8"})).trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}
4737
- var getMachineIdLinux=Object.freeze({__proto__:null,getMachineId:getMachineId$3});async function getMachineId$2(){try{return(await promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}try{return(await execAsync("kenv -q smbios.system.uuid")).stdout.trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdBsd=Object.freeze({__proto__:null,getMachineId:getMachineId$2});async function getMachineId$1(){let e="%windir%\\System32\\REG.exe";"ia32"===process$4.arch&&"PROCESSOR_ARCHITEW6432"in process$4.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{const t=(await execAsync(`${e} QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`)).stdout.split("REG_SZ");if(2===t.length)return t[1].trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdWin=Object.freeze({__proto__:null,getMachineId:getMachineId$1});async function getMachineId(){
4738
- diag.debug("could not read machine-id: unsupported platform")}var getMachineIdUnsupported=Object.freeze({__proto__:null,getMachineId});const getToJsonSchemaFn$4=async()=>e=>e.toJsonSchema();var arktypeCGObzDh=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$4});const getToJsonSchemaFn$3=async()=>{const{JSONSchema:e}=await tryImport(import("effect"),"effect");return t=>e.make(t)};var effectDBSVVF8G=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$3});const getToJsonSchemaFn$2=async()=>{const{toJSONSchema:e}=await tryImport(import("sury"),"sury");return t=>e(t)};var suryGtnkadyM=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$2});const getToJsonSchemaFn$1=async()=>{const{toJsonSchema:e}=await tryImport(import("@valibot/to-json-schema"),"@valibot/to-json-schema");return t=>e(t)};var valibotCbgwcZn_=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$1});const getToJsonSchemaFn=async()=>{let e=e=>{
4739
- throw new Error(`xsschema: Missing zod v4 dependencies "zod". see ${missingDependenciesUrl}`)},t=e=>{throw new Error(`xsschema: Missing zod v3 dependencies "zod-to-json-schema". see ${missingDependenciesUrl}`)};try{const{toJSONSchema:t}=await Promise.resolve().then(function(){return index});e=t}catch(e){e instanceof Error&&console.error(e.message)}try{const{zodToJsonSchema:e}=await Promise.resolve().then(function(){return index$1});t=e}catch(e){e instanceof Error&&console.error(e.message)}return async r=>"_zod"in r?e(r):t(r)};var zodCD8IEU5z=Object.freeze({__proto__:null,getToJsonSchemaFn});export{entry};
4732
+ this.captureEvent("cli:end",e),this.runId=null}cliError(e){this.captureEvent("cli:error",e)}runHelp(e){this.captureEvent("cli:run",{commandName:"help",...e})}specsSearch(e){this.captureEvent("cli:specs:search",e)}runVersion(e){this.captureEvent("cli:run",{commandName:"version",...e})}init(e){this.captureEvent("cli:project:init",e)}agentSetup(e){this.captureEvent("cli:agent:setup",e)}mcpSetup(e){this.captureEvent("cli:mcp:setup",e)}trackProjectGroup(e){this.shareUsageData&&this.posthog.groupIdentify({groupType:CLI_PROJECT_GROUP_TYPE,groupKey:e.projectId,properties:{customToolCount:e.customToolCount,isInitialized:e.isInitialized,ciCommand:e.ciCommand,$group_set_once:{firstSeenAt:e.firstSeenAt},lastEditedAt:(new Date).toISOString(),nodeVersion:this.nodeVersion,platform:this.platformInfo,arch:this.archInfo,cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease}})}projectMetadata(e){this.captureEventBase("cli:project:metadata",e)}trackProject(e){const t={
4733
+ projectId:this.projectId,...e,nodeVersion:this.nodeVersion,platform:this.platformInfo,arch:this.archInfo,cliVersion:this.cliVersion,osType:this.osType,osRelease:this.osRelease,firstSeenAt:(new Date).toISOString(),lastEditedAt:(new Date).toISOString()};this.trackProjectGroup(t),this.projectMetadata(t)}}async function createPosthogAnalytics(e,t,r,n){return PosthogAnalytics.create(e,t,r,n)}async function _asyncNullishCoalesce(e,t){return null!=e?e:await t()}async function startMonitoring(e){const t=getProvisionedEnvPath("production");if(fs__default.existsSync(t))try{validateEnv(cliMonitoringSchema,process.env)}catch(e){e instanceof Error?console.error(formatValidationError(e)):console.error("Failed to validate environment variables: please review the install instructions."),process.exit(FAILURE)}
4734
+ const r=getDefaultGlobalConfigDir(),n=new ConfigManager(join(r,GLOBAL_CONFIG_FILE_NAME),GlobalConfigSchema),{logger:i,logBus:s}=await constructLogger("cli",n),o=await _asyncNullishCoalesce(await n.get("shareUsageData"),async()=>!0);let a,c;try{a=(await readAuth(i)).user}catch(e){i.debug({err:e},"failed to read auth")}if(o&&process.env.LANGFUSE_PROXY_TOKEN){const[e,t]=process.env.LANGFUSE_PROXY_TOKEN.split(":");c=quietLangfuse({publicKey:e,secretKey:t,baseUrl:"https://42957.tessl.io/",flushAt:1,flushInterval:0})}else c=quietLangfuse();const u=new PostHog("phc_S8tHJaPxa5ORnP0RVyyTaJHeCcft6XMqfjx9ZlJWvkO",{host:process.env.POSTHOG_HOST||"https://app.posthog.com"});"yes"===process.env.TESSL_DEBUG_MONITORING&&u.debug(!0);const l=userIdentifier(a);setOtelUser(a),u.identify({distinctId:l,properties:{...o?getSysinfo():{},email:a?a.email:void 0}}),a&&u.alias({distinctId:a.id,alias:loggedOutUserIdentifier()});const d=await createPosthogAnalytics(u,l,o,e);return{monitoring:{shareUsageData:o,
4735
+ user:a?{id:a.id,email:a.email}:void 0,langfuse:c,logger:i,logBus:s,reporter:new ReportEmitter,posthogCapture:e=>{o&&u.capture({distinctId:l,event:e.event,properties:e.properties})},analytics:d,shutdown:async()=>{i.debug({},"Shutting down monitoring services");const e=async()=>new Promise((e,t)=>setTimeout(()=>t(new Error("Monitoring shutdown timed out")),2e3));try{await Promise.race([u.flush(),e()])}catch(e){i.error({err:e},"Failed to flush PostHog events")}try{await Promise.race([c.flushAsync(),e()]),i.debug({},"Successfully flushed Langfuse events")}catch(e){i.error({err:e},"Failed to flush Langfuse events")}try{await flushLogger(i.originalLogger),i.debug({},"Successfully flushed logger")}catch(e){}}},globalConfig:n}}async function entry(){if(!await checkLegal())return 145;initSysinfo();const e=await checkDeprecationStatusWithCache();if(e)return console.error(e.message),console.error(e.installUrl),DEPRECATED_EXIT_CODE
4736
+ ;const t=sessionData(),r=projectCache(),{monitoring:n,globalConfig:i}=await startMonitoring(r);try{return await withSpan("cli.entry",async()=>main(n,i,t,r))}catch(e){return n.logger.error({err:e},"critical error during startup"),n.analytics.cliError({command:process.argv.slice(2).join(" "),message:e instanceof Error?e.message:String(e),stack:e instanceof Error&&e.stack||"",expected:e instanceof ExpectedError}),144}finally{await n.shutdown(),await sdk.shutdown(),showCursor()}}entry().then(e=>{process.exit(e)}).catch(e=>{console.error("Error occurred during exit:",e),process.exit(1)});const execAsync=require$$0$b.promisify(require$$0$c.exec);async function getMachineId$4(){try{const e=(await execAsync('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split("\n").find(e=>e.includes("IOPlatformUUID"));if(!e)return;const t=e.split('" = "');if(2===t.length)return t[1].slice(0,-1)}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdDarwin=Object.freeze({__proto__:null,
4737
+ getMachineId:getMachineId$4});async function getMachineId$3(){const e=["/etc/machine-id","/var/lib/dbus/machine-id"];for(const t of e)try{return(await promises.readFile(t,{encoding:"utf8"})).trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdLinux=Object.freeze({__proto__:null,getMachineId:getMachineId$3});async function getMachineId$2(){try{return(await promises.readFile("/etc/hostid",{encoding:"utf8"})).trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}try{return(await execAsync("kenv -q smbios.system.uuid")).stdout.trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdBsd=Object.freeze({__proto__:null,getMachineId:getMachineId$2});async function getMachineId$1(){let e="%windir%\\System32\\REG.exe";"ia32"===process$4.arch&&"PROCESSOR_ARCHITEW6432"in process$4.env&&(e="%windir%\\sysnative\\cmd.exe /c "+e);try{
4738
+ const t=(await execAsync(`${e} QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid`)).stdout.split("REG_SZ");if(2===t.length)return t[1].trim()}catch(e){diag.debug(`error reading machine id: ${e}`)}}var getMachineIdWin=Object.freeze({__proto__:null,getMachineId:getMachineId$1});async function getMachineId(){diag.debug("could not read machine-id: unsupported platform")}var getMachineIdUnsupported=Object.freeze({__proto__:null,getMachineId});const getToJsonSchemaFn$4=async()=>e=>e.toJsonSchema();var arktypeCGObzDh=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$4});const getToJsonSchemaFn$3=async()=>{const{JSONSchema:e}=await tryImport(import("effect"),"effect");return t=>e.make(t)};var effectDBSVVF8G=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$3});const getToJsonSchemaFn$2=async()=>{const{toJSONSchema:e}=await tryImport(import("sury"),"sury");return t=>e(t)};var suryGtnkadyM=Object.freeze({__proto__:null,
4739
+ getToJsonSchemaFn:getToJsonSchemaFn$2});const getToJsonSchemaFn$1=async()=>{const{toJsonSchema:e}=await tryImport(import("@valibot/to-json-schema"),"@valibot/to-json-schema");return t=>e(t)};var valibotCbgwcZn_=Object.freeze({__proto__:null,getToJsonSchemaFn:getToJsonSchemaFn$1});const getToJsonSchemaFn=async()=>{let e=e=>{throw new Error(`xsschema: Missing zod v4 dependencies "zod". see ${missingDependenciesUrl}`)},t=e=>{throw new Error(`xsschema: Missing zod v3 dependencies "zod-to-json-schema". see ${missingDependenciesUrl}`)};try{const{toJSONSchema:t}=await Promise.resolve().then(function(){return index});e=t}catch(e){e instanceof Error&&console.error(e.message)}try{const{zodToJsonSchema:e}=await Promise.resolve().then(function(){return index$1});t=e}catch(e){e instanceof Error&&console.error(e.message)}return async r=>"_zod"in r?e(r):t(r)};var zodCD8IEU5z=Object.freeze({__proto__:null,getToJsonSchemaFn});export{entry};