@turbobase/cli 1.1.19 → 1.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/turbobase-standalone.mjs +358 -166
- package/dist/turbobase.js +337 -145
- package/package.json +1 -1
package/dist/turbobase.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __tbCreateRequire } from 'node:module';
|
|
3
3
|
const require = __tbCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
4
|
+
var ly=Object.create;var pi=Object.defineProperty;var cy=Object.getOwnPropertyDescriptor;var dy=Object.getOwnPropertyNames;var uy=Object.getPrototypeOf,py=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ud=(t,e)=>{for(var n in e)pi(t,n,{get:e[n],enumerable:!0})},fy=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dy(e))!py.call(t,s)&&s!==n&&pi(t,s,{get:()=>e[s],enumerable:!(r=cy(e,s))||r.enumerable});return t};var pd=(t,e,n)=>(n=t!=null?ly(uy(t)):{},fy(e||!t||!t.__esModule?pi(n,"default",{value:t,enumerable:!0}):n,t));function ar(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var ms=j(()=>{});import{z as nn}from"zod";function gs(t){let e=fi.safeParse(t);return e.success?(e.data.inputs??[]).filter(n=>n.type==="connection"):[]}function hi(t,e){let n=fi.safeParse(t);if(!n.success)throw new Lt(`invalid manifest: ${n.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);if(fd.test(e))throw new Lt('a literal connection_id is baked into the bundle source \u2014 connection binding is an install-time input, not a published value. Declare an inputs[] entry { type: "connection", source_system } instead.');let r=JSON.stringify(n.data);if(fd.test(r))throw new Lt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var hd,md,fi,Lt,fd,gd=j(()=>{hd=nn.object({type:nn.literal("connection"),source_system:nn.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:nn.string().min(1).max(200).optional()}),md=nn.discriminatedUnion("type",[hd]),fi=nn.object({inputs:nn.array(md).optional()}).passthrough(),Lt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};fd=/\bconnection[_-]?id\b["']?\s*[:=]/i});var ys,mi=j(()=>{ys=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Ue}from"zod";var gi,yd,bd=j(()=>{ms();mi();gi=Ue.object({id:Ue.string().min(1,"hook id must be non-empty"),recordType:Ue.union([Ue.string().min(1),Ue.array(Ue.string().min(1)).min(1),Ue.literal("*")]),event:Ue.enum(ys),source:Ue.string().min(1).optional(),when:Ue.unknown().optional(),run:Ue.unknown(),failClosed:Ue.boolean().optional(),timeoutMs:Ue.number().int().positive().optional(),description:Ue.string().optional(),systemReserved:Ue.boolean().optional()}).superRefine((t,e)=>{typeof t.run!="function"&&e.addIssue({code:"custom",path:["run"],message:"run must be a function"}),"when"in t&&t.when!==void 0&&typeof t.when!="function"&&e.addIssue({code:"custom",path:["when"],message:"when, when present, must be a function"})}),yd=ar({kind:"hook",schema:gi,factoryName:"defineHook"})});var wd=j(()=>{bd();mi()});var bs,yi=j(()=>{bs=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as Re}from"zod";var bi,vd,kd=j(()=>{ms();yi();bi=Re.object({id:Re.string().min(1,"conduit id must be non-empty"),on:Re.enum(bs),from:Re.object({source:Re.string().min(1,"from.source must be non-empty"),recordType:Re.string().min(1,"from.recordType must be non-empty"),when:Re.unknown().optional()}),to:Re.object({source:Re.string().min(1,"to.source must be non-empty"),recordType:Re.string().min(1,"to.recordType must be non-empty")}),mode:Re.enum(["dual-bind","one-shot"]).optional(),transform:Re.unknown(),idempotencyKey:Re.unknown().optional(),cycleBudget:Re.number().int().positive().optional(),conflictStrategy:Re.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:Re.number().int().positive().optional(),description:Re.string().optional(),systemReserved:Re.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let n=t.from?.when;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let r=t.idempotencyKey;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let s=t.from,o=t.to;s?.source&&o?.source&&s.source===o.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),vd=ar({kind:"conduit",schema:bi,factoryName:"defineConduit"})});var Sd=j(()=>{kd();yi()});async function by(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let n=await e.default(t,{defaultNonNullable:!1});return e.astToString(n)}async function ws(t,e={}){return(e.transform??by)(t)}var wi=j(()=>{});function vi(t){switch(t.toLowerCase().trim()){case"boolean":return"boolean";case"smallint":case"integer":case"bigint":case"numeric":case"decimal":case"real":case"double precision":return"number";case"text":case"character varying":case"character":case"varchar":case"char":case"uuid":case"name":case"citext":return"string";case"timestamp with time zone":case"timestamp without time zone":case"timestamp":case"date":case"time":case"time with time zone":case"time without time zone":return"string";case"json":case"jsonb":return"unknown";case"array":return"unknown[]";default:return"unknown"}}function _d(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function ki(t){return`${_d(t.source)}${_d(t.recordType)}`}function wy(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function vy(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function Si(t){let e=ki(t),n=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&n.push(t.description);let r=n.length===1?`/** ${n[0]} */`:`/**
|
|
5
5
|
* ${n.join(`
|
|
6
6
|
* `)}
|
|
7
7
|
*/`;if(t.columns.length===0)return`${r}
|
|
8
8
|
export interface ${e} {
|
|
9
9
|
// no columns introspected
|
|
10
10
|
[key: string]: unknown;
|
|
11
|
-
}`;let s=t.columns.map(o=>{let i=
|
|
12
|
-
${
|
|
11
|
+
}`;let s=t.columns.map(o=>{let i=vi(o.pgType),a=o.nullable?"?":"",l=o.nullable?" | null":"";return` /** ${vy(o)} */
|
|
12
|
+
${wy(o.name)}${a}: ${i}${l};`});return`${r}
|
|
13
13
|
export interface ${e} {
|
|
14
14
|
${s.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}function
|
|
16
|
+
}`}function vs(t){return[...t.records].sort((r,s)=>`${r.source}:${r.recordType}`.localeCompare(`${s.source}:${s.recordType}`)).map(Si).join(`
|
|
17
17
|
|
|
18
|
-
`)}function
|
|
19
|
-
`)}var
|
|
18
|
+
`)}function $d(t){let e=new Map,n=(s,o)=>{let i=e.get(s);i||e.set(s,i=new Map);for(let a of o)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let s of t.records){s.table&&n(s.table,s.columns);for(let o of s.lines??[])n(o.table,o.columns)}let r={};for(let[s,o]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>o.get(a)===!1);if(o.get("parent_pg_row_id")===!1&&i){r[s]=["parent_pg_row_id",i];continue}if(o.get("pg_row_id")===!1){r[s]="pg_row_id";continue}if(o.get("external_id")===!1){r[s]="external_id";continue}}return r}function ky(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function _i(t){let e=$d(t);return["/**"," * The seek key each table can be keyset-paged on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([r,s])=>{let o=Array.isArray(s)?`[${s.map(i=>`'${i}'`).join(", ")}]`:`'${s}'`;return` ${ky(r)}: ${o},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
|
|
19
|
+
`)}var $i=j(()=>{});function Sy(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function xd(t,e,n){let r=await n(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!r.ok)throw new Error(`types-gen: GET ${t} failed (${r.status} ${r.statusText})`);return r.json()}async function Dt(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let n=Sy(t.baseUrl),r=await xd(n.records,t.token,e);if(!r||!Array.isArray(r.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let s=vs(r),o=[_y,"// ----- Record shapes (from /v1/catalog/records) -----",s,"// ----- Keyset seek keys (derived from column nullability) -----",_i(r)];if(!t.recordsOnly){let i=await xd(n.openapi,t.token,e),a=await ws(i,t.openApi);o.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return o.join(`
|
|
20
20
|
|
|
21
21
|
`)+`
|
|
22
|
-
`}var
|
|
23
|
-
`)});var
|
|
24
|
-
`,{mode:384})}async function ku(t){let e=Qe(t.baseUrl),n=await ar(),r=new Date().toISOString();return n.tenants[e]={token:t.token,updatedAt:r},n.active=e,await vi(n),{baseUrl:e,token:t.token,updatedAt:r}}async function ut(t){let e=await ar();if(t){let o=Qe(t),i=e.tenants[o];return i?{baseUrl:o,token:i.token,updatedAt:i.updatedAt}:null}let n=Object.keys(e.tenants),r=e.active&&e.tenants[e.active]?e.active:n.length===1?n[0]:void 0;if(!r)return null;let s=e.tenants[r];return{baseUrl:r,token:s.token,updatedAt:s.updatedAt}}async function vs(t){let e=Qe(t),n=await ar(),r=n.tenants[e];return r?(n.active=e,await vi(n),{baseUrl:e,token:r.token,updatedAt:r.updatedAt}):null}async function ki(t){let e=await ar(),n=t?Qe(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!n||!e.tenants[n])return null;if(delete e.tenants[n],e.active===n){let r=Object.keys(e.tenants);e.active=r.length===1?r[0]:void 0}return await vi(e),n}async function xt(){let t=await ar();return Object.entries(t.tenants).map(([e,n])=>({baseUrl:e,token:n.token,updatedAt:n.updatedAt}))}var lr=j(()=>{});function Su(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,n=typeof e.message=="string"&&e.message?e.message:e.error;return typeof n=="string"?n.trim().slice(0,200):""}function _u(t){return t.replace(/\/+$/,"")}function Si(t=process.env){let e=(t[wn]??"").trim(),n=(t[ks]??"").trim();return!e||!n?null:{registryUrl:e,token:n}}function _i(t){let e;try{e=new URL(t)}catch{return`${wn} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&n?null:`${wn} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var ne,F,wn,ks,cr,jt=j(()=>{ne=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="ApiError"}status;body};F=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=_u(e.baseUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=n}async request(e,n,r,s){let o=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...r!==void 0?{"Content-Type":"application/json"}:{},...s??{}},...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Su(a);throw new ne(`${e} ${n} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let n=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${n}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async logs(e,n){let r=n&&n>0?`?limit=${Math.floor(n)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${r}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.limit&&n.limit>0&&r.set("limit",String(Math.floor(n.limit)));let s=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${s}`)).events??[]}async bindings(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/bindings${r}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,n,r={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:n,...r.note?{note:r.note}:{},...r.meta?{meta:r.meta}:{}},r.proposalId?{"x-proposal-id":r.proposalId}:void 0)}learningsPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.section&&n.set("section",e.section),e.limit!==void 0&&n.set("limit",String(e.limit)),e.group===!1&&n.set("group","false");let r=n.toString();return this.request("GET",`/v1/learnings/pending${r?`?${r}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.limit!==void 0&&n.set("limit",String(e.limit)),e.group===!1&&n.set("group","false"),e.reapply&&n.set("reapply","true");let r=n.toString();return this.request("GET",`/v1/learnings/rules-pending${r?`?${r}`:""}`)}rulesPush(e,n={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...n.app?{app:n.app}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.group===!1?{group:!1}:{},...n.reapply?{reapply:!0}:{}})}skillsList(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status);let r=n.toString();return this.request("GET",`/v1/skills${r?`?${r}`:""}`)}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status);let r=n.toString();return this.request("GET",`/v1/docs${r?`?${r}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,n={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...n.app?{app:n.app}:{},...n.section?{section:n.section}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e){return this.request("POST","/v1/config/apply",{bundle:e})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,n){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(n)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,n){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,n)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,n){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:n.files,target:n.target,...n.approvedBy?{approvedBy:n.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},wn="TURBOBASE_REGISTRY_URL",ks="TURBOBASE_REGISTRY_TOKEN";cr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=_u(e.registryUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=n}async request(e,n,r){let s={Authorization:`Bearer ${this.token}`,Accept:"application/json"};r!==void 0&&(s["Content-Type"]="application/json");let o=await this.fetchImpl(`${this.registryUrl}${n}`,{method:e,headers:s,...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Su(a);throw new ne(`${e} ${n} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,n){let r=n?`?version=${encodeURIComponent(n)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${r}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function cb(t){if(lb.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function db(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:cb(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||fb(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:ub,loader:"js"}))}}}function fb(t){let e=t.startsWith("node:")?t.slice(5):t;return pb.has(e.split("/")[0])}function $u(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function hb(){try{return(await import("esbuild")).build}catch(t){throw $u("esbuild",t)}}async function mb(){try{return(await import("isolated-vm")).default}catch(t){throw $u("isolated-vm",t)}}async function Ss(t){let e=await hb(),n;try{n=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[db()]})}catch(r){let o=r.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new $i(o||`extension bundle failed: ${String(r)}`)}return n.outputFiles?.[0]?.text??""}async function ur(t,e,n={}){let r=n.timeoutMs??200,s=n.memoryLimitMb??16,o=n.member??"run",i={patches:[],logs:[]},a=await mb(),l=new a.Isolate({memoryLimit:s});try{let d=await l.createContext(),p=d.global,h=new a.Callback(I=>{let D=JSON.parse(String(I));i.rejection||(i.rejection=D)}),_=new a.Callback(I=>{i.patches.push(JSON.parse(String(I)))}),y=new a.Callback(I=>{let D=JSON.parse(String(I));i.logs.push(D)}),w=new a.Callback(I=>{i.result=JSON.parse(String(I))});await p.set("__tb_reject",h),await p.set("__tb_patch",_),await p.set("__tb_log",y),await p.set("__tb_result",w),await p.set("__tb_ctx_json",JSON.stringify(gb(e)));let T=bb(t,o),P=await(await l.compileScript(T)).run(d,{timeout:r,promise:!0});return o==="when"?{effects:i,whenResult:!!P}:{effects:i}}finally{l.isDisposed||l.dispose()}}function gb(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function bb(t,e){return`
|
|
22
|
+
`}var _y,Rd=j(()=>{wi();$i();$i();wi();_y=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
|
|
23
|
+
`)});var xi=j(()=>{ms();gd();wd();Sd();Rd()});import{homedir as $y}from"node:os";import{join as Td}from"node:path";import{promises as Ri}from"node:fs";function Xe(t){return t.trim().replace(/\/+$/,"")}function ks(){let t=process.env.TURBOBASE_HOME??Td($y(),".turbobase");return{dir:t,file:Td(t,"credentials")}}function Ed(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function lr(){let{file:t}=ks(),e;try{let o=await Ri.readFile(t,"utf8");e=JSON.parse(o)}catch(o){if(o.code==="ENOENT")return{tenants:{}};throw o}if(!e||typeof e!="object")return{tenants:{}};let n=e;if(n.tenants&&typeof n.tenants=="object"){let o={};for(let[a,l]of Object.entries(n.tenants))Ed(l)&&(o[a]={token:l.token,updatedAt:l.updatedAt});return{active:typeof n.active=="string"&&o[n.active]?n.active:void 0,tenants:o}}let r={};for(let[o,i]of Object.entries(n))Ed(i)&&(r[o]={token:i.token,updatedAt:i.updatedAt});return{active:xy(r),tenants:r}}function xy(t){let e,n="";for(let[r,s]of Object.entries(t))(!e||String(s.updatedAt)>n)&&(e=r,n=String(s.updatedAt));return e}async function Ti(t){let{dir:e,file:n}=ks();await Ri.mkdir(e,{recursive:!0,mode:448}),await Ri.writeFile(n,JSON.stringify(t,null,2)+`
|
|
24
|
+
`,{mode:384})}async function Pd(t){let e=Xe(t.baseUrl),n=await lr(),r=new Date().toISOString();return n.tenants[e]={token:t.token,updatedAt:r},n.active=e,await Ti(n),{baseUrl:e,token:t.token,updatedAt:r}}async function ut(t){let e=await lr();if(t){let o=Xe(t),i=e.tenants[o];return i?{baseUrl:o,token:i.token,updatedAt:i.updatedAt}:null}let n=Object.keys(e.tenants),r=e.active&&e.tenants[e.active]?e.active:n.length===1?n[0]:void 0;if(!r)return null;let s=e.tenants[r];return{baseUrl:r,token:s.token,updatedAt:s.updatedAt}}async function Ss(t){let e=Xe(t),n=await lr(),r=n.tenants[e];return r?(n.active=e,await Ti(n),{baseUrl:e,token:r.token,updatedAt:r.updatedAt}):null}async function Ei(t){let e=await lr(),n=t?Xe(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!n||!e.tenants[n])return null;if(delete e.tenants[n],e.active===n){let r=Object.keys(e.tenants);e.active=r.length===1?r[0]:void 0}return await Ti(e),n}async function Rt(){let t=await lr();return Object.entries(t.tenants).map(([e,n])=>({baseUrl:e,token:n.token,updatedAt:n.updatedAt}))}var cr=j(()=>{});function Ad(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,n=typeof e.message=="string"&&e.message?e.message:e.error;return typeof n=="string"?n.trim().slice(0,200):""}function Id(t){return t.replace(/\/+$/,"")}function Pi(t=process.env){let e=(t[vn]??"").trim(),n=(t[_s]??"").trim();return!e||!n?null:{registryUrl:e,token:n}}function Ai(t){let e;try{e=new URL(t)}catch{return`${vn} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&n?null:`${vn} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var X,B,vn,_s,dr,Tt=j(()=>{X=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="ApiError"}status;body};B=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Id(e.baseUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=n}async request(e,n,r,s){let o=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...r!==void 0?{"Content-Type":"application/json"}:{},...s??{}},...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Ad(a);throw new X(`${e} ${n} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let n=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${n}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async proposals(e={}){let n=new URLSearchParams;e.status?.length&&n.set("status",e.status.join(",")),e.provenance?.length&&n.set("provenance",e.provenance.join(",")),e.recordType&&n.set("recordType",e.recordType),e.source&&n.set("source",e.source),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString();return(await this.request("GET",`/v1/extensions/proposals${r?`?${r}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,n){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,n?{reason:n}:{})}async logs(e,n){let r=n&&n>0?`?limit=${Math.floor(n)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${r}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.limit&&n.limit>0&&r.set("limit",String(Math.floor(n.limit)));let s=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${s}`)).events??[]}async bindings(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/bindings${r}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,n,r={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:n,...r.note?{note:r.note}:{},...r.meta?{meta:r.meta}:{}},r.proposalId?{"x-proposal-id":r.proposalId}:void 0)}learningsPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.section&&n.set("section",e.section),e.limit!==void 0&&n.set("limit",String(e.limit)),e.group===!1&&n.set("group","false");let r=n.toString();return this.request("GET",`/v1/learnings/pending${r?`?${r}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.limit!==void 0&&n.set("limit",String(e.limit)),e.group===!1&&n.set("group","false"),e.reapply&&n.set("reapply","true");let r=n.toString();return this.request("GET",`/v1/learnings/rules-pending${r?`?${r}`:""}`)}rulesPush(e,n={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...n.app?{app:n.app}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.group===!1?{group:!1}:{},...n.reapply?{reapply:!0}:{}})}skillsList(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status);let r=n.toString();return this.request("GET",`/v1/skills${r?`?${r}`:""}`)}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status);let r=n.toString();return this.request("GET",`/v1/docs${r?`?${r}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,n={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...n.app?{app:n.app}:{},...n.section?{section:n.section}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e){return this.request("POST","/v1/config/apply",{bundle:e})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,n){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(n)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,n){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,n)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,n){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:n.files,target:n.target,...n.approvedBy?{approvedBy:n.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},vn="TURBOBASE_REGISTRY_URL",_s="TURBOBASE_REGISTRY_TOKEN";dr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Id(e.registryUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=n}async request(e,n,r){let s={Authorization:`Bearer ${this.token}`,Accept:"application/json"};r!==void 0&&(s["Content-Type"]="application/json");let o=await this.fetchImpl(`${this.registryUrl}${n}`,{method:e,headers:s,...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Ad(a);throw new X(`${e} ${n} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,n){let r=n?`?version=${encodeURIComponent(n)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${r}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function Ty(t){if(Ry.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Py(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:Ty(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||Iy(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:Ey,loader:"js"}))}}}function Iy(t){let e=t.startsWith("node:")?t.slice(5):t;return Ay.has(e.split("/")[0])}function Cd(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function Cy(){try{return(await import("esbuild")).build}catch(t){throw Cd("esbuild",t)}}async function Oy(){try{return(await import("isolated-vm")).default}catch(t){throw Cd("isolated-vm",t)}}async function $s(t){let e=await Cy(),n;try{n=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[Py()]})}catch(r){let o=r.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new Ii(o||`extension bundle failed: ${String(r)}`)}return n.outputFiles?.[0]?.text??""}async function ur(t,e,n={}){let r=n.timeoutMs??200,s=n.memoryLimitMb??16,o=n.member??"run",i={patches:[],logs:[]},a=await Oy(),l=new a.Isolate({memoryLimit:s});try{let p=await l.createContext(),u=p.global,m=new a.Callback(I=>{let U=JSON.parse(String(I));i.rejection||(i.rejection=U)}),x=new a.Callback(I=>{i.patches.push(JSON.parse(String(I)))}),v=new a.Callback(I=>{let U=JSON.parse(String(I));i.logs.push(U)}),k=new a.Callback(I=>{i.result=JSON.parse(String(I))});await u.set("__tb_reject",m),await u.set("__tb_patch",x),await u.set("__tb_log",v),await u.set("__tb_result",k),await u.set("__tb_ctx_json",JSON.stringify(Ny(e)));let R=jy(t,o),P=await(await l.compileScript(R)).run(p,{timeout:r,promise:!0});return o==="when"?{effects:i,whenResult:!!P}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Ny(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function jy(t,e){return`
|
|
25
25
|
"use strict";
|
|
26
26
|
(async () => {
|
|
27
27
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -90,36 +90,36 @@ ${s.join(`
|
|
|
90
90
|
${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
|
|
91
91
|
return ${e==="when"?"out":"undefined"};
|
|
92
92
|
})()
|
|
93
|
-
`}var
|
|
93
|
+
`}var Ry,Ey,Ii,Ay,Ci=j(()=>{Ry=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);Ey=`
|
|
94
94
|
export const defineHook = (def) => def;
|
|
95
95
|
export const defineConduit = (def) => def;
|
|
96
96
|
export default defineHook;
|
|
97
|
-
|
|
97
|
+
`,Ii=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};Ay=new Set(["assert","buffer","child_process","cluster","crypto","dns","events","fs","http","http2","https","net","os","path","process","querystring","readline","stream","string_decoder","timers","tls","tty","url","util","v8","vm","worker_threads","zlib"])});import{promises as Oi}from"node:fs";import{join as Ly}from"node:path";function Dy(t){return{recordType:t.recordType??"unknown",event:t.event??"before_save",direction:t.direction??"standalone",origin:t.origin??"user",source:t.source??null,payload:t.payload??{},prior:t.prior,user:t.user,tenantConfig:t.tenantConfig??{},metadata:t.metadata}}async function Uy(t,e,n){let r=e.name??n,s=e.expect??"pass";try{let{effects:o}=await ur(t,Dy(e.context)),i=o.rejection?"reject":"pass";return{name:r,expected:s,observed:i,pass:i===s,rejection:o.rejection,patchCount:o.patches.length}}catch(o){return{name:r,expected:s,observed:"pass",pass:!1,patchCount:0,error:o instanceof Error?o.message:String(o)}}}async function xs(t,e){let n=await $s(t),r=[];for(let s=0;s<e.length;s+=1)r.push(await Uy(n,e[s],`sample[${s}]`));return r}async function pr(t){let e;try{e=await Oi.readdir(t)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of e.sort()){if(!r.endsWith(".json"))continue;let s=await Oi.readFile(Ly(t,r),"utf8"),o=JSON.parse(s),i=Array.isArray(o)?o:[o];for(let a=0;a<i.length;a+=1){let l=i[a];n.push({file:r,fixture:{...l,name:l.name??`${r}${i.length>1?`#${a}`:""}`}})}}return n}function fr(t){return Oi.readFile(t,"utf8")}var Ni=j(()=>{Ci()});function qt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function mb(t){let e=t.recordType;if(!e)throw new rt("record type is required (e.g. --record=salesOrder)");let n=t.event??"before_save",r=t.template??"require-field",s=t.source,o=s?`
|
|
98
98
|
source: ${JSON.stringify(s)},`:"",i,a;if(r==="blank")i=`
|
|
99
99
|
run: (ctx) => {
|
|
100
100
|
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
101
101
|
// with ctx.patch({...}); observe with ctx.log('info', '...').
|
|
102
|
-
},`,a="custom";else if(r==="require-field"){let
|
|
102
|
+
},`,a="custom";else if(r==="require-field"){let x=t.field;if(!x)throw new rt("require-field template needs --field=<name>");i=`
|
|
103
103
|
run: (ctx) => {
|
|
104
|
-
const v = ctx.payload[${JSON.stringify(
|
|
104
|
+
const v = ctx.payload[${JSON.stringify(x)}];
|
|
105
105
|
if (v === undefined || v === null || v === '') {
|
|
106
106
|
ctx.reject({
|
|
107
107
|
code: 'MANDATORY_FIELD_MISSING',
|
|
108
|
-
field: ${JSON.stringify(
|
|
109
|
-
message: ${JSON.stringify(`${
|
|
108
|
+
field: ${JSON.stringify(x)},
|
|
109
|
+
message: ${JSON.stringify(`${x} is required`)},
|
|
110
110
|
});
|
|
111
111
|
}
|
|
112
|
-
},`,a=`require-field-${
|
|
112
|
+
},`,a=`require-field-${x}`}else if(r==="enforce-format"){let x=t.field;if(!x)throw new rt("enforce-format template needs --field=<name>");if(!t.regex)throw new rt("enforce-format template needs --regex=<pattern>");i=`
|
|
113
113
|
run: (ctx) => {
|
|
114
|
-
const v = ctx.payload[${JSON.stringify(
|
|
114
|
+
const v = ctx.payload[${JSON.stringify(x)}];
|
|
115
115
|
if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
|
|
116
116
|
ctx.reject({
|
|
117
117
|
code: 'INVALID_FORMAT',
|
|
118
|
-
field: ${JSON.stringify(
|
|
119
|
-
message: ${JSON.stringify(`${
|
|
118
|
+
field: ${JSON.stringify(x)},
|
|
119
|
+
message: ${JSON.stringify(`${x} does not match expected format`)},
|
|
120
120
|
});
|
|
121
121
|
}
|
|
122
|
-
},`,a=`enforce-format-${
|
|
122
|
+
},`,a=`enforce-format-${x}`}else throw new rt(`unsupported template: ${r}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${qt(t.regex).slice(0,24)}`:""}`,u=`/**
|
|
123
123
|
* ${t.description??`${a} on ${e}.${n}`}
|
|
124
124
|
*
|
|
125
125
|
* Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
|
|
@@ -132,7 +132,7 @@ export default defineHook<Record<string, unknown>>({
|
|
|
132
132
|
recordType: ${JSON.stringify(e)},
|
|
133
133
|
event: ${JSON.stringify(n)},${o}${i}
|
|
134
134
|
});
|
|
135
|
-
`;return{relativePath:`hooks/${e}/${n}.${a}.ts`,content:
|
|
135
|
+
`;return{relativePath:`hooks/${e}/${n}.${a}.ts`,content:u}}function gb(t){let e=t.recordType;if(!e)throw new rt("record type is required (e.g. --record=order)");let n=t.source;if(!n)throw new rt("--source is required (the origin source, e.g. --source=shopify)");let r=t.to;if(!r)throw new rt("--to is required (the target source, e.g. --to=netsuite)");if(n===r)throw new rt(`a conduit must bridge two DIFFERENT sources (got --source=${n} --to=${r}); use \`turbobase ext new hook\` for an intra-source transform`);let s=t.toRecordType??e,o=t.event??"after_canonicalize_inbound",i=t.id??`${qt(n)}2${qt(r)}:${qt(e)}`,l=`/**
|
|
136
136
|
* ${t.description??`Bridge ${n} ${e} \u2192 ${r} ${s} (${o}).`}
|
|
137
137
|
*
|
|
138
138
|
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
@@ -175,7 +175,7 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
175
175
|
},
|
|
176
176
|
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
177
177
|
});
|
|
178
|
-
`;return{relativePath:`conduits/${
|
|
178
|
+
`;return{relativePath:`conduits/${qt(n)}-${qt(e)}-to-${qt(r)}-${qt(s)}.ts`,content:l}}function Mt(t,e){let n=yb[t];if(!n)throw new rt(`unknown extension kind '${t}'. Scaffoldable kinds: ${ru.join(", ")}.`);return n(e)}var ru,rt,yb,Ps=j(()=>{ru=["hook","conduit"];rt=class extends Error{};yb={hook:mb,conduit:gb}});function av(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e>>>0}function lv(t){return dp[av(t)%dp.length]}function cv(t){let e=t.trim().split(/[\s\-_.]+/).filter(n=>/[a-z0-9]/i.test(n));return e.length===0?t.trim().slice(0,1).toUpperCase()||"\u2022":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase()}function up(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function pp(t,e){let[n,r]=lv(t),s=up(cv(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${up(e)}">
|
|
179
179
|
<defs>
|
|
180
180
|
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
181
181
|
<stop offset="0" stop-color="${n}"/>
|
|
@@ -185,9 +185,9 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
185
185
|
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
186
186
|
<text x="32" y="34" text-anchor="middle" dominant-baseline="central" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="26" font-weight="600" fill="#ffffff">${s}</text>
|
|
187
187
|
</svg>
|
|
188
|
-
`}var
|
|
189
|
-
`}function
|
|
190
|
-
`}function
|
|
188
|
+
`}var dp,fp=j(()=>{dp=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var hp,mp=j(()=>{hp=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var _p={};ud(_p,{MAIN_TSX:()=>kp,STYLES_CSS:()=>Sp,TSCONFIG:()=>wp,TURBOBASE_CLIENT:()=>gp,indexHtml:()=>vp,instanceOriginFromEnv:()=>gv,packageJson:()=>yp,scaffoldAppFiles:()=>bv,starterApp:()=>wv,viteConfig:()=>bp});function uv(t){let e={name:t.title},n=(t.description??"").trim().slice(0,dv);return n&&(e.description=n),e.icon="favicon.svg",e.learnings={...hp},JSON.stringify(e,null,2)+`
|
|
189
|
+
`}function yp(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:pv},dependencies:{react:"^18.3.1","react-dom":"^18.3.1"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
|
|
190
|
+
`}function mv(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}function gv(t=process.env){let e=(t.TENANT_SLUG??"").trim(),n=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!n))return`https://${e}.${n}`}function bp(t,e={}){let n=mv(e.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
191
191
|
import react from '@vitejs/plugin-react';
|
|
192
192
|
|
|
193
193
|
// A same-origin static SPA served at /a/${t}. \`base\` MUST match that mount
|
|
@@ -201,8 +201,8 @@ import react from '@vitejs/plugin-react';
|
|
|
201
201
|
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
202
202
|
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
203
203
|
// them at boot; restart the dev server after changing one).
|
|
204
|
-
const TENANT = process.env.SUPABASE_URL || '${n??
|
|
205
|
-
const API = process.env.TURBOBASE_API_URL || '${n??
|
|
204
|
+
const TENANT = process.env.SUPABASE_URL || '${n??fv}'; // /rest + the Realtime WS
|
|
205
|
+
const API = process.env.TURBOBASE_API_URL || '${n??hv}'; // /v1, /auth, /login, /_app
|
|
206
206
|
|
|
207
207
|
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
208
208
|
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
@@ -234,7 +234,7 @@ export default defineConfig({
|
|
|
234
234
|
},
|
|
235
235
|
build: { outDir: 'dist' },
|
|
236
236
|
});
|
|
237
|
-
`}function
|
|
237
|
+
`}function vp(t){return`<!doctype html>
|
|
238
238
|
<html lang="en">
|
|
239
239
|
<head>
|
|
240
240
|
<meta charset="UTF-8" />
|
|
@@ -247,7 +247,7 @@ export default defineConfig({
|
|
|
247
247
|
<script type="module" src="/src/main.tsx"></script>
|
|
248
248
|
</body>
|
|
249
249
|
</html>
|
|
250
|
-
`}function
|
|
250
|
+
`}function bv(t){return{"package.json":yp(t.slug),"vite.config.ts":bp(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":yv,"tsconfig.json":wp,"index.html":vp(t.title),"public/turbobase.json":uv(t),"public/favicon.svg":pp(t.slug,t.title),"src/main.tsx":kp,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":gp,"src/styles.css":Sp,"README.md":`# ${t.title}
|
|
251
251
|
|
|
252
252
|
\`\`\`sh
|
|
253
253
|
npm install
|
|
@@ -268,33 +268,153 @@ every read comes back "permission denied", which looks like an RLS problem.
|
|
|
268
268
|
|
|
269
269
|
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
270
270
|
live access token and is gitignored \u2014 keep it that way.
|
|
271
|
-
`}}function
|
|
272
|
-
import { select } from './lib/turbobase';
|
|
271
|
+
`}}function wv(t){return`import React from 'react';
|
|
272
|
+
import { select, write, del } from './lib/turbobase';
|
|
273
273
|
|
|
274
|
-
/** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has.
|
|
274
|
+
/** Swap for any record type \u2014 GET /v1/catalog/records lists what this instance has.
|
|
275
|
+
* \`hooks/\` in this project carries a \`before_save\` example for the same one. */
|
|
275
276
|
const RECORD_TYPE = 'customer';
|
|
276
277
|
|
|
278
|
+
/** Project the columns you render. Never \`select=*\` on a mirrored table \u2014 it
|
|
279
|
+
* drags the whole \`raw\` source document down with every row. */
|
|
280
|
+
const COLUMNS = 'pg_row_id,company_name,email';
|
|
281
|
+
|
|
282
|
+
type Row = { pg_row_id: string; company_name: string | null; email: string | null };
|
|
283
|
+
|
|
284
|
+
const message = (e: unknown): string => (e instanceof Error ? e.message : String(e));
|
|
285
|
+
const label = (r: Row): string => r.company_name ?? r.email ?? r.pg_row_id;
|
|
286
|
+
|
|
277
287
|
export default function App() {
|
|
278
|
-
const [rows, setRows] = React.useState<
|
|
288
|
+
const [rows, setRows] = React.useState<Row[]>([]);
|
|
279
289
|
const [error, setError] = React.useState<string | null>(null);
|
|
290
|
+
const [note, setNote] = React.useState<string | null>(null);
|
|
291
|
+
const [editing, setEditing] = React.useState<{ pgRowId: string; email: string } | null>(null);
|
|
292
|
+
const [busy, setBusy] = React.useState(false);
|
|
293
|
+
|
|
294
|
+
// Reads are RLS-scoped to the signed-in user \u2014 no key, no token handling. A
|
|
295
|
+
// tombstoned row is hidden by a restrictive policy, so a deleted row simply
|
|
296
|
+
// stops coming back rather than needing a filter here.
|
|
297
|
+
const refresh = React.useCallback(
|
|
298
|
+
() => select<Row>(\`\${RECORD_TYPE}?select=\${COLUMNS}&limit=25\`).then(setRows),
|
|
299
|
+
[],
|
|
300
|
+
);
|
|
280
301
|
|
|
281
302
|
React.useEffect(() => {
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
303
|
+
refresh().catch((e: unknown) => setError(message(e)));
|
|
304
|
+
}, [refresh]);
|
|
305
|
+
|
|
306
|
+
/** Run one mutation and report what actually happened. Every refusal below
|
|
307
|
+
* arrives as a THROW \u2014 a guardrail denial, a hook \`ctx.reject\`, a source that
|
|
308
|
+
* will not accept the operation \u2014 so nothing is quietly swallowed. */
|
|
309
|
+
async function run(mutate: () => Promise<string>): Promise<void> {
|
|
310
|
+
setBusy(true);
|
|
311
|
+
setError(null);
|
|
312
|
+
setNote(null);
|
|
313
|
+
try {
|
|
314
|
+
const outcome = await mutate();
|
|
315
|
+
await refresh();
|
|
316
|
+
setNote(outcome);
|
|
317
|
+
} catch (e: unknown) {
|
|
318
|
+
setError(message(e));
|
|
319
|
+
} finally {
|
|
320
|
+
setBusy(false);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** EDIT \u2014 through \`POST /v1/data/<recordType>\`, the canonical write boundary.
|
|
325
|
+
* Not a PostgREST write: \`authenticated\` holds no UPDATE on the mirror, so
|
|
326
|
+
* that path is a 42501 whatever the query says. This one runs the record
|
|
327
|
+
* type's \`before_save\` hooks, which is where validation belongs \u2014 a rule
|
|
328
|
+
* enforced in this component is bypassed by the chat agent, an MCP client and
|
|
329
|
+
* the next app to touch the row. The scaffolded hook rejects a malformed
|
|
330
|
+
* email, so typing one here surfaces its rejection in the banner below. */
|
|
331
|
+
const saveEmail = (row: Row, email: string): Promise<void> =>
|
|
332
|
+
run(async () => {
|
|
333
|
+
const res = await write<{ row: { pg_row_id: string | null; external_id: string | null } }>(
|
|
334
|
+
RECORD_TYPE,
|
|
335
|
+
{ pgRowId: row.pg_row_id, parent: { email } },
|
|
336
|
+
);
|
|
337
|
+
setEditing(null);
|
|
338
|
+
return \`write() accepted row \${res.row.pg_row_id ?? '(unkeyed)'} \u2014 the source write is queued, not confirmed.\`;
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
/** DELETE \u2014 through \`DELETE /v1/data/<recordType>\`. Destructive, so it is
|
|
342
|
+
* gated harder than a write: it needs a \`<recordType>.delete\` guardrail
|
|
343
|
+
* allow (a \`.write\` allow does NOT cover delete), is denied outright under
|
|
344
|
+
* deny-by-default, and is capped by the per-minute/hour/day delete rate
|
|
345
|
+
* limit. Any of those, or a source with delete-to-source parked, throws. */
|
|
346
|
+
const remove = (row: Row): Promise<void> =>
|
|
347
|
+
run(async () => {
|
|
348
|
+
const result = await del(RECORD_TYPE, { pgRowId: row.pg_row_id });
|
|
349
|
+
const { enqueued } = result;
|
|
350
|
+
// \`deleted\` is the LOCAL tombstone. \`enqueued\` is whether a source delete
|
|
351
|
+
// was queued behind it \u2014 false means the row had never synced upstream, so
|
|
352
|
+
// there was nothing to delete there. enqueued=true is NOT "the source
|
|
353
|
+
// deleted it": that leg can still be held for operator approval (a
|
|
354
|
+
// require_confirm guardrail) or refused by the source (dependent records,
|
|
355
|
+
// a required deletion reason), and either way the failure surfaces as a
|
|
356
|
+
// sync_failure rather than here.
|
|
357
|
+
return \`del() \u2192 \${JSON.stringify(result)} \u2014 \${
|
|
358
|
+
enqueued
|
|
359
|
+
? 'the source delete is QUEUED; it can still be held for approval or refused upstream, so watch sync failures.'
|
|
360
|
+
: 'nothing was queued; this row had never synced upstream, so the tombstone is purely local.'
|
|
361
|
+
}\`;
|
|
362
|
+
});
|
|
287
363
|
|
|
288
364
|
return (
|
|
289
|
-
<main style={{ padding: 24 }}>
|
|
365
|
+
<main style={{ padding: 24, maxWidth: 760 }}>
|
|
290
366
|
<h1>${t}</h1>
|
|
291
|
-
{error && <p style={{ color: 'crimson' }}>{error}</p>}
|
|
367
|
+
{error && <p role="alert" style={{ color: 'crimson' }}>{error}</p>}
|
|
368
|
+
{note && <p style={{ color: '#166534' }}>{note}</p>}
|
|
292
369
|
<p>{rows.length} {RECORD_TYPE} row(s), scoped to you.</p>
|
|
293
|
-
<
|
|
370
|
+
<ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
|
|
371
|
+
{rows.map((row) => {
|
|
372
|
+
const edit = editing && editing.pgRowId === row.pg_row_id ? editing : null;
|
|
373
|
+
return (
|
|
374
|
+
<li key={row.pg_row_id} style={{ borderTop: '1px solid #e2e8f0', padding: '8px 0' }}>
|
|
375
|
+
<strong>{label(row)}</strong>{' '}
|
|
376
|
+
<span style={{ color: '#64748b' }}>{row.email ?? 'no email'}</span>{' '}
|
|
377
|
+
{edit ? (
|
|
378
|
+
<>
|
|
379
|
+
<input
|
|
380
|
+
value={edit.email}
|
|
381
|
+
placeholder="email"
|
|
382
|
+
onChange={(e) => setEditing({ pgRowId: row.pg_row_id, email: e.target.value })}
|
|
383
|
+
/>
|
|
384
|
+
<button disabled={busy} onClick={() => void saveEmail(row, edit.email)}>Save</button>
|
|
385
|
+
<button disabled={busy} onClick={() => setEditing(null)}>Cancel</button>
|
|
386
|
+
</>
|
|
387
|
+
) : (
|
|
388
|
+
<>
|
|
389
|
+
<button
|
|
390
|
+
disabled={busy}
|
|
391
|
+
onClick={() => setEditing({ pgRowId: row.pg_row_id, email: row.email ?? '' })}
|
|
392
|
+
>
|
|
393
|
+
Edit email
|
|
394
|
+
</button>
|
|
395
|
+
<button
|
|
396
|
+
disabled={busy}
|
|
397
|
+
onClick={() => {
|
|
398
|
+
// Destructive and real: this deletes upstream too, subject
|
|
399
|
+
// to the guardrails above. Confirm before firing it.
|
|
400
|
+
if (window.confirm(\`Delete \${label(row)}?\`)) void remove(row);
|
|
401
|
+
}}
|
|
402
|
+
>
|
|
403
|
+
Delete
|
|
404
|
+
</button>
|
|
405
|
+
</>
|
|
406
|
+
)}
|
|
407
|
+
</li>
|
|
408
|
+
);
|
|
409
|
+
})}
|
|
410
|
+
</ul>
|
|
411
|
+
{rows.length === 0 && !error && (
|
|
412
|
+
<p>Nothing to show \u2014 sync a {RECORD_TYPE}, or point RECORD_TYPE at a record this instance has.</p>
|
|
413
|
+
)}
|
|
294
414
|
</main>
|
|
295
415
|
);
|
|
296
416
|
}
|
|
297
|
-
`}var
|
|
417
|
+
`}var dv,gp,Sr,pv,fv,hv,yv,wp,kp,Sp,$p=j(()=>{fp();mp();dv=200;gp=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
|
|
298
418
|
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
299
419
|
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
300
420
|
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
@@ -583,6 +703,31 @@ export async function write<T = unknown>(recordType: string, body: unknown): Pro
|
|
|
583
703
|
return (await res.json()) as T;
|
|
584
704
|
}
|
|
585
705
|
|
|
706
|
+
/** Delete a record through the canonical boundary DELETE /v1/data/<recordType>.
|
|
707
|
+
* Identify the row by \`pgRowId\` OR \`externalId\` (one is required). NEVER issue a
|
|
708
|
+
* hard SQL DELETE against a table \u2014 apps hold no DELETE grant, and it would not
|
|
709
|
+
* propagate to the source.
|
|
710
|
+
*
|
|
711
|
+
* What happens: the row is soft-deleted (tombstoned) locally, and \u2014 for a
|
|
712
|
+
* bidirectional, delete-capable source (NetSuite today; others parked) \u2014 the
|
|
713
|
+
* delete is queued to the source. Deletes are gated as a DESTRUCTIVE op: they
|
|
714
|
+
* need a \`<record>.delete\` guardrail allow (a \`.write\` allow does NOT cover
|
|
715
|
+
* delete), are denied under deny-by-default, and are capped by the per-minute/
|
|
716
|
+
* hour/day delete rate limit. A parked source, a denied guardrail, or a source
|
|
717
|
+
* that refuses the delete (e.g. NetSuite deletion-reason / has-dependents) fails
|
|
718
|
+
* LOUDLY \u2014 this throws, or the sync surfaces a \`sync_failure\`; nothing is
|
|
719
|
+
* silently upserted. Returns \`{ deleted, enqueued }\`: \`enqueued\` is false when
|
|
720
|
+
* the row never synced upstream (a purely local tombstone). */
|
|
721
|
+
export async function del(
|
|
722
|
+
recordType: string,
|
|
723
|
+
key: { pgRowId: string } | { externalId: string },
|
|
724
|
+
): Promise<{ deleted: boolean; enqueued: boolean }> {
|
|
725
|
+
const q = 'pgRowId' in key ? \`pgRowId=\${encodeURIComponent(key.pgRowId)}\` : \`externalId=\${encodeURIComponent(key.externalId)}\`;
|
|
726
|
+
const res = await req(\`/v1/data/\${recordType}?\${q}\`, { method: 'DELETE' });
|
|
727
|
+
if (!res.ok) throw new Error(await readError(res));
|
|
728
|
+
return (await res.json()) as { deleted: boolean; enqueued: boolean };
|
|
729
|
+
}
|
|
730
|
+
|
|
586
731
|
/** One sub-result from batch(): its own status, so a 429/5xx on one query does
|
|
587
732
|
* not fail the others. \`ok\` is status 2xx; \`rows\` is the parsed body on
|
|
588
733
|
* success (undefined on failure \u2014 read \`status\`/\`error\`). */
|
|
@@ -1051,7 +1196,7 @@ export async function selectPage<T = unknown>(
|
|
|
1051
1196
|
}
|
|
1052
1197
|
return { rows, nextCursor };
|
|
1053
1198
|
}
|
|
1054
|
-
`,
|
|
1199
|
+
`,Sr="src/types.ts",pv=`turbobase project types -o ${Sr} || node -e "if(require('node:fs').existsSync('${Sr}')){console.error('turbobase: could not refresh ${Sr} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${Sr} is missing. It is generated from the instance catalog and gitignored, so a fresh checkout has no copy. Run: turbobase auth login --base-url <your-instance> --token tb_pat_... , then turbobase project types -o ${Sr}');process.exit(1)}"`;fv="http://localhost:54331",hv="http://localhost:4100";yv=`node_modules/
|
|
1055
1200
|
dist/
|
|
1056
1201
|
build/
|
|
1057
1202
|
|
|
@@ -1063,8 +1208,8 @@ build/
|
|
|
1063
1208
|
!.env.example
|
|
1064
1209
|
|
|
1065
1210
|
.DS_Store
|
|
1066
|
-
`,
|
|
1067
|
-
`;
|
|
1211
|
+
`,wp=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0},include:["src"]},null,2)}
|
|
1212
|
+
`;kp=`import React from 'react';
|
|
1068
1213
|
import { createRoot } from 'react-dom/client';
|
|
1069
1214
|
import App from './App';
|
|
1070
1215
|
import './styles.css';
|
|
@@ -1074,53 +1219,53 @@ createRoot(document.getElementById('root')!).render(
|
|
|
1074
1219
|
<App />
|
|
1075
1220
|
</React.StrictMode>,
|
|
1076
1221
|
);
|
|
1077
|
-
`,
|
|
1222
|
+
`,Sp=`:root { color-scheme: light; font-family: ui-sans-serif, system-ui, sans-serif; }
|
|
1078
1223
|
* { box-sizing: border-box; }
|
|
1079
1224
|
body { margin: 0; background: #f8fafc; color: #0f172a; }
|
|
1080
|
-
`});import*as
|
|
1081
|
-
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function lp(t){return t.description}function cp(t){if(wt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function An(t){if(wt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var Sr=j(()=>{});import*as c from"zod/v4";function Tp(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Rp(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Qi,up,Bt,Ls,$e,dp,pp,JP,Gw,Ww,Xi,Ze,_r,fp,Re,rt,st,Ee,zs,hp,ea,mp,gp,ta,$r,B,na,bp,yp,ZP,Ds,Jw,Us,Zw,xr,In,wp,Yw,Qw,Xw,ev,tv,nv,ra,rv,sv,sa,qs,ov,iv,Ms,av,Tr,Rr,lv,Er,Cn,cv,Pr,Bs,Fs,Ks,YP,Hs,Vs,Gs,vp,kp,Sp,oa,_p,Ar,On,$p,uv,Ws,dv,Js,pv,ia,fv,Zs,hv,mv,gv,bv,yv,wv,vv,kv,Sv,_v,Ys,$v,xv,Qs,aa,la,ca,Tv,Rv,Ev,ua,Pv,Av,Iv,Cv,Ov,xp,Xs,Nv,eo,QP,jv,Nn,Lv,XP,Ir,zv,da,Dv,Uv,qv,Mv,Bv,Fv,Kv,js,Hv,Vv,Gv,Cr,pa,Wv,Jv,Zv,Yv,Qv,Xv,ek,tk,nk,rk,sk,ok,ik,ak,lk,ck,uk,dk,jn,pk,fk,hk,to,mk,gk,bk,fa,yk,eA,tA,nA,rA,sA,oA,U,Yi,Ln=j(()=>{Qi="2025-11-25",up=[Qi,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Bt="io.modelcontextprotocol/related-task",Ls="2.0",$e=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),dp=c.union([c.string(),c.number().int()]),pp=c.string(),JP=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),Gw=c.object({ttl:c.number().optional()}),Ww=c.object({taskId:c.string()}),Xi=c.looseObject({progressToken:dp.optional(),[Bt]:Ww.optional()}),Ze=c.object({_meta:Xi.optional()}),_r=Ze.extend({task:Gw.optional()}),fp=t=>_r.safeParse(t).success,Re=c.object({method:c.string(),params:Ze.loose().optional()}),rt=c.object({_meta:Xi.optional()}),st=c.object({method:c.string(),params:rt.loose().optional()}),Ee=c.looseObject({_meta:Xi.optional()}),zs=c.union([c.string(),c.number().int()]),hp=c.object({jsonrpc:c.literal(Ls),id:zs,...Re.shape}).strict(),ea=t=>hp.safeParse(t).success,mp=c.object({jsonrpc:c.literal(Ls),...st.shape}).strict(),gp=t=>mp.safeParse(t).success,ta=c.object({jsonrpc:c.literal(Ls),id:zs,result:Ee}).strict(),$r=t=>ta.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(B||(B={}));na=c.object({jsonrpc:c.literal(Ls),id:zs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),bp=t=>na.safeParse(t).success,yp=c.union([hp,mp,ta,na]),ZP=c.union([ta,na]),Ds=Ee.strict(),Jw=rt.extend({requestId:zs.optional(),reason:c.string().optional()}),Us=st.extend({method:c.literal("notifications/cancelled"),params:Jw}),Zw=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),xr=c.object({icons:c.array(Zw).optional()}),In=c.object({name:c.string(),title:c.string().optional()}),wp=In.extend({...In.shape,...xr.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),Yw=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),Qw=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:Yw.optional(),url:$e.optional()}),c.record(c.string(),c.unknown()).optional())),Xw=c.looseObject({list:$e.optional(),cancel:$e.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:$e.optional()}).optional(),elicitation:c.looseObject({create:$e.optional()}).optional()}).optional()}),ev=c.looseObject({list:$e.optional(),cancel:$e.optional(),requests:c.looseObject({tools:c.looseObject({call:$e.optional()}).optional()}).optional()}),tv=c.object({experimental:c.record(c.string(),$e).optional(),sampling:c.object({context:$e.optional(),tools:$e.optional()}).optional(),elicitation:Qw.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Xw.optional(),extensions:c.record(c.string(),$e).optional()}),nv=Ze.extend({protocolVersion:c.string(),capabilities:tv,clientInfo:wp}),ra=Re.extend({method:c.literal("initialize"),params:nv}),rv=c.object({experimental:c.record(c.string(),$e).optional(),logging:$e.optional(),completions:$e.optional(),prompts:c.object({listChanged:c.boolean().optional()}).optional(),resources:c.object({subscribe:c.boolean().optional(),listChanged:c.boolean().optional()}).optional(),tools:c.object({listChanged:c.boolean().optional()}).optional(),tasks:ev.optional(),extensions:c.record(c.string(),$e).optional()}),sv=Ee.extend({protocolVersion:c.string(),capabilities:rv,serverInfo:wp,instructions:c.string().optional()}),sa=st.extend({method:c.literal("notifications/initialized"),params:rt.optional()}),qs=Re.extend({method:c.literal("ping"),params:Ze.optional()}),ov=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),iv=c.object({...rt.shape,...ov.shape,progressToken:dp}),Ms=st.extend({method:c.literal("notifications/progress"),params:iv}),av=Ze.extend({cursor:pp.optional()}),Tr=Re.extend({params:av.optional()}),Rr=Ee.extend({nextCursor:pp.optional()}),lv=c.enum(["working","input_required","completed","failed","cancelled"]),Er=c.object({taskId:c.string(),status:lv,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Cn=Ee.extend({task:Er}),cv=rt.merge(Er),Pr=st.extend({method:c.literal("notifications/tasks/status"),params:cv}),Bs=Re.extend({method:c.literal("tasks/get"),params:Ze.extend({taskId:c.string()})}),Fs=Ee.merge(Er),Ks=Re.extend({method:c.literal("tasks/result"),params:Ze.extend({taskId:c.string()})}),YP=Ee.loose(),Hs=Tr.extend({method:c.literal("tasks/list")}),Vs=Rr.extend({tasks:c.array(Er)}),Gs=Re.extend({method:c.literal("tasks/cancel"),params:Ze.extend({taskId:c.string()})}),vp=Ee.merge(Er),kp=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),Sp=kp.extend({text:c.string()}),oa=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),_p=kp.extend({blob:oa}),Ar=c.enum(["user","assistant"]),On=c.object({audience:c.array(Ar).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),$p=c.object({...In.shape,...xr.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:On.optional(),_meta:c.optional(c.looseObject({}))}),uv=c.object({...In.shape,...xr.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:On.optional(),_meta:c.optional(c.looseObject({}))}),Ws=Tr.extend({method:c.literal("resources/list")}),dv=Rr.extend({resources:c.array($p)}),Js=Tr.extend({method:c.literal("resources/templates/list")}),pv=Rr.extend({resourceTemplates:c.array(uv)}),ia=Ze.extend({uri:c.string()}),fv=ia,Zs=Re.extend({method:c.literal("resources/read"),params:fv}),hv=Ee.extend({contents:c.array(c.union([Sp,_p]))}),mv=st.extend({method:c.literal("notifications/resources/list_changed"),params:rt.optional()}),gv=ia,bv=Re.extend({method:c.literal("resources/subscribe"),params:gv}),yv=ia,wv=Re.extend({method:c.literal("resources/unsubscribe"),params:yv}),vv=rt.extend({uri:c.string()}),kv=st.extend({method:c.literal("notifications/resources/updated"),params:vv}),Sv=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),_v=c.object({...In.shape,...xr.shape,description:c.optional(c.string()),arguments:c.optional(c.array(Sv)),_meta:c.optional(c.looseObject({}))}),Ys=Tr.extend({method:c.literal("prompts/list")}),$v=Rr.extend({prompts:c.array(_v)}),xv=Ze.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Qs=Re.extend({method:c.literal("prompts/get"),params:xv}),aa=c.object({type:c.literal("text"),text:c.string(),annotations:On.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),la=c.object({type:c.literal("image"),data:oa,mimeType:c.string(),annotations:On.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ca=c.object({type:c.literal("audio"),data:oa,mimeType:c.string(),annotations:On.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Tv=c.object({type:c.literal("tool_use"),name:c.string(),id:c.string(),input:c.record(c.string(),c.unknown()),_meta:c.record(c.string(),c.unknown()).optional()}),Rv=c.object({type:c.literal("resource"),resource:c.union([Sp,_p]),annotations:On.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ev=$p.extend({type:c.literal("resource_link")}),ua=c.union([aa,la,ca,Ev,Rv]),Pv=c.object({role:Ar,content:ua}),Av=Ee.extend({description:c.string().optional(),messages:c.array(Pv)}),Iv=st.extend({method:c.literal("notifications/prompts/list_changed"),params:rt.optional()}),Cv=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Ov=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),xp=c.object({...In.shape,...xr.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),$e).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),$e).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:Cv.optional(),execution:Ov.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Xs=Tr.extend({method:c.literal("tools/list")}),Nv=Rr.extend({tools:c.array(xp)}),eo=Ee.extend({content:c.array(ua).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),QP=eo.or(Ee.extend({toolResult:c.unknown()})),jv=_r.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Nn=Re.extend({method:c.literal("tools/call"),params:jv}),Lv=st.extend({method:c.literal("notifications/tools/list_changed"),params:rt.optional()}),XP=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Ir=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),zv=Ze.extend({level:Ir}),da=Re.extend({method:c.literal("logging/setLevel"),params:zv}),Dv=rt.extend({level:Ir,logger:c.string().optional(),data:c.unknown()}),Uv=st.extend({method:c.literal("notifications/message"),params:Dv}),qv=c.object({name:c.string().optional()}),Mv=c.object({hints:c.array(qv).optional(),costPriority:c.number().min(0).max(1).optional(),speedPriority:c.number().min(0).max(1).optional(),intelligencePriority:c.number().min(0).max(1).optional()}),Bv=c.object({mode:c.enum(["auto","required","none"]).optional()}),Fv=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(ua).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Kv=c.discriminatedUnion("type",[aa,la,ca]),js=c.discriminatedUnion("type",[aa,la,ca,Tv,Fv]),Hv=c.object({role:Ar,content:c.union([js,c.array(js)]),_meta:c.record(c.string(),c.unknown()).optional()}),Vv=_r.extend({messages:c.array(Hv),modelPreferences:Mv.optional(),systemPrompt:c.string().optional(),includeContext:c.enum(["none","thisServer","allServers"]).optional(),temperature:c.number().optional(),maxTokens:c.number().int(),stopSequences:c.array(c.string()).optional(),metadata:$e.optional(),tools:c.array(xp).optional(),toolChoice:Bv.optional()}),Gv=Re.extend({method:c.literal("sampling/createMessage"),params:Vv}),Cr=Ee.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Ar,content:Kv}),pa=Ee.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Ar,content:c.union([js,c.array(js)])}),Wv=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),Jv=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),minLength:c.number().optional(),maxLength:c.number().optional(),format:c.enum(["email","uri","date","date-time"]).optional(),default:c.string().optional()}),Zv=c.object({type:c.enum(["number","integer"]),title:c.string().optional(),description:c.string().optional(),minimum:c.number().optional(),maximum:c.number().optional(),default:c.number().optional()}),Yv=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),Qv=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),oneOf:c.array(c.object({const:c.string(),title:c.string()})),default:c.string().optional()}),Xv=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),enumNames:c.array(c.string()).optional(),default:c.string().optional()}),ek=c.union([Yv,Qv]),tk=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({type:c.literal("string"),enum:c.array(c.string())}),default:c.array(c.string()).optional()}),nk=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({anyOf:c.array(c.object({const:c.string(),title:c.string()}))}),default:c.array(c.string()).optional()}),rk=c.union([tk,nk]),sk=c.union([Xv,ek,rk]),ok=c.union([sk,Wv,Jv,Zv]),ik=_r.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),ok),required:c.array(c.string()).optional()})}),ak=_r.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),lk=c.union([ik,ak]),ck=Re.extend({method:c.literal("elicitation/create"),params:lk}),uk=rt.extend({elicitationId:c.string()}),dk=st.extend({method:c.literal("notifications/elicitation/complete"),params:uk}),jn=Ee.extend({action:c.enum(["accept","decline","cancel"]),content:c.preprocess(t=>t===null?void 0:t,c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())])).optional())}),pk=c.object({type:c.literal("ref/resource"),uri:c.string()}),fk=c.object({type:c.literal("ref/prompt"),name:c.string()}),hk=Ze.extend({ref:c.union([fk,pk]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),to=Re.extend({method:c.literal("completion/complete"),params:hk});mk=Ee.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),gk=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),bk=Re.extend({method:c.literal("roots/list"),params:Ze.optional()}),fa=Ee.extend({roots:c.array(gk)}),yk=st.extend({method:c.literal("notifications/roots/list_changed"),params:rt.optional()}),eA=c.union([qs,ra,to,da,Qs,Ys,Ws,Js,Zs,bv,wv,Nn,Xs,Bs,Ks,Hs,Gs]),tA=c.union([Us,Ms,sa,yk,Pr]),nA=c.union([Ds,Cr,pa,jn,fa,Fs,Vs,Cn]),rA=c.union([qs,Gv,ck,bk,Bs,Ks,Hs,Gs]),sA=c.union([Us,Ms,Uv,kv,mv,Lv,Iv,Pr,dk]),oA=c.union([Ds,sv,mk,Av,$v,dv,pv,hv,eo,Nv,Fs,Vs,Cn]),U=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===B.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new Yi(s.elicitations,n)}return new t(e,n,r)}},Yi=class extends U{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(B.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Ft(t){return t==="completed"||t==="failed"||t==="cancelled"}var Ep=j(()=>{});var Ap,Pp,Ip,no=j(()=>{Ap=Symbol("Let zodToJsonSchema decide on which parser to use"),Pp={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Ip=t=>typeof t=="string"?{...Pp,name:t}:{...Pp,...t}});var Cp,ha=j(()=>{no();Cp=t=>{let e=Ip(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function ma(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ie(t,e,n,r,s){t[e]=n,ma(t,e,r,s)}var Kt=j(()=>{});var ro,so=j(()=>{ro=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ro(e,t.currentPath):e.join("/")}}var ot=j(()=>{so()});import{ZodFirstPartyTypeKind as wk}from"zod/v3";function Op(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==wk.ZodAny&&(n.items=K(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ie(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ie(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ie(n,"minItems",t.exactLength.value,t.exactLength.message,e),ie(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var ga=j(()=>{Kt();_e()});function Np(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ie(n,"minimum",r.value,r.message,e):ie(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ie(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ie(n,"maximum",r.value,r.message,e):ie(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ie(n,"maximum",r.value,r.message,e));break;case"multipleOf":ie(n,"multipleOf",r.value,r.message,e);break}return n}var ba=j(()=>{Kt()});function jp(){return{type:"boolean"}}var ya=j(()=>{});function oo(t,e){return K(t.type._def,e)}var io=j(()=>{_e()});var Lp,wa=j(()=>{_e();Lp=(t,e)=>K(t.innerType._def,e)});function va(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>va(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return vk(t,e)}}var vk,ka=j(()=>{Kt();vk=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":ie(n,"minimum",r.value,r.message,e);break;case"max":ie(n,"maximum",r.value,r.message,e);break}return n}});function zp(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}var Sa=j(()=>{_e()});function Dp(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):we(e)}var _a=j(()=>{_e();ot()});function Up(t){return{type:"string",enum:Array.from(t.values)}}var $a=j(()=>{});function qp(t,e){let n=[K(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return n.forEach(o=>{if(kk(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(r=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...l}=o;i=l}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}var kk,xa=j(()=>{_e();kk=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Mp(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var Ta=j(()=>{});function ao(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ie(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ie(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":pt(n,"email",r.message,e);break;case"format:idn-email":pt(n,"idn-email",r.message,e);break;case"pattern:zod":Ue(n,dt.email,r.message,e);break}break;case"url":pt(n,"uri",r.message,e);break;case"uuid":pt(n,"uuid",r.message,e);break;case"regex":Ue(n,r.regex,r.message,e);break;case"cuid":Ue(n,dt.cuid,r.message,e);break;case"cuid2":Ue(n,dt.cuid2,r.message,e);break;case"startsWith":Ue(n,RegExp(`^${Ea(r.value,e)}`),r.message,e);break;case"endsWith":Ue(n,RegExp(`${Ea(r.value,e)}$`),r.message,e);break;case"datetime":pt(n,"date-time",r.message,e);break;case"date":pt(n,"date",r.message,e);break;case"time":pt(n,"time",r.message,e);break;case"duration":pt(n,"duration",r.message,e);break;case"length":ie(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ie(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Ue(n,RegExp(Ea(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&pt(n,"ipv4",r.message,e),r.version!=="v4"&&pt(n,"ipv6",r.message,e);break}case"base64url":Ue(n,dt.base64url,r.message,e);break;case"jwt":Ue(n,dt.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Ue(n,dt.ipv4Cidr,r.message,e),r.version!=="v4"&&Ue(n,dt.ipv6Cidr,r.message,e);break}case"emoji":Ue(n,dt.emoji(),r.message,e);break;case"ulid":{Ue(n,dt.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{pt(n,"binary",r.message,e);break}case"contentEncoding:base64":{ie(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Ue(n,dt.base64,r.message,e);break}}break}case"nanoid":Ue(n,dt.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Ea(t,e){return e.patternStrategy==="escape"?_k(t):t}function _k(t){let e="";for(let n=0;n<t.length;n++)Sk.has(t[n])||(e+="\\"),e+=t[n];return e}function pt(t,e,n,r){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ie(t,"format",e,n,r)}function Ue(t,e,n,r){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Bp(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ie(t,"pattern",Bp(e,r),n,r)}function Bp(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let l=0;l<r.length;l++){if(o){s+=r[l],o=!1;continue}if(n.i){if(i){if(r[l].match(/[a-z]/)){a?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),a=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],a=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(n.m){if(r[l]==="^"){s+=`(^|(?<=[\r
|
|
1225
|
+
`});import*as xp from"zod/v3";import*as on from"zod/v4-mini";function vt(t){return!!t._zod}function an(t){let e=Object.values(t);if(e.length===0)return on.object({});let n=e.every(vt),r=e.every(s=>!vt(s));if(n)return on.object(t);if(r)return xp.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Bt(t,e){return vt(t)?on.safeParse(t,e):t.safeParse(e)}async function Us(t,e){return vt(t)?await on.safeParseAsync(t,e):await t.safeParseAsync(e)}function Ft(t){if(!t)return;let e;if(vt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function An(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return an(t)}}if(vt(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function vv(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function zs(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${vv(e.path)}`:e.message).join(`
|
|
1226
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Rp(t){return t.description}function Tp(t){if(vt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function In(t){if(vt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var _r=j(()=>{});import*as c from"zod/v4";function Hp(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Kp(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var ia,Ep,Ht,Ms,xe,Pp,Ap,EA,kv,Sv,aa,Ye,$r,Ip,Ee,st,ot,Pe,Bs,Cp,la,Op,Np,ca,xr,F,da,jp,Lp,PA,Fs,_v,Hs,$v,Rr,Cn,Dp,xv,Rv,Tv,Ev,Pv,Av,ua,Iv,Cv,pa,Ks,Ov,Nv,Vs,jv,Tr,Er,Lv,Pr,On,Dv,Ar,Gs,Ws,Js,AA,Zs,Ys,Qs,Up,zp,qp,fa,Mp,Ir,Nn,Bp,Uv,Xs,zv,eo,qv,ha,Mv,to,Bv,Fv,Hv,Kv,Vv,Gv,Wv,Jv,Zv,Yv,no,Qv,Xv,ro,ma,ga,ya,ek,tk,nk,ba,rk,sk,ok,ik,ak,Fp,so,lk,oo,IA,ck,jn,dk,CA,Cr,uk,wa,pk,fk,hk,mk,gk,yk,bk,qs,wk,vk,kk,Or,va,Sk,_k,$k,xk,Rk,Tk,Ek,Pk,Ak,Ik,Ck,Ok,Nk,jk,Lk,Dk,Uk,zk,Ln,qk,Mk,Bk,io,Fk,Hk,Kk,ka,Vk,OA,NA,jA,LA,DA,UA,z,oa,Dn=j(()=>{ia="2025-11-25",Ep=[ia,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ht="io.modelcontextprotocol/related-task",Ms="2.0",xe=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Pp=c.union([c.string(),c.number().int()]),Ap=c.string(),EA=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),kv=c.object({ttl:c.number().optional()}),Sv=c.object({taskId:c.string()}),aa=c.looseObject({progressToken:Pp.optional(),[Ht]:Sv.optional()}),Ye=c.object({_meta:aa.optional()}),$r=Ye.extend({task:kv.optional()}),Ip=t=>$r.safeParse(t).success,Ee=c.object({method:c.string(),params:Ye.loose().optional()}),st=c.object({_meta:aa.optional()}),ot=c.object({method:c.string(),params:st.loose().optional()}),Pe=c.looseObject({_meta:aa.optional()}),Bs=c.union([c.string(),c.number().int()]),Cp=c.object({jsonrpc:c.literal(Ms),id:Bs,...Ee.shape}).strict(),la=t=>Cp.safeParse(t).success,Op=c.object({jsonrpc:c.literal(Ms),...ot.shape}).strict(),Np=t=>Op.safeParse(t).success,ca=c.object({jsonrpc:c.literal(Ms),id:Bs,result:Pe}).strict(),xr=t=>ca.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(F||(F={}));da=c.object({jsonrpc:c.literal(Ms),id:Bs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),jp=t=>da.safeParse(t).success,Lp=c.union([Cp,Op,ca,da]),PA=c.union([ca,da]),Fs=Pe.strict(),_v=st.extend({requestId:Bs.optional(),reason:c.string().optional()}),Hs=ot.extend({method:c.literal("notifications/cancelled"),params:_v}),$v=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Rr=c.object({icons:c.array($v).optional()}),Cn=c.object({name:c.string(),title:c.string().optional()}),Dp=Cn.extend({...Cn.shape,...Rr.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),xv=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),Rv=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:xv.optional(),url:xe.optional()}),c.record(c.string(),c.unknown()).optional())),Tv=c.looseObject({list:xe.optional(),cancel:xe.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:xe.optional()}).optional(),elicitation:c.looseObject({create:xe.optional()}).optional()}).optional()}),Ev=c.looseObject({list:xe.optional(),cancel:xe.optional(),requests:c.looseObject({tools:c.looseObject({call:xe.optional()}).optional()}).optional()}),Pv=c.object({experimental:c.record(c.string(),xe).optional(),sampling:c.object({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:Rv.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Tv.optional(),extensions:c.record(c.string(),xe).optional()}),Av=Ye.extend({protocolVersion:c.string(),capabilities:Pv,clientInfo:Dp}),ua=Ee.extend({method:c.literal("initialize"),params:Av}),Iv=c.object({experimental:c.record(c.string(),xe).optional(),logging:xe.optional(),completions:xe.optional(),prompts:c.object({listChanged:c.boolean().optional()}).optional(),resources:c.object({subscribe:c.boolean().optional(),listChanged:c.boolean().optional()}).optional(),tools:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Ev.optional(),extensions:c.record(c.string(),xe).optional()}),Cv=Pe.extend({protocolVersion:c.string(),capabilities:Iv,serverInfo:Dp,instructions:c.string().optional()}),pa=ot.extend({method:c.literal("notifications/initialized"),params:st.optional()}),Ks=Ee.extend({method:c.literal("ping"),params:Ye.optional()}),Ov=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),Nv=c.object({...st.shape,...Ov.shape,progressToken:Pp}),Vs=ot.extend({method:c.literal("notifications/progress"),params:Nv}),jv=Ye.extend({cursor:Ap.optional()}),Tr=Ee.extend({params:jv.optional()}),Er=Pe.extend({nextCursor:Ap.optional()}),Lv=c.enum(["working","input_required","completed","failed","cancelled"]),Pr=c.object({taskId:c.string(),status:Lv,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),On=Pe.extend({task:Pr}),Dv=st.merge(Pr),Ar=ot.extend({method:c.literal("notifications/tasks/status"),params:Dv}),Gs=Ee.extend({method:c.literal("tasks/get"),params:Ye.extend({taskId:c.string()})}),Ws=Pe.merge(Pr),Js=Ee.extend({method:c.literal("tasks/result"),params:Ye.extend({taskId:c.string()})}),AA=Pe.loose(),Zs=Tr.extend({method:c.literal("tasks/list")}),Ys=Er.extend({tasks:c.array(Pr)}),Qs=Ee.extend({method:c.literal("tasks/cancel"),params:Ye.extend({taskId:c.string()})}),Up=Pe.merge(Pr),zp=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),qp=zp.extend({text:c.string()}),fa=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mp=zp.extend({blob:fa}),Ir=c.enum(["user","assistant"]),Nn=c.object({audience:c.array(Ir).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),Bp=c.object({...Cn.shape,...Rr.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Nn.optional(),_meta:c.optional(c.looseObject({}))}),Uv=c.object({...Cn.shape,...Rr.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Nn.optional(),_meta:c.optional(c.looseObject({}))}),Xs=Tr.extend({method:c.literal("resources/list")}),zv=Er.extend({resources:c.array(Bp)}),eo=Tr.extend({method:c.literal("resources/templates/list")}),qv=Er.extend({resourceTemplates:c.array(Uv)}),ha=Ye.extend({uri:c.string()}),Mv=ha,to=Ee.extend({method:c.literal("resources/read"),params:Mv}),Bv=Pe.extend({contents:c.array(c.union([qp,Mp]))}),Fv=ot.extend({method:c.literal("notifications/resources/list_changed"),params:st.optional()}),Hv=ha,Kv=Ee.extend({method:c.literal("resources/subscribe"),params:Hv}),Vv=ha,Gv=Ee.extend({method:c.literal("resources/unsubscribe"),params:Vv}),Wv=st.extend({uri:c.string()}),Jv=ot.extend({method:c.literal("notifications/resources/updated"),params:Wv}),Zv=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),Yv=c.object({...Cn.shape,...Rr.shape,description:c.optional(c.string()),arguments:c.optional(c.array(Zv)),_meta:c.optional(c.looseObject({}))}),no=Tr.extend({method:c.literal("prompts/list")}),Qv=Er.extend({prompts:c.array(Yv)}),Xv=Ye.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),ro=Ee.extend({method:c.literal("prompts/get"),params:Xv}),ma=c.object({type:c.literal("text"),text:c.string(),annotations:Nn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ga=c.object({type:c.literal("image"),data:fa,mimeType:c.string(),annotations:Nn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ya=c.object({type:c.literal("audio"),data:fa,mimeType:c.string(),annotations:Nn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ek=c.object({type:c.literal("tool_use"),name:c.string(),id:c.string(),input:c.record(c.string(),c.unknown()),_meta:c.record(c.string(),c.unknown()).optional()}),tk=c.object({type:c.literal("resource"),resource:c.union([qp,Mp]),annotations:Nn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),nk=Bp.extend({type:c.literal("resource_link")}),ba=c.union([ma,ga,ya,nk,tk]),rk=c.object({role:Ir,content:ba}),sk=Pe.extend({description:c.string().optional(),messages:c.array(rk)}),ok=ot.extend({method:c.literal("notifications/prompts/list_changed"),params:st.optional()}),ik=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),ak=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),Fp=c.object({...Cn.shape,...Rr.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),xe).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),xe).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:ik.optional(),execution:ak.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),so=Tr.extend({method:c.literal("tools/list")}),lk=Er.extend({tools:c.array(Fp)}),oo=Pe.extend({content:c.array(ba).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),IA=oo.or(Pe.extend({toolResult:c.unknown()})),ck=$r.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),jn=Ee.extend({method:c.literal("tools/call"),params:ck}),dk=ot.extend({method:c.literal("notifications/tools/list_changed"),params:st.optional()}),CA=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Cr=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),uk=Ye.extend({level:Cr}),wa=Ee.extend({method:c.literal("logging/setLevel"),params:uk}),pk=st.extend({level:Cr,logger:c.string().optional(),data:c.unknown()}),fk=ot.extend({method:c.literal("notifications/message"),params:pk}),hk=c.object({name:c.string().optional()}),mk=c.object({hints:c.array(hk).optional(),costPriority:c.number().min(0).max(1).optional(),speedPriority:c.number().min(0).max(1).optional(),intelligencePriority:c.number().min(0).max(1).optional()}),gk=c.object({mode:c.enum(["auto","required","none"]).optional()}),yk=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(ba).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),bk=c.discriminatedUnion("type",[ma,ga,ya]),qs=c.discriminatedUnion("type",[ma,ga,ya,ek,yk]),wk=c.object({role:Ir,content:c.union([qs,c.array(qs)]),_meta:c.record(c.string(),c.unknown()).optional()}),vk=$r.extend({messages:c.array(wk),modelPreferences:mk.optional(),systemPrompt:c.string().optional(),includeContext:c.enum(["none","thisServer","allServers"]).optional(),temperature:c.number().optional(),maxTokens:c.number().int(),stopSequences:c.array(c.string()).optional(),metadata:xe.optional(),tools:c.array(Fp).optional(),toolChoice:gk.optional()}),kk=Ee.extend({method:c.literal("sampling/createMessage"),params:vk}),Or=Pe.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Ir,content:bk}),va=Pe.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Ir,content:c.union([qs,c.array(qs)])}),Sk=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),_k=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),minLength:c.number().optional(),maxLength:c.number().optional(),format:c.enum(["email","uri","date","date-time"]).optional(),default:c.string().optional()}),$k=c.object({type:c.enum(["number","integer"]),title:c.string().optional(),description:c.string().optional(),minimum:c.number().optional(),maximum:c.number().optional(),default:c.number().optional()}),xk=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),Rk=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),oneOf:c.array(c.object({const:c.string(),title:c.string()})),default:c.string().optional()}),Tk=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),enumNames:c.array(c.string()).optional(),default:c.string().optional()}),Ek=c.union([xk,Rk]),Pk=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({type:c.literal("string"),enum:c.array(c.string())}),default:c.array(c.string()).optional()}),Ak=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({anyOf:c.array(c.object({const:c.string(),title:c.string()}))}),default:c.array(c.string()).optional()}),Ik=c.union([Pk,Ak]),Ck=c.union([Tk,Ek,Ik]),Ok=c.union([Ck,Sk,_k,$k]),Nk=$r.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ok),required:c.array(c.string()).optional()})}),jk=$r.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),Lk=c.union([Nk,jk]),Dk=Ee.extend({method:c.literal("elicitation/create"),params:Lk}),Uk=st.extend({elicitationId:c.string()}),zk=ot.extend({method:c.literal("notifications/elicitation/complete"),params:Uk}),Ln=Pe.extend({action:c.enum(["accept","decline","cancel"]),content:c.preprocess(t=>t===null?void 0:t,c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())])).optional())}),qk=c.object({type:c.literal("ref/resource"),uri:c.string()}),Mk=c.object({type:c.literal("ref/prompt"),name:c.string()}),Bk=Ye.extend({ref:c.union([Mk,qk]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),io=Ee.extend({method:c.literal("completion/complete"),params:Bk});Fk=Pe.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),Hk=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Kk=Ee.extend({method:c.literal("roots/list"),params:Ye.optional()}),ka=Pe.extend({roots:c.array(Hk)}),Vk=ot.extend({method:c.literal("notifications/roots/list_changed"),params:st.optional()}),OA=c.union([Ks,ua,io,wa,ro,no,Xs,eo,to,Kv,Gv,jn,so,Gs,Js,Zs,Qs]),NA=c.union([Hs,Vs,pa,Vk,Ar]),jA=c.union([Fs,Or,va,Ln,ka,Ws,Ys,On]),LA=c.union([Ks,kk,Dk,Kk,Gs,Js,Zs,Qs]),DA=c.union([Hs,Vs,fk,Jv,Fv,dk,ok,Ar,zk]),UA=c.union([Fs,Cv,Fk,sk,Qv,zv,qv,Bv,oo,lk,Ws,Ys,On]),z=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===F.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new oa(s.elicitations,n)}return new t(e,n,r)}},oa=class extends z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(F.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Kt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Vp=j(()=>{});var Wp,Gp,Jp,ao=j(()=>{Wp=Symbol("Let zodToJsonSchema decide on which parser to use"),Gp={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Jp=t=>typeof t=="string"?{...Gp,name:t}:{...Gp,...t}});var Zp,Sa=j(()=>{ao();Zp=t=>{let e=Jp(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function _a(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ie(t,e,n,r,s){t[e]=n,_a(t,e,r,s)}var Vt=j(()=>{});var lo,co=j(()=>{lo=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?lo(e,t.currentPath):e.join("/")}}var it=j(()=>{co()});import{ZodFirstPartyTypeKind as Gk}from"zod/v3";function Yp(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==Gk.ZodAny&&(n.items=K(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ie(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ie(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ie(n,"minItems",t.exactLength.value,t.exactLength.message,e),ie(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var $a=j(()=>{Vt();$e()});function Qp(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ie(n,"minimum",r.value,r.message,e):ie(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ie(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ie(n,"maximum",r.value,r.message,e):ie(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ie(n,"maximum",r.value,r.message,e));break;case"multipleOf":ie(n,"multipleOf",r.value,r.message,e);break}return n}var xa=j(()=>{Vt()});function Xp(){return{type:"boolean"}}var Ra=j(()=>{});function uo(t,e){return K(t.type._def,e)}var po=j(()=>{$e()});var ef,Ta=j(()=>{$e();ef=(t,e)=>K(t.innerType._def,e)});function Ea(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>Ea(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Wk(t,e)}}var Wk,Pa=j(()=>{Vt();Wk=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":ie(n,"minimum",r.value,r.message,e);break;case"max":ie(n,"maximum",r.value,r.message,e);break}return n}});function tf(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}var Aa=j(()=>{$e()});function nf(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):we(e)}var Ia=j(()=>{$e();it()});function rf(t){return{type:"string",enum:Array.from(t.values)}}var Ca=j(()=>{});function sf(t,e){let n=[K(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return n.forEach(o=>{if(Jk(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(r=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...l}=o;i=l}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}var Jk,Oa=j(()=>{$e();Jk=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function of(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var Na=j(()=>{});function fo(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ie(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ie(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ht(n,"email",r.message,e);break;case"format:idn-email":ht(n,"idn-email",r.message,e);break;case"pattern:zod":Me(n,ft.email,r.message,e);break}break;case"url":ht(n,"uri",r.message,e);break;case"uuid":ht(n,"uuid",r.message,e);break;case"regex":Me(n,r.regex,r.message,e);break;case"cuid":Me(n,ft.cuid,r.message,e);break;case"cuid2":Me(n,ft.cuid2,r.message,e);break;case"startsWith":Me(n,RegExp(`^${La(r.value,e)}`),r.message,e);break;case"endsWith":Me(n,RegExp(`${La(r.value,e)}$`),r.message,e);break;case"datetime":ht(n,"date-time",r.message,e);break;case"date":ht(n,"date",r.message,e);break;case"time":ht(n,"time",r.message,e);break;case"duration":ht(n,"duration",r.message,e);break;case"length":ie(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ie(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Me(n,RegExp(La(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&ht(n,"ipv4",r.message,e),r.version!=="v4"&&ht(n,"ipv6",r.message,e);break}case"base64url":Me(n,ft.base64url,r.message,e);break;case"jwt":Me(n,ft.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Me(n,ft.ipv4Cidr,r.message,e),r.version!=="v4"&&Me(n,ft.ipv6Cidr,r.message,e);break}case"emoji":Me(n,ft.emoji(),r.message,e);break;case"ulid":{Me(n,ft.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ht(n,"binary",r.message,e);break}case"contentEncoding:base64":{ie(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Me(n,ft.base64,r.message,e);break}}break}case"nanoid":Me(n,ft.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function La(t,e){return e.patternStrategy==="escape"?Yk(t):t}function Yk(t){let e="";for(let n=0;n<t.length;n++)Zk.has(t[n])||(e+="\\"),e+=t[n];return e}function ht(t,e,n,r){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ie(t,"format",e,n,r)}function Me(t,e,n,r){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:af(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ie(t,"pattern",af(e,r),n,r)}function af(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let l=0;l<r.length;l++){if(o){s+=r[l],o=!1;continue}if(n.i){if(i){if(r[l].match(/[a-z]/)){a?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),a=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],a=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(n.m){if(r[l]==="^"){s+=`(^|(?<=[\r
|
|
1082
1227
|
]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
|
|
1083
1228
|
]))`;continue}}if(n.s&&r[l]==="."){s+=i?`${r[l]}\r
|
|
1084
1229
|
`:`[${r[l]}\r
|
|
1085
|
-
]`;continue}s+=r[l],r[l]==="\\"?o=!0:i&&r[l]==="]"?i=!1:!i&&r[l]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}var Ra,dt,Sk,lo=j(()=>{Kt();dt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ra===void 0&&(Ra=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ra),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};Sk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Or}from"zod/v3";function co(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===Or.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===Or.ZodString&&t.keyType._def.checks?.length){let{type:r,...s}=ao(t.keyType._def,e);return{...n,propertyNames:s}}else{if(t.keyType?._def.typeName===Or.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Or.ZodBranded&&t.keyType._def.type._def.typeName===Or.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...s}=oo(t.keyType._def,e);return{...n,propertyNames:s}}}return n}var uo=j(()=>{_e();lo();io();ot()});function Fp(t,e){if(e.mapStrategy==="record")return co(t,e);let n=K(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),r=K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Pa=j(()=>{_e();uo();ot()});function Kp(t){let e=t.values,r=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(r.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}var Aa=j(()=>{});function Hp(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}var Ia=j(()=>{ot()});function Vp(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ca=j(()=>{});function Wp(t,e){if(e.target==="openApi3")return Gp(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Nr&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,o)=>{let i=Nr[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(r.length===n.length){let s=r.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:n.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(o=>!r.includes(o))],[])};return Gp(t,e)}var Nr,Gp,po=j(()=>{_e();Nr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Gp=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>K(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function Jp(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Nr[t.innerType._def.typeName],nullable:!0}:{type:[Nr[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Oa=j(()=>{_e();po()});function Zp(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",ma(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ie(n,"minimum",r.value,r.message,e):ie(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ie(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ie(n,"maximum",r.value,r.message,e):ie(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ie(n,"maximum",r.value,r.message,e));break;case"multipleOf":ie(n,"multipleOf",r.value,r.message,e);break}return n}var Na=j(()=>{Kt()});function Yp(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let d=xk(l);d&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);let p=K(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(r.properties[a]=p,d||s.push(a))}s.length&&(r.required=s);let i=$k(t,e);return i!==void 0&&(r.additionalProperties=i),r}function $k(t,e){if(t.catchall._def.typeName!=="ZodNever")return K(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function xk(t){try{return t.isOptional()}catch{return!0}}var ja=j(()=>{_e()});var Qp,La=j(()=>{_e();ot();Qp=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(t.innerType._def,e);let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:we(e)},n]}:we(e)}});var Xp,za=j(()=>{_e();Xp=(t,e)=>{if(e.pipeStrategy==="input")return K(t.in._def,e);if(e.pipeStrategy==="output")return K(t.out._def,e);let n=K(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=K(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}}});function ef(t,e){return K(t.type._def,e)}var Da=j(()=>{_e()});function tf(t,e){let r={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var Ua=j(()=>{Kt();_e()});function nf(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>K(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:K(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>K(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var qa=j(()=>{_e()});function rf(t){return{not:we(t)}}var Ma=j(()=>{ot()});function sf(t){return we(t)}var Ba=j(()=>{ot()});var of,Fa=j(()=>{_e();of=(t,e)=>K(t.innerType._def,e)});import{ZodFirstPartyTypeKind as oe}from"zod/v3";var af,Ka=j(()=>{ot();ga();ba();ya();io();wa();ka();Sa();_a();$a();xa();Ta();Pa();Aa();Ia();Ca();Oa();Na();ja();La();za();Da();uo();Ua();lo();qa();Ma();po();Ba();Fa();af=(t,e,n)=>{switch(e){case oe.ZodString:return ao(t,n);case oe.ZodNumber:return Zp(t,n);case oe.ZodObject:return Yp(t,n);case oe.ZodBigInt:return Np(t,n);case oe.ZodBoolean:return jp();case oe.ZodDate:return va(t,n);case oe.ZodUndefined:return rf(n);case oe.ZodNull:return Vp(n);case oe.ZodArray:return Op(t,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return Wp(t,n);case oe.ZodIntersection:return qp(t,n);case oe.ZodTuple:return nf(t,n);case oe.ZodRecord:return co(t,n);case oe.ZodLiteral:return Mp(t,n);case oe.ZodEnum:return Up(t);case oe.ZodNativeEnum:return Kp(t);case oe.ZodNullable:return Jp(t,n);case oe.ZodOptional:return Qp(t,n);case oe.ZodMap:return Fp(t,n);case oe.ZodSet:return tf(t,n);case oe.ZodLazy:return()=>t.getter()._def;case oe.ZodPromise:return ef(t,n);case oe.ZodNaN:case oe.ZodNever:return Hp(n);case oe.ZodEffects:return Dp(t,n);case oe.ZodAny:return we(n);case oe.ZodUnknown:return sf(n);case oe.ZodDefault:return zp(t,n);case oe.ZodBranded:return oo(t,n);case oe.ZodReadonly:return of(t,n);case oe.ZodCatch:return Lp(t,n);case oe.ZodPipeline:return Xp(t,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(r=>{})(e)}}});function K(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==Ap)return a}if(r&&!n){let a=Tk(r,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=af(t,t.typeName,e),i=typeof o=="function"?K(o(),e):o;if(i&&Rk(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var Tk,Rk,_e=j(()=>{no();Ka();so();ot();Tk=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ro(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},Rk=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var lf=j(()=>{});var Ha,Va=j(()=>{_e();ha();ot();Ha=(t,e)=>{let n=Cp(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[d,p])=>({...l,[d]:K(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,d]},!0)??we(n)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=K(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??we(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=s===void 0?r?{...o,[n.definitionPath]:r}:o:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:o}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var cf=j(()=>{no();ha();Kt();so();_e();lf();ot();ga();ba();ya();io();wa();ka();Sa();_a();$a();xa();Ta();Pa();Aa();Ia();Ca();Oa();Na();ja();La();za();Da();Fa();uo();Ua();lo();qa();Ma();po();Ba();Ka();Va();Va()});import*as uf from"zod/v4-mini";function Ek(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Ga(t,e){return wt(t)?uf.toJSONSchema(t,{target:Ek(e?.target),io:e?.pipeStrategy??"input"}):Ha(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Wa(t){let n=Mt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=An(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Ja(t,e){let n=qt(t,e);if(!n.success)throw n.error;return n.data}var Za=j(()=>{Sr();cf()});function df(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function pf(t,e){let n={...t};for(let r in e){let s=r,o=e[s];if(o===void 0)continue;let i=n[s];df(i)&&df(o)?n[s]={...i,...o}:n[s]=o}return n}var Pk,fo,ff=j(()=>{Sr();Ln();Ep();Za();Pk=6e4,fo=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Us,n=>{this._oncancel(n)}),this.setNotificationHandler(Ms,n=>{this._onprogress(n)}),this.setRequestHandler(qs,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Bs,async(n,r)=>{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new U(B.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Ks,async(n,r)=>{let s=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,d=l.id,p=this._requestResolvers.get(d);if(p)if(this._requestResolvers.delete(d),a.type==="response")p(l);else{let h=l,_=new U(h.error.code,h.error.message,h.error.data);p(_)}else{let h=a.type==="response"?"Response":"Error";this._onerror(new Error(`${h} handler missing for request ${d}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new U(B.InvalidParams,`Task not found: ${o}`);if(!Ft(i.status))return await this._waitForTaskUpdate(o,r.signal),await s();if(Ft(i.status)){let a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Bt]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Hs,async(n,r)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new U(B.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Gs,async(n,r)=>{try{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new U(B.InvalidParams,`Task not found: ${n.params.taskId}`);if(Ft(s.status))throw new U(B.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new U(B.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof U?s:new U(B.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),U.fromError(B.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),$r(o)||bp(o)?this._onresponse(o):ea(o)?this._onrequest(o,i):gp(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=U.fromError(B.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Bt]?.taskId;if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:B.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):s?.send(p).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=fp(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,d={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let h={relatedRequestId:e.id};o&&(h.relatedTask={taskId:o}),await this.notification(p,h)},sendRequest:async(p,h,_)=>{if(i.signal.aborted)throw new U(B.ConnectionClosed,"Request was cancelled");let y={..._,relatedRequestId:e.id};o&&!y.relatedTask&&(y.relatedTask={taskId:o});let w=y.relatedTask?.taskId??o;return w&&l&&await l.updateTaskStatus(w,"input_required"),await this.request(p,h,y)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,d)).then(async p=>{if(i.signal.aborted)return;let h={result:p,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:h,timestamp:Date.now()},s?.sessionId):await s?.send(h)},async p=>{if(i.signal.aborted)return;let h={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:B.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},s?.sessionId):await s?.send(h)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,s=Number(n),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),$r(e))r(e);else{let i=new U(e.error.code,e.error.message,e.error.data);r(i)}return}let s=this._responseHandlers.get(n);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if($r(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,n))}}if(o||this._progressHandlers.delete(n),$r(e))s(e);else{let i=U.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:s}=r??{};if(!s){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof U?i:new U(B.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Cn,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new U(B.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Ft(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)}:a.status==="failed"?yield{type:"error",error:new U(B.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new U(B.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(d=>setTimeout(d,l)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof U?i:new U(B.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=r??{};return new Promise((d,p)=>{let h=I=>{p(I)};if(!this._transport){h(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(I){h(I);return}r?.signal?.throwIfAborted();let _=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:_};r?.onprogress&&(this._progressHandlers.set(_,r.onprogress),y.params={...e.params,_meta:{...e.params?._meta||{},progressToken:_}}),a&&(y.params={...y.params,task:a}),l&&(y.params={...y.params,_meta:{...y.params?._meta||{},[Bt]:l}});let w=I=>{this._responseHandlers.delete(_),this._progressHandlers.delete(_),this._cleanupTimeout(_),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(I)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(se=>this._onerror(new Error(`Failed to send cancellation: ${se}`)));let D=I instanceof U?I:new U(B.RequestTimeout,String(I));p(D)};this._responseHandlers.set(_,I=>{if(!r?.signal?.aborted){if(I instanceof Error)return p(I);try{let D=qt(n,I.result);D.success?d(D.data):p(D.error)}catch(D){p(D)}}}),r?.signal?.addEventListener("abort",()=>{w(r?.signal?.reason)});let T=r?.timeout??Pk,R=()=>w(U.fromError(B.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(_,T,r?.maxTotalTimeout,R,r?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let I=D=>{let se=this._responseHandlers.get(_);se?se(D):this._onerror(new Error(`Response handler missing for side-channeled request ${_}`))};this._requestResolvers.set(_,I),this._enqueueTaskMessage(P,{type:"request",message:y,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(_),p(D)})}else this._transport.send(y,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(_),p(I)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Fs,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Vs,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},vp,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Bt]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Bt]:n.relatedTask}}}),this._transport?.send(a,n).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Bt]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Wa(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,o)=>{let i=Ja(e,s);return Promise.resolve(n(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let r=Wa(e);this._notificationHandlers.set(r,s=>{let o=Ja(e,s);return Promise.resolve(n(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,s)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let s of r)if(s.type==="request"&&ea(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new U(B.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(r=s.pollInterval)}catch{}return new Promise((s,o)=>{if(n.aborted){o(new U(B.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,r);n.addEventListener("abort",()=>{clearTimeout(i),o(new U(B.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await r.createTask(s,e.id,{method:e.method,params:e.params},n)},getTask:async s=>{let o=await r.getTask(s,n);if(!o)throw new U(B.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await r.storeTaskResult(s,o,i,n);let a=await r.getTask(s,n);if(a){let l=Pr.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Ft(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>r.getTaskResult(s,n),updateTaskStatus:async(s,o,i)=>{let a=await r.getTask(s,n);if(!a)throw new U(B.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Ft(a.status))throw new U(B.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(s,o,i,n);let l=await r.getTask(s,n);if(l){let d=Pr.parse({method:"notifications/tasks/status",params:l});await this.notification(d),Ft(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}});var zr=L(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.regexpCode=de.getEsmExportName=de.getProperty=de.safeStringify=de.stringify=de.strConcat=de.addCodeArg=de.str=de._=de.nil=de._Code=de.Name=de.IDENTIFIER=de._CodeOrName=void 0;var jr=class{};de._CodeOrName=jr;de.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var on=class extends jr{constructor(e){if(super(),!de.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};de.Name=on;var it=class extends jr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof on&&(n[r.str]=(n[r.str]||0)+1),n),{})}};de._Code=it;de.nil=new it("");function hf(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Qa(n,e[r]),n.push(t[++r]);return new it(n)}de._=hf;var Ya=new it("+");function mf(t,...e){let n=[Lr(t[0])],r=0;for(;r<e.length;)n.push(Ya),Qa(n,e[r]),n.push(Ya,Lr(t[++r]));return Ak(n),new it(n)}de.str=mf;function Qa(t,e){e instanceof it?t.push(...e._items):e instanceof on?t.push(e):t.push(Ok(e))}de.addCodeArg=Qa;function Ak(t){let e=1;for(;e<t.length-1;){if(t[e]===Ya){let n=Ik(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function Ik(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof on||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof on))return`"${t}${e.slice(1)}`}function Ck(t,e){return e.emptyStr()?t:t.emptyStr()?e:mf`${t}${e}`}de.strConcat=Ck;function Ok(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Lr(Array.isArray(t)?t.join(","):t)}function Nk(t){return new it(Lr(t))}de.stringify=Nk;function Lr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}de.safeStringify=Lr;function jk(t){return typeof t=="string"&&de.IDENTIFIER.test(t)?new it(`.${t}`):hf`[${t}]`}de.getProperty=jk;function Lk(t){if(typeof t=="string"&&de.IDENTIFIER.test(t))return new it(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}de.getEsmExportName=Lk;function zk(t){return new it(t.toString())}de.regexpCode=zk});var tl=L(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.ValueScope=He.ValueScopeName=He.Scope=He.varKinds=He.UsedValueState=void 0;var Ke=zr(),Xa=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ho;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ho||(He.UsedValueState=ho={}));He.varKinds={const:new Ke.Name("const"),let:new Ke.Name("let"),var:new Ke.Name("var")};var mo=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Ke.Name?e:this.name(e)}name(e){return new Ke.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};He.Scope=mo;var go=class extends Ke.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Ke._)`.${new Ke.Name(n)}[${r}]`}};He.ValueScopeName=go;var Dk=(0,Ke._)`\n`,el=class extends mo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Dk:Ke.nil}}get(){return this._scope}name(e){return new go(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(r=n.key)!==null&&r!==void 0?r:n.ref,a=this._values[o];if(a){let p=a.get(i);if(p)return p}else a=this._values[o]=new Map;a.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),d=l.length;return l[d]=n.ref,s.setValue(n,{property:o,itemIndex:d}),s}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Ke._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},n,r)}_reduceValues(e,n,r={},s){let o=Ke.nil;for(let i in e){let a=e[i];if(!a)continue;let l=r[i]=r[i]||new Map;a.forEach(d=>{if(l.has(d))return;l.set(d,ho.Started);let p=n(d);if(p){let h=this.opts.es5?He.varKinds.var:He.varKinds.const;o=(0,Ke._)`${o}${h} ${d} = ${p};${this.opts._n}`}else if(p=s?.(d))o=(0,Ke._)`${o}${p}${this.opts._n}`;else throw new Xa(d);l.set(d,ho.Completed)})}return o}};He.ValueScope=el});var X=L(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.or=ee.and=ee.not=ee.CodeGen=ee.operators=ee.varKinds=ee.ValueScopeName=ee.ValueScope=ee.Scope=ee.Name=ee.regexpCode=ee.stringify=ee.getProperty=ee.nil=ee.strConcat=ee.str=ee._=void 0;var ae=zr(),ft=tl(),Ht=zr();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return Ht._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return Ht.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return Ht.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return Ht.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return Ht.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return Ht.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return Ht.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return Ht.Name}});var vo=tl();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return vo.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return vo.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return vo.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return vo.varKinds}});ee.operators={GT:new ae._Code(">"),GTE:new ae._Code(">="),LT:new ae._Code("<"),LTE:new ae._Code("<="),EQ:new ae._Code("==="),NEQ:new ae._Code("!=="),NOT:new ae._Code("!"),OR:new ae._Code("||"),AND:new ae._Code("&&"),ADD:new ae._Code("+")};var Et=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},nl=class extends Et{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?ft.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${s};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=Dn(this.rhs,e,n)),this}get names(){return this.rhs instanceof ae._CodeOrName?this.rhs.names:{}}},bo=class extends Et{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof ae.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Dn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ae.Name?{}:{...this.lhs.names};return wo(e,this.rhs)}},rl=class extends bo{constructor(e,n,r,s){super(e,r,s),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},sl=class extends Et{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ol=class extends Et{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},il=class extends Et{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},al=class extends Et{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=Dn(this.code,e,n),this}get names(){return this.code instanceof ae._CodeOrName?this.code.names:{}}},Dr=class extends Et{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,s=r.length;for(;s--;){let o=r[s];o.optimizeNames(e,n)||(Uk(e,o.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>cn(e,n.names),{})}},Pt=class extends Dr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},ll=class extends Dr{},zn=class extends Pt{};zn.kind="else";var an=class t extends Pt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new zn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(gf(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=Dn(this.condition,e,n),this}get names(){let e=super.names;return wo(e,this.condition),this.else&&cn(e,this.else.names),e}};an.kind="if";var ln=class extends Pt{};ln.kind="for";var cl=class extends ln{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=Dn(this.iteration,e,n),this}get names(){return cn(super.names,this.iteration.names)}},ul=class extends ln{constructor(e,n,r,s){super(),this.varKind=e,this.name=n,this.from=r,this.to=s}render(e){let n=e.es5?ft.varKinds.var:this.varKind,{name:r,from:s,to:o}=this;return`for(${n} ${r}=${s}; ${r}<${o}; ${r}++)`+super.render(e)}get names(){let e=wo(super.names,this.from);return wo(e,this.to)}},yo=class extends ln{constructor(e,n,r,s){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=Dn(this.iterable,e,n),this}get names(){return cn(super.names,this.iterable.names)}},Ur=class extends Pt{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ur.kind="func";var qr=class extends Dr{render(e){return"return "+super.render(e)}};qr.kind="return";var dl=class extends Pt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,s;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(s=this.finally)===null||s===void 0||s.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&cn(e,this.catch.names),this.finally&&cn(e,this.finally.names),e}},Mr=class extends Pt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Mr.kind="catch";var Br=class extends Pt{render(e){return"finally"+super.render(e)}};Br.kind="finally";var pl=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
1086
|
-
`:""},this._extScope=e,this._scope=new ft.Scope({parent:e}),this._nodes=[new ll]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,s){let o=this._scope.toName(n);return r!==void 0&&s&&(this._constants[o.str]=r),this._leafNode(new nl(e,o,r)),o}const(e,n,r){return this._def(ft.varKinds.const,e,n,r)}let(e,n,r){return this._def(ft.varKinds.let,e,n,r)}var(e,n,r){return this._def(ft.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new bo(e,n,r))}add(e,n){return this._leafNode(new rl(e,ee.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ae.nil&&this._leafNode(new al(e)),this}object(...e){let n=["{"];for(let[r,s]of e)n.length>1&&n.push(","),n.push(r),(r!==s||this.opts.es5)&&(n.push(":"),(0,ae.addCodeArg)(n,s));return n.push("}"),new ae._Code(n)}if(e,n,r){if(this._blockNode(new an(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new an(e))}else(){return this._elseNode(new zn)}endIf(){return this._endBlockNode(an,zn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new cl(e),n)}forRange(e,n,r,s,o=this.opts.es5?ft.varKinds.var:ft.varKinds.let){let i=this._scope.toName(e);return this._for(new ul(o,i,n,r),()=>s(i))}forOf(e,n,r,s=ft.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=n instanceof ae.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,ae._)`${i}.length`,a=>{this.var(o,(0,ae._)`${i}[${a}]`),r(o)})}return this._for(new yo("of",s,o,n),()=>r(o))}forIn(e,n,r,s=this.opts.es5?ft.varKinds.var:ft.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ae._)`Object.keys(${n})`,r);let o=this._scope.toName(e);return this._for(new yo("in",s,o,n),()=>r(o))}endFor(){return this._endBlockNode(ln)}label(e){return this._leafNode(new sl(e))}break(e){return this._leafNode(new ol(e))}return(e){let n=new qr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(qr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new dl;if(this._blockNode(s),this.code(e),n){let o=this.name("e");this._currNode=s.catch=new Mr(o),n(o)}return r&&(this._currNode=s.finally=new Br,this.code(r)),this._endBlockNode(Mr,Br)}throw(e){return this._leafNode(new il(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=ae.nil,r,s){return this._blockNode(new Ur(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Ur)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof an))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};ee.CodeGen=pl;function cn(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function wo(t,e){return e instanceof ae._CodeOrName?cn(t,e.names):t}function Dn(t,e,n){if(t instanceof ae.Name)return r(t);if(!s(t))return t;return new ae._Code(t._items.reduce((o,i)=>(i instanceof ae.Name&&(i=r(i)),i instanceof ae._Code?o.push(...i._items):o.push(i),o),[]));function r(o){let i=n[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof ae._Code&&o._items.some(i=>i instanceof ae.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function Uk(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function gf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ae._)`!${fl(t)}`}ee.not=gf;var qk=bf(ee.operators.AND);function Mk(...t){return t.reduce(qk)}ee.and=Mk;var Bk=bf(ee.operators.OR);function Fk(...t){return t.reduce(Bk)}ee.or=Fk;function bf(t){return(e,n)=>e===ae.nil?n:n===ae.nil?e:(0,ae._)`${fl(e)} ${t} ${fl(n)}`}function fl(t){return t instanceof ae.Name?t:(0,ae._)`(${t})`}});var le=L(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.checkStrictMode=te.getErrorPath=te.Type=te.useFunc=te.setEvaluated=te.evaluatedPropsToName=te.mergeEvaluated=te.eachItem=te.unescapeJsonPointer=te.escapeJsonPointer=te.escapeFragment=te.unescapeFragment=te.schemaRefOrVal=te.schemaHasRulesButRef=te.schemaHasRules=te.checkUnknownRules=te.alwaysValidSchema=te.toHash=void 0;var ge=X(),Kk=zr();function Hk(t){let e={};for(let n of t)e[n]=!0;return e}te.toHash=Hk;function Vk(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(vf(t,e),!kf(e,t.self.RULES.all))}te.alwaysValidSchema=Vk;function vf(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let s=r.RULES.keywords;for(let o in e)s[o]||$f(t,`unknown keyword: "${o}"`)}te.checkUnknownRules=vf;function kf(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}te.schemaHasRules=kf;function Gk(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}te.schemaHasRulesButRef=Gk;function Wk({topSchemaRef:t,schemaPath:e},n,r,s){if(!s){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,ge._)`${n}`}return(0,ge._)`${t}${e}${(0,ge.getProperty)(r)}`}te.schemaRefOrVal=Wk;function Jk(t){return Sf(decodeURIComponent(t))}te.unescapeFragment=Jk;function Zk(t){return encodeURIComponent(ml(t))}te.escapeFragment=Zk;function ml(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}te.escapeJsonPointer=ml;function Sf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}te.unescapeJsonPointer=Sf;function Yk(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}te.eachItem=Yk;function yf({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(s,o,i,a)=>{let l=i===void 0?o:i instanceof ge.Name?(o instanceof ge.Name?t(s,o,i):e(s,o,i),i):o instanceof ge.Name?(e(s,i,o),o):n(o,i);return a===ge.Name&&!(l instanceof ge.Name)?r(s,l):l}}te.mergeEvaluated={props:yf({mergeNames:(t,e,n)=>t.if((0,ge._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,ge._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,ge._)`${n} || {}`).code((0,ge._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,ge._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,ge._)`${n} || {}`),gl(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:_f}),items:yf({mergeNames:(t,e,n)=>t.if((0,ge._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,ge._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,ge._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,ge._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function _f(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,ge._)`{}`);return e!==void 0&&gl(t,n,e),n}te.evaluatedPropsToName=_f;function gl(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(r)}`,!0))}te.setEvaluated=gl;var wf={};function Qk(t,e){return t.scopeValue("func",{ref:e,code:wf[e.code]||(wf[e.code]=new Kk._Code(e.code))})}te.useFunc=Qk;var hl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(hl||(te.Type=hl={}));function Xk(t,e,n){if(t instanceof ge.Name){let r=e===hl.Num;return n?r?(0,ge._)`"[" + ${t} + "]"`:(0,ge._)`"['" + ${t} + "']"`:r?(0,ge._)`"/" + ${t}`:(0,ge._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,ge.getProperty)(t).toString():"/"+ml(t)}te.getErrorPath=Xk;function $f(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}te.checkStrictMode=$f});var At=L(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var Oe=X(),eS={data:new Oe.Name("data"),valCxt:new Oe.Name("valCxt"),instancePath:new Oe.Name("instancePath"),parentData:new Oe.Name("parentData"),parentDataProperty:new Oe.Name("parentDataProperty"),rootData:new Oe.Name("rootData"),dynamicAnchors:new Oe.Name("dynamicAnchors"),vErrors:new Oe.Name("vErrors"),errors:new Oe.Name("errors"),this:new Oe.Name("this"),self:new Oe.Name("self"),scope:new Oe.Name("scope"),json:new Oe.Name("json"),jsonPos:new Oe.Name("jsonPos"),jsonLen:new Oe.Name("jsonLen"),jsonPart:new Oe.Name("jsonPart")};bl.default=eS});var Fr=L(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.extendErrors=Ne.resetErrorsCount=Ne.reportExtraError=Ne.reportError=Ne.keyword$DataError=Ne.keywordError=void 0;var ce=X(),ko=le(),qe=At();Ne.keywordError={message:({keyword:t})=>(0,ce.str)`must pass "${t}" keyword validation`};Ne.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ce.str)`"${t}" keyword must be ${e} ($data)`:(0,ce.str)`"${t}" keyword is invalid ($data)`};function tS(t,e=Ne.keywordError,n,r){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=Rf(t,e,n);r??(i||a)?xf(o,l):Tf(s,(0,ce._)`[${l}]`)}Ne.reportError=tS;function nS(t,e=Ne.keywordError,n){let{it:r}=t,{gen:s,compositeRule:o,allErrors:i}=r,a=Rf(t,e,n);xf(s,a),o||i||Tf(r,qe.default.vErrors)}Ne.reportExtraError=nS;function rS(t,e){t.assign(qe.default.errors,e),t.if((0,ce._)`${qe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ce._)`${qe.default.vErrors}.length`,e),()=>t.assign(qe.default.vErrors,null)))}Ne.resetErrorsCount=rS;function sS({gen:t,keyword:e,schemaValue:n,data:r,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,qe.default.errors,a=>{t.const(i,(0,ce._)`${qe.default.vErrors}[${a}]`),t.if((0,ce._)`${i}.instancePath === undefined`,()=>t.assign((0,ce._)`${i}.instancePath`,(0,ce.strConcat)(qe.default.instancePath,o.errorPath))),t.assign((0,ce._)`${i}.schemaPath`,(0,ce.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,ce._)`${i}.schema`,n),t.assign((0,ce._)`${i}.data`,r))})}Ne.extendErrors=sS;function xf(t,e){let n=t.const("err",e);t.if((0,ce._)`${qe.default.vErrors} === null`,()=>t.assign(qe.default.vErrors,(0,ce._)`[${n}]`),(0,ce._)`${qe.default.vErrors}.push(${n})`),t.code((0,ce._)`${qe.default.errors}++`)}function Tf(t,e){let{gen:n,validateName:r,schemaEnv:s}=t;s.$async?n.throw((0,ce._)`new ${t.ValidationError}(${e})`):(n.assign((0,ce._)`${r}.errors`,e),n.return(!1))}var un={keyword:new ce.Name("keyword"),schemaPath:new ce.Name("schemaPath"),params:new ce.Name("params"),propertyName:new ce.Name("propertyName"),message:new ce.Name("message"),schema:new ce.Name("schema"),parentSchema:new ce.Name("parentSchema")};function Rf(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,ce._)`{}`:oS(t,e,n)}function oS(t,e,n={}){let{gen:r,it:s}=t,o=[iS(s,n),aS(t,n)];return lS(t,e,o),r.object(...o)}function iS({errorPath:t},{instancePath:e}){let n=e?(0,ce.str)`${t}${(0,ko.getErrorPath)(e,ko.Type.Str)}`:t;return[qe.default.instancePath,(0,ce.strConcat)(qe.default.instancePath,n)]}function aS({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let s=r?e:(0,ce.str)`${e}/${t}`;return n&&(s=(0,ce.str)`${s}${(0,ko.getErrorPath)(n,ko.Type.Str)}`),[un.schemaPath,s]}function lS(t,{params:e,message:n},r){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:d,topSchemaRef:p,schemaPath:h}=a;r.push([un.keyword,s],[un.params,typeof e=="function"?e(t):e||(0,ce._)`{}`]),l.messages&&r.push([un.message,typeof n=="function"?n(t):n]),l.verbose&&r.push([un.schema,i],[un.parentSchema,(0,ce._)`${p}${h}`],[qe.default.data,o]),d&&r.push([un.propertyName,d])}});var Pf=L(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.boolOrEmptySchema=Un.topBoolOrEmptySchema=void 0;var cS=Fr(),uS=X(),dS=At(),pS={message:"boolean schema is false"};function fS(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Ef(t,!1):typeof n=="object"&&n.$async===!0?e.return(dS.default.data):(e.assign((0,uS._)`${r}.errors`,null),e.return(!0))}Un.topBoolOrEmptySchema=fS;function hS(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Ef(t)):n.var(e,!0)}Un.boolOrEmptySchema=hS;function Ef(t,e){let{gen:n,data:r}=t,s={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,cS.reportError)(s,pS,void 0,e)}});var yl=L(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.getRules=qn.isJSONType=void 0;var mS=["string","number","integer","boolean","null","object","array"],gS=new Set(mS);function bS(t){return typeof t=="string"&&gS.has(t)}qn.isJSONType=bS;function yS(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}qn.getRules=yS});var wl=L(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.shouldUseRule=Vt.shouldUseGroup=Vt.schemaHasRulesForType=void 0;function wS({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&Af(t,r)}Vt.schemaHasRulesForType=wS;function Af(t,e){return e.rules.some(n=>If(t,n))}Vt.shouldUseGroup=Af;function If(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Vt.shouldUseRule=If});var Kr=L(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;var vS=yl(),kS=wl(),SS=Fr(),Y=X(),Cf=le(),Mn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Mn||(je.DataType=Mn={}));function _S(t){let e=Of(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}je.getSchemaTypes=_S;function Of(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(vS.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}je.getJSONTypes=Of;function $S(t,e){let{gen:n,data:r,opts:s}=t,o=xS(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,kS.schemaHasRulesForType)(t,e[0]));if(i){let a=kl(e,r,s.strictNumbers,Mn.Wrong);n.if(a,()=>{o.length?TS(t,e,o):Sl(t)})}return i}je.coerceAndCheckDataType=$S;var Nf=new Set(["string","number","integer","boolean","null"]);function xS(t,e){return e?t.filter(n=>Nf.has(n)||e==="array"&&n==="array"):[]}function TS(t,e,n){let{gen:r,data:s,opts:o}=t,i=r.let("dataType",(0,Y._)`typeof ${s}`),a=r.let("coerced",(0,Y._)`undefined`);o.coerceTypes==="array"&&r.if((0,Y._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,Y._)`${s}[0]`).assign(i,(0,Y._)`typeof ${s}`).if(kl(e,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,Y._)`${a} !== undefined`);for(let d of n)(Nf.has(d)||d==="array"&&o.coerceTypes==="array")&&l(d);r.else(),Sl(t),r.endIf(),r.if((0,Y._)`${a} !== undefined`,()=>{r.assign(s,a),RS(t,a)});function l(d){switch(d){case"string":r.elseIf((0,Y._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Y._)`"" + ${s}`).elseIf((0,Y._)`${s} === null`).assign(a,(0,Y._)`""`);return;case"number":r.elseIf((0,Y._)`${i} == "boolean" || ${s} === null
|
|
1230
|
+
]`;continue}s+=r[l],r[l]==="\\"?o=!0:i&&r[l]==="]"?i=!1:!i&&r[l]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}var ja,ft,Zk,ho=j(()=>{Vt();ft={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ja===void 0&&(ja=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ja),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};Zk=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Nr}from"zod/v3";function mo(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===Nr.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===Nr.ZodString&&t.keyType._def.checks?.length){let{type:r,...s}=fo(t.keyType._def,e);return{...n,propertyNames:s}}else{if(t.keyType?._def.typeName===Nr.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Nr.ZodBranded&&t.keyType._def.type._def.typeName===Nr.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...s}=uo(t.keyType._def,e);return{...n,propertyNames:s}}}return n}var go=j(()=>{$e();ho();po();it()});function lf(t,e){if(e.mapStrategy==="record")return mo(t,e);let n=K(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),r=K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Da=j(()=>{$e();go();it()});function cf(t){let e=t.values,r=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(r.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}var Ua=j(()=>{});function df(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}var za=j(()=>{it()});function uf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var qa=j(()=>{});function ff(t,e){if(e.target==="openApi3")return pf(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in jr&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,o)=>{let i=jr[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(r.length===n.length){let s=r.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:n.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(o=>!r.includes(o))],[])};return pf(t,e)}var jr,pf,yo=j(()=>{$e();jr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};pf=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>K(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function hf(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:jr[t.innerType._def.typeName],nullable:!0}:{type:[jr[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Ma=j(()=>{$e();yo()});function mf(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",_a(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ie(n,"minimum",r.value,r.message,e):ie(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ie(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ie(n,"maximum",r.value,r.message,e):ie(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ie(n,"maximum",r.value,r.message,e));break;case"multipleOf":ie(n,"multipleOf",r.value,r.message,e);break}return n}var Ba=j(()=>{Vt()});function gf(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let p=Xk(l);p&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),p=!1);let u=K(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(r.properties[a]=u,p||s.push(a))}s.length&&(r.required=s);let i=Qk(t,e);return i!==void 0&&(r.additionalProperties=i),r}function Qk(t,e){if(t.catchall._def.typeName!=="ZodNever")return K(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Xk(t){try{return t.isOptional()}catch{return!0}}var Fa=j(()=>{$e()});var yf,Ha=j(()=>{$e();it();yf=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(t.innerType._def,e);let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:we(e)},n]}:we(e)}});var bf,Ka=j(()=>{$e();bf=(t,e)=>{if(e.pipeStrategy==="input")return K(t.in._def,e);if(e.pipeStrategy==="output")return K(t.out._def,e);let n=K(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=K(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}}});function wf(t,e){return K(t.type._def,e)}var Va=j(()=>{$e()});function vf(t,e){let r={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var Ga=j(()=>{Vt();$e()});function kf(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>K(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:K(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>K(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var Wa=j(()=>{$e()});function Sf(t){return{not:we(t)}}var Ja=j(()=>{it()});function _f(t){return we(t)}var Za=j(()=>{it()});var $f,Ya=j(()=>{$e();$f=(t,e)=>K(t.innerType._def,e)});import{ZodFirstPartyTypeKind as oe}from"zod/v3";var xf,Qa=j(()=>{it();$a();xa();Ra();po();Ta();Pa();Aa();Ia();Ca();Oa();Na();Da();Ua();za();qa();Ma();Ba();Fa();Ha();Ka();Va();go();Ga();ho();Wa();Ja();yo();Za();Ya();xf=(t,e,n)=>{switch(e){case oe.ZodString:return fo(t,n);case oe.ZodNumber:return mf(t,n);case oe.ZodObject:return gf(t,n);case oe.ZodBigInt:return Qp(t,n);case oe.ZodBoolean:return Xp();case oe.ZodDate:return Ea(t,n);case oe.ZodUndefined:return Sf(n);case oe.ZodNull:return uf(n);case oe.ZodArray:return Yp(t,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return ff(t,n);case oe.ZodIntersection:return sf(t,n);case oe.ZodTuple:return kf(t,n);case oe.ZodRecord:return mo(t,n);case oe.ZodLiteral:return of(t,n);case oe.ZodEnum:return rf(t);case oe.ZodNativeEnum:return cf(t);case oe.ZodNullable:return hf(t,n);case oe.ZodOptional:return yf(t,n);case oe.ZodMap:return lf(t,n);case oe.ZodSet:return vf(t,n);case oe.ZodLazy:return()=>t.getter()._def;case oe.ZodPromise:return wf(t,n);case oe.ZodNaN:case oe.ZodNever:return df(n);case oe.ZodEffects:return nf(t,n);case oe.ZodAny:return we(n);case oe.ZodUnknown:return _f(n);case oe.ZodDefault:return tf(t,n);case oe.ZodBranded:return uo(t,n);case oe.ZodReadonly:return $f(t,n);case oe.ZodCatch:return ef(t,n);case oe.ZodPipeline:return bf(t,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(r=>{})(e)}}});function K(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==Wp)return a}if(r&&!n){let a=eS(r,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=xf(t,t.typeName,e),i=typeof o=="function"?K(o(),e):o;if(i&&tS(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var eS,tS,$e=j(()=>{ao();Qa();co();it();eS=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:lo(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},tS=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var Rf=j(()=>{});var Xa,el=j(()=>{$e();Sa();it();Xa=(t,e)=>{let n=Zp(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[p,u])=>({...l,[p]:K(u._def,{...n,currentPath:[...n.basePath,n.definitionPath,p]},!0)??we(n)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=K(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??we(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=s===void 0?r?{...o,[n.definitionPath]:r}:o:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:o}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var Tf=j(()=>{ao();Sa();Vt();co();$e();Rf();it();$a();xa();Ra();po();Ta();Pa();Aa();Ia();Ca();Oa();Na();Da();Ua();za();qa();Ma();Ba();Fa();Ha();Ka();Va();Ya();go();Ga();ho();Wa();Ja();yo();Za();Qa();el();el()});import*as Ef from"zod/v4-mini";function nS(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function tl(t,e){return vt(t)?Ef.toJSONSchema(t,{target:nS(e?.target),io:e?.pipeStrategy??"input"}):Xa(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function nl(t){let n=Ft(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=In(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function rl(t,e){let n=Bt(t,e);if(!n.success)throw n.error;return n.data}var sl=j(()=>{_r();Tf()});function Pf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Af(t,e){let n={...t};for(let r in e){let s=r,o=e[s];if(o===void 0)continue;let i=n[s];Pf(i)&&Pf(o)?n[s]={...i,...o}:n[s]=o}return n}var rS,bo,If=j(()=>{_r();Dn();Vp();sl();rS=6e4,bo=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Hs,n=>{this._oncancel(n)}),this.setNotificationHandler(Vs,n=>{this._onprogress(n)}),this.setRequestHandler(Ks,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Gs,async(n,r)=>{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(F.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Js,async(n,r)=>{let s=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,p=l.id,u=this._requestResolvers.get(p);if(u)if(this._requestResolvers.delete(p),a.type==="response")u(l);else{let m=l,x=new z(m.error.code,m.error.message,m.error.data);u(x)}else{let m=a.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${p}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new z(F.InvalidParams,`Task not found: ${o}`);if(!Kt(i.status))return await this._waitForTaskUpdate(o,r.signal),await s();if(Kt(i.status)){let a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Ht]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Zs,async(n,r)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new z(F.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Qs,async(n,r)=>{try{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(F.InvalidParams,`Task not found: ${n.params.taskId}`);if(Kt(s.status))throw new z(F.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new z(F.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof z?s:new z(F.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),z.fromError(F.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),xr(o)||jp(o)?this._onresponse(o):la(o)?this._onrequest(o,i):Np(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=z.fromError(F.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Ht]?.taskId;if(r===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:F.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},s?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):s?.send(u).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Ip(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,p={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let m={relatedRequestId:e.id};o&&(m.relatedTask={taskId:o}),await this.notification(u,m)},sendRequest:async(u,m,x)=>{if(i.signal.aborted)throw new z(F.ConnectionClosed,"Request was cancelled");let v={...x,relatedRequestId:e.id};o&&!v.relatedTask&&(v.relatedTask={taskId:o});let k=v.relatedTask?.taskId??o;return k&&l&&await l.updateTaskStatus(k,"input_required"),await this.request(u,m,v)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,p)).then(async u=>{if(i.signal.aborted)return;let m={result:u,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:m,timestamp:Date.now()},s?.sessionId):await s?.send(m)},async u=>{if(i.signal.aborted)return;let m={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:F.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:m,timestamp:Date.now()},s?.sessionId):await s?.send(m)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,s=Number(n),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),xr(e))r(e);else{let i=new z(e.error.code,e.error.message,e.error.data);r(i)}return}let s=this._responseHandlers.get(n);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(xr(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(o=!0,this._taskProgressTokens.set(a.taskId,n))}}if(o||this._progressHandlers.delete(n),xr(e))s(e);else{let i=z.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:s}=r??{};if(!s){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof z?i:new z(F.InternalError,String(i))}}return}let o;try{let i=await this.request(e,On,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(F.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Kt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)}:a.status==="failed"?yield{type:"error",error:new z(F.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(F.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(p=>setTimeout(p,l)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(F.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=r??{};return new Promise((p,u)=>{let m=I=>{u(I)};if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(I){m(I);return}r?.signal?.throwIfAborted();let x=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:x};r?.onprogress&&(this._progressHandlers.set(x,r.onprogress),v.params={...e.params,_meta:{...e.params?._meta||{},progressToken:x}}),a&&(v.params={...v.params,task:a}),l&&(v.params={...v.params,_meta:{...v.params?._meta||{},[Ht]:l}});let k=I=>{this._responseHandlers.delete(x),this._progressHandlers.delete(x),this._cleanupTimeout(x),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:x,reason:String(I)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(se=>this._onerror(new Error(`Failed to send cancellation: ${se}`)));let U=I instanceof z?I:new z(F.RequestTimeout,String(I));u(U)};this._responseHandlers.set(x,I=>{if(!r?.signal?.aborted){if(I instanceof Error)return u(I);try{let U=Bt(n,I.result);U.success?p(U.data):u(U.error)}catch(U){u(U)}}}),r?.signal?.addEventListener("abort",()=>{k(r?.signal?.reason)});let R=r?.timeout??rS,E=()=>k(z.fromError(F.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(x,R,r?.maxTotalTimeout,E,r?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let I=U=>{let se=this._responseHandlers.get(x);se?se(U):this._onerror(new Error(`Response handler missing for side-channeled request ${x}`))};this._requestResolvers.set(x,I),this._enqueueTaskMessage(P,{type:"request",message:v,timestamp:Date.now()}).catch(U=>{this._cleanupTimeout(x),u(U)})}else this._transport.send(v,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(x),u(I)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Ws,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Ys,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},Up,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Ht]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Ht]:n.relatedTask}}}),this._transport?.send(a,n).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Ht]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=nl(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,o)=>{let i=rl(e,s);return Promise.resolve(n(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let r=nl(e);this._notificationHandlers.set(r,s=>{let o=rl(e,s);return Promise.resolve(n(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,s)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let s of r)if(s.type==="request"&&la(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new z(F.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(r=s.pollInterval)}catch{}return new Promise((s,o)=>{if(n.aborted){o(new z(F.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,r);n.addEventListener("abort",()=>{clearTimeout(i),o(new z(F.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await r.createTask(s,e.id,{method:e.method,params:e.params},n)},getTask:async s=>{let o=await r.getTask(s,n);if(!o)throw new z(F.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await r.storeTaskResult(s,o,i,n);let a=await r.getTask(s,n);if(a){let l=Ar.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Kt(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>r.getTaskResult(s,n),updateTaskStatus:async(s,o,i)=>{let a=await r.getTask(s,n);if(!a)throw new z(F.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Kt(a.status))throw new z(F.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(s,o,i,n);let l=await r.getTask(s,n);if(l){let p=Ar.parse({method:"notifications/tasks/status",params:l});await this.notification(p),Kt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}});var Ur=L(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.regexpCode=ue.getEsmExportName=ue.getProperty=ue.safeStringify=ue.stringify=ue.strConcat=ue.addCodeArg=ue.str=ue._=ue.nil=ue._Code=ue.Name=ue.IDENTIFIER=ue._CodeOrName=void 0;var Lr=class{};ue._CodeOrName=Lr;ue.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ln=class extends Lr{constructor(e){if(super(),!ue.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ue.Name=ln;var at=class extends Lr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof ln&&(n[r.str]=(n[r.str]||0)+1),n),{})}};ue._Code=at;ue.nil=new at("");function Cf(t,...e){let n=[t[0]],r=0;for(;r<e.length;)il(n,e[r]),n.push(t[++r]);return new at(n)}ue._=Cf;var ol=new at("+");function Of(t,...e){let n=[Dr(t[0])],r=0;for(;r<e.length;)n.push(ol),il(n,e[r]),n.push(ol,Dr(t[++r]));return sS(n),new at(n)}ue.str=Of;function il(t,e){e instanceof at?t.push(...e._items):e instanceof ln?t.push(e):t.push(aS(e))}ue.addCodeArg=il;function sS(t){let e=1;for(;e<t.length-1;){if(t[e]===ol){let n=oS(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function oS(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ln||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof ln))return`"${t}${e.slice(1)}`}function iS(t,e){return e.emptyStr()?t:t.emptyStr()?e:Of`${t}${e}`}ue.strConcat=iS;function aS(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Dr(Array.isArray(t)?t.join(","):t)}function lS(t){return new at(Dr(t))}ue.stringify=lS;function Dr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ue.safeStringify=Dr;function cS(t){return typeof t=="string"&&ue.IDENTIFIER.test(t)?new at(`.${t}`):Cf`[${t}]`}ue.getProperty=cS;function dS(t){if(typeof t=="string"&&ue.IDENTIFIER.test(t))return new at(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ue.getEsmExportName=dS;function uS(t){return new at(t.toString())}ue.regexpCode=uS});var cl=L(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ValueScope=Ge.ValueScopeName=Ge.Scope=Ge.varKinds=Ge.UsedValueState=void 0;var Ve=Ur(),al=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},wo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(wo||(Ge.UsedValueState=wo={}));Ge.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};var vo=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Ve.Name?e:this.name(e)}name(e){return new Ve.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ge.Scope=vo;var ko=class extends Ve.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Ve._)`.${new Ve.Name(n)}[${r}]`}};Ge.ValueScopeName=ko;var pS=(0,Ve._)`\n`,ll=class extends vo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?pS:Ve.nil}}get(){return this._scope}name(e){return new ko(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(r=n.key)!==null&&r!==void 0?r:n.ref,a=this._values[o];if(a){let u=a.get(i);if(u)return u}else a=this._values[o]=new Map;a.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),p=l.length;return l[p]=n.ref,s.setValue(n,{property:o,itemIndex:p}),s}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Ve._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},n,r)}_reduceValues(e,n,r={},s){let o=Ve.nil;for(let i in e){let a=e[i];if(!a)continue;let l=r[i]=r[i]||new Map;a.forEach(p=>{if(l.has(p))return;l.set(p,wo.Started);let u=n(p);if(u){let m=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const;o=(0,Ve._)`${o}${m} ${p} = ${u};${this.opts._n}`}else if(u=s?.(p))o=(0,Ve._)`${o}${u}${this.opts._n}`;else throw new al(p);l.set(p,wo.Completed)})}return o}};Ge.ValueScope=ll});var ee=L(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.or=te.and=te.not=te.CodeGen=te.operators=te.varKinds=te.ValueScopeName=te.ValueScope=te.Scope=te.Name=te.regexpCode=te.stringify=te.getProperty=te.nil=te.strConcat=te.str=te._=void 0;var ae=Ur(),mt=cl(),Gt=Ur();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return Gt._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return Gt.str}});Object.defineProperty(te,"strConcat",{enumerable:!0,get:function(){return Gt.strConcat}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return Gt.nil}});Object.defineProperty(te,"getProperty",{enumerable:!0,get:function(){return Gt.getProperty}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return Gt.stringify}});Object.defineProperty(te,"regexpCode",{enumerable:!0,get:function(){return Gt.regexpCode}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return Gt.Name}});var xo=cl();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return xo.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return xo.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return xo.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return xo.varKinds}});te.operators={GT:new ae._Code(">"),GTE:new ae._Code(">="),LT:new ae._Code("<"),LTE:new ae._Code("<="),EQ:new ae._Code("==="),NEQ:new ae._Code("!=="),NOT:new ae._Code("!"),OR:new ae._Code("||"),AND:new ae._Code("&&"),ADD:new ae._Code("+")};var At=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},dl=class extends At{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?mt.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${s};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=zn(this.rhs,e,n)),this}get names(){return this.rhs instanceof ae._CodeOrName?this.rhs.names:{}}},So=class extends At{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof ae.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=zn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ae.Name?{}:{...this.lhs.names};return $o(e,this.rhs)}},ul=class extends So{constructor(e,n,r,s){super(e,r,s),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},pl=class extends At{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},fl=class extends At{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},hl=class extends At{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ml=class extends At{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=zn(this.code,e,n),this}get names(){return this.code instanceof ae._CodeOrName?this.code.names:{}}},zr=class extends At{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,s=r.length;for(;s--;){let o=r[s];o.optimizeNames(e,n)||(fS(e,o.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>un(e,n.names),{})}},It=class extends zr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},gl=class extends zr{},Un=class extends It{};Un.kind="else";var cn=class t extends It{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new Un(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Nf(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=zn(this.condition,e,n),this}get names(){let e=super.names;return $o(e,this.condition),this.else&&un(e,this.else.names),e}};cn.kind="if";var dn=class extends It{};dn.kind="for";var yl=class extends dn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=zn(this.iteration,e,n),this}get names(){return un(super.names,this.iteration.names)}},bl=class extends dn{constructor(e,n,r,s){super(),this.varKind=e,this.name=n,this.from=r,this.to=s}render(e){let n=e.es5?mt.varKinds.var:this.varKind,{name:r,from:s,to:o}=this;return`for(${n} ${r}=${s}; ${r}<${o}; ${r}++)`+super.render(e)}get names(){let e=$o(super.names,this.from);return $o(e,this.to)}},_o=class extends dn{constructor(e,n,r,s){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=zn(this.iterable,e,n),this}get names(){return un(super.names,this.iterable.names)}},qr=class extends It{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};qr.kind="func";var Mr=class extends zr{render(e){return"return "+super.render(e)}};Mr.kind="return";var wl=class extends It{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,s;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(s=this.finally)===null||s===void 0||s.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&un(e,this.catch.names),this.finally&&un(e,this.finally.names),e}},Br=class extends It{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Br.kind="catch";var Fr=class extends It{render(e){return"finally"+super.render(e)}};Fr.kind="finally";var vl=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
1231
|
+
`:""},this._extScope=e,this._scope=new mt.Scope({parent:e}),this._nodes=[new gl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,s){let o=this._scope.toName(n);return r!==void 0&&s&&(this._constants[o.str]=r),this._leafNode(new dl(e,o,r)),o}const(e,n,r){return this._def(mt.varKinds.const,e,n,r)}let(e,n,r){return this._def(mt.varKinds.let,e,n,r)}var(e,n,r){return this._def(mt.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new So(e,n,r))}add(e,n){return this._leafNode(new ul(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ae.nil&&this._leafNode(new ml(e)),this}object(...e){let n=["{"];for(let[r,s]of e)n.length>1&&n.push(","),n.push(r),(r!==s||this.opts.es5)&&(n.push(":"),(0,ae.addCodeArg)(n,s));return n.push("}"),new ae._Code(n)}if(e,n,r){if(this._blockNode(new cn(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new cn(e))}else(){return this._elseNode(new Un)}endIf(){return this._endBlockNode(cn,Un)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new yl(e),n)}forRange(e,n,r,s,o=this.opts.es5?mt.varKinds.var:mt.varKinds.let){let i=this._scope.toName(e);return this._for(new bl(o,i,n,r),()=>s(i))}forOf(e,n,r,s=mt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=n instanceof ae.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,ae._)`${i}.length`,a=>{this.var(o,(0,ae._)`${i}[${a}]`),r(o)})}return this._for(new _o("of",s,o,n),()=>r(o))}forIn(e,n,r,s=this.opts.es5?mt.varKinds.var:mt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ae._)`Object.keys(${n})`,r);let o=this._scope.toName(e);return this._for(new _o("in",s,o,n),()=>r(o))}endFor(){return this._endBlockNode(dn)}label(e){return this._leafNode(new pl(e))}break(e){return this._leafNode(new fl(e))}return(e){let n=new Mr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Mr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new wl;if(this._blockNode(s),this.code(e),n){let o=this.name("e");this._currNode=s.catch=new Br(o),n(o)}return r&&(this._currNode=s.finally=new Fr,this.code(r)),this._endBlockNode(Br,Fr)}throw(e){return this._leafNode(new hl(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=ae.nil,r,s){return this._blockNode(new qr(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(qr)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof cn))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};te.CodeGen=vl;function un(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function $o(t,e){return e instanceof ae._CodeOrName?un(t,e.names):t}function zn(t,e,n){if(t instanceof ae.Name)return r(t);if(!s(t))return t;return new ae._Code(t._items.reduce((o,i)=>(i instanceof ae.Name&&(i=r(i)),i instanceof ae._Code?o.push(...i._items):o.push(i),o),[]));function r(o){let i=n[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof ae._Code&&o._items.some(i=>i instanceof ae.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function fS(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Nf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ae._)`!${kl(t)}`}te.not=Nf;var hS=jf(te.operators.AND);function mS(...t){return t.reduce(hS)}te.and=mS;var gS=jf(te.operators.OR);function yS(...t){return t.reduce(gS)}te.or=yS;function jf(t){return(e,n)=>e===ae.nil?n:n===ae.nil?e:(0,ae._)`${kl(e)} ${t} ${kl(n)}`}function kl(t){return t instanceof ae.Name?t:(0,ae._)`(${t})`}});var le=L(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.checkStrictMode=ne.getErrorPath=ne.Type=ne.useFunc=ne.setEvaluated=ne.evaluatedPropsToName=ne.mergeEvaluated=ne.eachItem=ne.unescapeJsonPointer=ne.escapeJsonPointer=ne.escapeFragment=ne.unescapeFragment=ne.schemaRefOrVal=ne.schemaHasRulesButRef=ne.schemaHasRules=ne.checkUnknownRules=ne.alwaysValidSchema=ne.toHash=void 0;var ge=ee(),bS=Ur();function wS(t){let e={};for(let n of t)e[n]=!0;return e}ne.toHash=wS;function vS(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Uf(t,e),!zf(e,t.self.RULES.all))}ne.alwaysValidSchema=vS;function Uf(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let s=r.RULES.keywords;for(let o in e)s[o]||Bf(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=Uf;function zf(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ne.schemaHasRules=zf;function kS(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}ne.schemaHasRulesButRef=kS;function SS({topSchemaRef:t,schemaPath:e},n,r,s){if(!s){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,ge._)`${n}`}return(0,ge._)`${t}${e}${(0,ge.getProperty)(r)}`}ne.schemaRefOrVal=SS;function _S(t){return qf(decodeURIComponent(t))}ne.unescapeFragment=_S;function $S(t){return encodeURIComponent(_l(t))}ne.escapeFragment=$S;function _l(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=_l;function qf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=qf;function xS(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ne.eachItem=xS;function Lf({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(s,o,i,a)=>{let l=i===void 0?o:i instanceof ge.Name?(o instanceof ge.Name?t(s,o,i):e(s,o,i),i):o instanceof ge.Name?(e(s,i,o),o):n(o,i);return a===ge.Name&&!(l instanceof ge.Name)?r(s,l):l}}ne.mergeEvaluated={props:Lf({mergeNames:(t,e,n)=>t.if((0,ge._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,ge._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,ge._)`${n} || {}`).code((0,ge._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,ge._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,ge._)`${n} || {}`),$l(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Mf}),items:Lf({mergeNames:(t,e,n)=>t.if((0,ge._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,ge._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,ge._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,ge._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Mf(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,ge._)`{}`);return e!==void 0&&$l(t,n,e),n}ne.evaluatedPropsToName=Mf;function $l(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(r)}`,!0))}ne.setEvaluated=$l;var Df={};function RS(t,e){return t.scopeValue("func",{ref:e,code:Df[e.code]||(Df[e.code]=new bS._Code(e.code))})}ne.useFunc=RS;var Sl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Sl||(ne.Type=Sl={}));function TS(t,e,n){if(t instanceof ge.Name){let r=e===Sl.Num;return n?r?(0,ge._)`"[" + ${t} + "]"`:(0,ge._)`"['" + ${t} + "']"`:r?(0,ge._)`"/" + ${t}`:(0,ge._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,ge.getProperty)(t).toString():"/"+_l(t)}ne.getErrorPath=TS;function Bf(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}ne.checkStrictMode=Bf});var Ct=L(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});var Ne=ee(),ES={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};xl.default=ES});var Hr=L(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.extendErrors=je.resetErrorsCount=je.reportExtraError=je.reportError=je.keyword$DataError=je.keywordError=void 0;var ce=ee(),Ro=le(),Be=Ct();je.keywordError={message:({keyword:t})=>(0,ce.str)`must pass "${t}" keyword validation`};je.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ce.str)`"${t}" keyword must be ${e} ($data)`:(0,ce.str)`"${t}" keyword is invalid ($data)`};function PS(t,e=je.keywordError,n,r){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=Kf(t,e,n);r??(i||a)?Ff(o,l):Hf(s,(0,ce._)`[${l}]`)}je.reportError=PS;function AS(t,e=je.keywordError,n){let{it:r}=t,{gen:s,compositeRule:o,allErrors:i}=r,a=Kf(t,e,n);Ff(s,a),o||i||Hf(r,Be.default.vErrors)}je.reportExtraError=AS;function IS(t,e){t.assign(Be.default.errors,e),t.if((0,ce._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ce._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}je.resetErrorsCount=IS;function CS({gen:t,keyword:e,schemaValue:n,data:r,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,Be.default.errors,a=>{t.const(i,(0,ce._)`${Be.default.vErrors}[${a}]`),t.if((0,ce._)`${i}.instancePath === undefined`,()=>t.assign((0,ce._)`${i}.instancePath`,(0,ce.strConcat)(Be.default.instancePath,o.errorPath))),t.assign((0,ce._)`${i}.schemaPath`,(0,ce.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,ce._)`${i}.schema`,n),t.assign((0,ce._)`${i}.data`,r))})}je.extendErrors=CS;function Ff(t,e){let n=t.const("err",e);t.if((0,ce._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,ce._)`[${n}]`),(0,ce._)`${Be.default.vErrors}.push(${n})`),t.code((0,ce._)`${Be.default.errors}++`)}function Hf(t,e){let{gen:n,validateName:r,schemaEnv:s}=t;s.$async?n.throw((0,ce._)`new ${t.ValidationError}(${e})`):(n.assign((0,ce._)`${r}.errors`,e),n.return(!1))}var pn={keyword:new ce.Name("keyword"),schemaPath:new ce.Name("schemaPath"),params:new ce.Name("params"),propertyName:new ce.Name("propertyName"),message:new ce.Name("message"),schema:new ce.Name("schema"),parentSchema:new ce.Name("parentSchema")};function Kf(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,ce._)`{}`:OS(t,e,n)}function OS(t,e,n={}){let{gen:r,it:s}=t,o=[NS(s,n),jS(t,n)];return LS(t,e,o),r.object(...o)}function NS({errorPath:t},{instancePath:e}){let n=e?(0,ce.str)`${t}${(0,Ro.getErrorPath)(e,Ro.Type.Str)}`:t;return[Be.default.instancePath,(0,ce.strConcat)(Be.default.instancePath,n)]}function jS({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let s=r?e:(0,ce.str)`${e}/${t}`;return n&&(s=(0,ce.str)`${s}${(0,Ro.getErrorPath)(n,Ro.Type.Str)}`),[pn.schemaPath,s]}function LS(t,{params:e,message:n},r){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:p,topSchemaRef:u,schemaPath:m}=a;r.push([pn.keyword,s],[pn.params,typeof e=="function"?e(t):e||(0,ce._)`{}`]),l.messages&&r.push([pn.message,typeof n=="function"?n(t):n]),l.verbose&&r.push([pn.schema,i],[pn.parentSchema,(0,ce._)`${u}${m}`],[Be.default.data,o]),p&&r.push([pn.propertyName,p])}});var Gf=L(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.boolOrEmptySchema=qn.topBoolOrEmptySchema=void 0;var DS=Hr(),US=ee(),zS=Ct(),qS={message:"boolean schema is false"};function MS(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Vf(t,!1):typeof n=="object"&&n.$async===!0?e.return(zS.default.data):(e.assign((0,US._)`${r}.errors`,null),e.return(!0))}qn.topBoolOrEmptySchema=MS;function BS(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Vf(t)):n.var(e,!0)}qn.boolOrEmptySchema=BS;function Vf(t,e){let{gen:n,data:r}=t,s={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,DS.reportError)(s,qS,void 0,e)}});var Rl=L(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.getRules=Mn.isJSONType=void 0;var FS=["string","number","integer","boolean","null","object","array"],HS=new Set(FS);function KS(t){return typeof t=="string"&&HS.has(t)}Mn.isJSONType=KS;function VS(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Mn.getRules=VS});var Tl=L(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.shouldUseRule=Wt.shouldUseGroup=Wt.schemaHasRulesForType=void 0;function GS({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&Wf(t,r)}Wt.schemaHasRulesForType=GS;function Wf(t,e){return e.rules.some(n=>Jf(t,n))}Wt.shouldUseGroup=Wf;function Jf(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Wt.shouldUseRule=Jf});var Kr=L(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var WS=Rl(),JS=Tl(),ZS=Hr(),Y=ee(),Zf=le(),Bn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Bn||(Le.DataType=Bn={}));function YS(t){let e=Yf(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Le.getSchemaTypes=YS;function Yf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(WS.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=Yf;function QS(t,e){let{gen:n,data:r,opts:s}=t,o=XS(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,JS.schemaHasRulesForType)(t,e[0]));if(i){let a=Pl(e,r,s.strictNumbers,Bn.Wrong);n.if(a,()=>{o.length?e_(t,e,o):Al(t)})}return i}Le.coerceAndCheckDataType=QS;var Qf=new Set(["string","number","integer","boolean","null"]);function XS(t,e){return e?t.filter(n=>Qf.has(n)||e==="array"&&n==="array"):[]}function e_(t,e,n){let{gen:r,data:s,opts:o}=t,i=r.let("dataType",(0,Y._)`typeof ${s}`),a=r.let("coerced",(0,Y._)`undefined`);o.coerceTypes==="array"&&r.if((0,Y._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,Y._)`${s}[0]`).assign(i,(0,Y._)`typeof ${s}`).if(Pl(e,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,Y._)`${a} !== undefined`);for(let p of n)(Qf.has(p)||p==="array"&&o.coerceTypes==="array")&&l(p);r.else(),Al(t),r.endIf(),r.if((0,Y._)`${a} !== undefined`,()=>{r.assign(s,a),t_(t,a)});function l(p){switch(p){case"string":r.elseIf((0,Y._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Y._)`"" + ${s}`).elseIf((0,Y._)`${s} === null`).assign(a,(0,Y._)`""`);return;case"number":r.elseIf((0,Y._)`${i} == "boolean" || ${s} === null
|
|
1087
1232
|
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,Y._)`+${s}`);return;case"integer":r.elseIf((0,Y._)`${i} === "boolean" || ${s} === null
|
|
1088
1233
|
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,Y._)`+${s}`);return;case"boolean":r.elseIf((0,Y._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,Y._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":r.elseIf((0,Y._)`${s} === "" || ${s} === 0 || ${s} === false`),r.assign(a,null);return;case"array":r.elseIf((0,Y._)`${i} === "string" || ${i} === "number"
|
|
1089
|
-
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,Y._)`[${s}]`)}}}function RS({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${n}]`,r))}function vl(t,e,n,r=Mn.Correct){let s=r===Mn.Correct?Y.operators.EQ:Y.operators.NEQ,o;switch(t){case"null":return(0,Y._)`${e} ${s} null`;case"array":o=(0,Y._)`Array.isArray(${e})`;break;case"object":o=(0,Y._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,Y._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,Y._)`typeof ${e} ${s} ${t}`}return r===Mn.Correct?o:(0,Y.not)(o);function i(a=Y.nil){return(0,Y.and)((0,Y._)`typeof ${e} == "number"`,a,n?(0,Y._)`isFinite(${e})`:Y.nil)}}je.checkDataType=vl;function kl(t,e,n,r){if(t.length===1)return vl(t[0],e,n,r);let s,o=(0,Cf.toHash)(t);if(o.array&&o.object){let i=(0,Y._)`typeof ${e} != "object"`;s=o.null?i:(0,Y._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=Y.nil;o.number&&delete o.integer;for(let i in o)s=(0,Y.and)(s,vl(i,e,n,r));return s}je.checkDataTypes=kl;var ES={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function Sl(t){let e=PS(t);(0,SS.reportError)(e,ES)}je.reportTypeError=Sl;function PS(t){let{gen:e,data:n,schema:r}=t,s=(0,Cf.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:t}}});var Lf=L(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.assignDefaults=void 0;var Bn=X(),AS=le();function IS(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let s in n)jf(t,s,n[s].default);else e==="array"&&Array.isArray(r)&&r.forEach((s,o)=>jf(t,o,s.default))}So.assignDefaults=IS;function jf(t,e,n){let{gen:r,compositeRule:s,data:o,opts:i}=t;if(n===void 0)return;let a=(0,Bn._)`${o}${(0,Bn.getProperty)(e)}`;if(s){(0,AS.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Bn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Bn._)`${l} || ${a} === null || ${a} === ""`),r.if(l,(0,Bn._)`${a} = ${(0,Bn.stringify)(n)}`)}});var at=L(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.validateUnion=me.validateArray=me.usePattern=me.callValidateCode=me.schemaProperties=me.allSchemaProperties=me.noPropertyInData=me.propertyInData=me.isOwnProperty=me.hasPropFunc=me.reportMissingProp=me.checkMissingProp=me.checkReportMissingProp=void 0;var be=X(),_l=le(),Gt=At(),CS=le();function OS(t,e){let{gen:n,data:r,it:s}=t;n.if(xl(n,r,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,be._)`${e}`},!0),t.error()})}me.checkReportMissingProp=OS;function NS({gen:t,data:e,it:{opts:n}},r,s){return(0,be.or)(...r.map(o=>(0,be.and)(xl(t,e,o,n.ownProperties),(0,be._)`${s} = ${o}`)))}me.checkMissingProp=NS;function jS(t,e){t.setParams({missingProperty:e},!0),t.error()}me.reportMissingProp=jS;function zf(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,be._)`Object.prototype.hasOwnProperty`})}me.hasPropFunc=zf;function $l(t,e,n){return(0,be._)`${zf(t)}.call(${e}, ${n})`}me.isOwnProperty=$l;function LS(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} !== undefined`;return r?(0,be._)`${s} && ${$l(t,e,n)}`:s}me.propertyInData=LS;function xl(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} === undefined`;return r?(0,be.or)(s,(0,be.not)($l(t,e,n))):s}me.noPropertyInData=xl;function Df(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}me.allSchemaProperties=Df;function zS(t,e){return Df(e).filter(n=>!(0,_l.alwaysValidSchema)(t,e[n]))}me.schemaProperties=zS;function DS({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:s,errorPath:o},it:i},a,l,d){let p=d?(0,be._)`${t}, ${e}, ${r}${s}`:e,h=[[Gt.default.instancePath,(0,be.strConcat)(Gt.default.instancePath,o)],[Gt.default.parentData,i.parentData],[Gt.default.parentDataProperty,i.parentDataProperty],[Gt.default.rootData,Gt.default.rootData]];i.opts.dynamicRef&&h.push([Gt.default.dynamicAnchors,Gt.default.dynamicAnchors]);let _=(0,be._)`${p}, ${n.object(...h)}`;return l!==be.nil?(0,be._)`${a}.call(${l}, ${_})`:(0,be._)`${a}(${_})`}me.callValidateCode=DS;var US=(0,be._)`new RegExp`;function qS({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(n,r);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,be._)`${s.code==="new RegExp"?US:(0,CS.useFunc)(t,s)}(${n}, ${r})`})}me.usePattern=qS;function MS(t){let{gen:e,data:n,keyword:r,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let l=e.const("len",(0,be._)`${n}.length`);e.forRange("i",0,l,d=>{t.subschema({keyword:r,dataProp:d,dataPropType:_l.Type.Num},o),e.if((0,be.not)(o),a)})}}me.validateArray=MS;function BS(t){let{gen:e,schema:n,keyword:r,it:s}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(l=>(0,_l.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((l,d)=>{let p=t.subschema({keyword:r,schemaProp:d,compositeRule:!0},a);e.assign(i,(0,be._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,be.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}me.validateUnion=BS});var Mf=L(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.validateKeywordUsage=vt.validSchemaType=vt.funcKeywordCode=vt.macroKeywordCode=void 0;var Me=X(),dn=At(),FS=at(),KS=Fr();function HS(t,e){let{gen:n,keyword:r,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=qf(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let d=n.name("valid");t.subschema({schema:a,schemaPath:Me.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))}vt.macroKeywordCode=HS;function VS(t,e){var n;let{gen:r,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;WS(l,e);let d=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,p=qf(r,s,d),h=r.let("valid");t.block$data(h,_),t.ok((n=e.valid)!==null&&n!==void 0?n:h);function _(){if(e.errors===!1)T(),e.modifying&&Uf(t),R(()=>t.error());else{let P=e.async?y():w();e.modifying&&Uf(t),R(()=>GS(t,P))}}function y(){let P=r.let("ruleErrs",null);return r.try(()=>T((0,Me._)`await `),I=>r.assign(h,!1).if((0,Me._)`${I} instanceof ${l.ValidationError}`,()=>r.assign(P,(0,Me._)`${I}.errors`),()=>r.throw(I))),P}function w(){let P=(0,Me._)`${p}.errors`;return r.assign(P,null),T(Me.nil),P}function T(P=e.async?(0,Me._)`await `:Me.nil){let I=l.opts.passContext?dn.default.this:dn.default.self,D=!("compile"in e&&!a||e.schema===!1);r.assign(h,(0,Me._)`${P}${(0,FS.callValidateCode)(t,p,I,D)}`,e.modifying)}function R(P){var I;r.if((0,Me.not)((I=e.valid)!==null&&I!==void 0?I:h),P)}}vt.funcKeywordCode=VS;function Uf(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Me._)`${r.parentData}[${r.parentDataProperty}]`))}function GS(t,e){let{gen:n}=t;n.if((0,Me._)`Array.isArray(${e})`,()=>{n.assign(dn.default.vErrors,(0,Me._)`${dn.default.vErrors} === null ? ${e} : ${dn.default.vErrors}.concat(${e})`).assign(dn.default.errors,(0,Me._)`${dn.default.vErrors}.length`),(0,KS.extendErrors)(t)},()=>t.error())}function WS({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function qf(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Me.stringify)(n)})}function JS(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}vt.validSchemaType=JS;function ZS({schema:t,opts:e,self:n,errSchemaPath:r},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${r}": `+n.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(l);else throw new Error(l)}}vt.validateKeywordUsage=ZS});var Ff=L(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.extendSubschemaMode=Wt.extendSubschemaData=Wt.getSubschema=void 0;var kt=X(),Bf=le();function YS(t,{keyword:e,schemaProp:n,schema:r,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,kt._)`${t.schemaPath}${(0,kt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,kt._)`${t.schemaPath}${(0,kt.getProperty)(e)}${(0,kt.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Bf.escapeFragment)(n)}`}}if(r!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Wt.getSubschema=YS;function QS(t,e,{dataProp:n,dataPropType:r,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:d,dataPathArr:p,opts:h}=e,_=a.let("data",(0,kt._)`${e.data}${(0,kt.getProperty)(n)}`,!0);l(_),t.errorPath=(0,kt.str)`${d}${(0,Bf.getErrorPath)(n,r,h.jsPropertySyntax)}`,t.parentDataProperty=(0,kt._)`${n}`,t.dataPathArr=[...p,t.parentDataProperty]}if(s!==void 0){let d=s instanceof kt.Name?s:a.let("data",s,!0);l(d),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(d){t.data=d,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,d]}}Wt.extendSubschemaData=QS;function XS(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:s,allErrors:o}){r!==void 0&&(t.compositeRule=r),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=n}Wt.extendSubschemaMode=XS});var Tl=L((kO,Kf)=>{"use strict";Kf.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,s,o;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(s=r;s--!==0;)if(!t(e[s],n[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(o=Object.keys(e),r=o.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[s]))return!1;for(s=r;s--!==0;){var i=o[s];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var Vf=L((SO,Hf)=>{"use strict";var Jt=Hf.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},s=n.post||function(){};_o(e,r,s,t,"",t)};Jt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Jt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Jt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Jt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function _o(t,e,n,r,s,o,i,a,l,d){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,s,o,i,a,l,d);for(var p in r){var h=r[p];if(Array.isArray(h)){if(p in Jt.arrayKeywords)for(var _=0;_<h.length;_++)_o(t,e,n,h[_],s+"/"+p+"/"+_,o,s,p,r,_)}else if(p in Jt.propsKeywords){if(h&&typeof h=="object")for(var y in h)_o(t,e,n,h[y],s+"/"+p+"/"+e_(y),o,s,p,r,y)}else(p in Jt.keywords||t.allKeys&&!(p in Jt.skipKeywords))&&_o(t,e,n,h,s+"/"+p,o,s,p,r)}n(r,s,o,i,a,l,d)}}function e_(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Hr=L(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.getSchemaRefs=Ve.resolveUrl=Ve.normalizeId=Ve._getFullPath=Ve.getFullPath=Ve.inlineRef=void 0;var t_=le(),n_=Tl(),r_=Vf(),s_=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o_(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Rl(t):e?Gf(t)<=e:!1}Ve.inlineRef=o_;var i_=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Rl(t){for(let e in t){if(i_.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Rl)||typeof n=="object"&&Rl(n))return!0}return!1}function Gf(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!s_.has(n)&&(typeof t[n]=="object"&&(0,t_.eachItem)(t[n],r=>e+=Gf(r)),e===1/0))return 1/0}return e}function Wf(t,e="",n){n!==!1&&(e=Fn(e));let r=t.parse(e);return Jf(t,r)}Ve.getFullPath=Wf;function Jf(t,e){return t.serialize(e).split("#")[0]+"#"}Ve._getFullPath=Jf;var a_=/#\/?$/;function Fn(t){return t?t.replace(a_,""):""}Ve.normalizeId=Fn;function l_(t,e,n){return n=Fn(n),t.resolve(e,n)}Ve.resolveUrl=l_;var c_=/^[a-z_][-a-z0-9._]*$/i;function u_(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,s=Fn(t[n]||e),o={"":s},i=Wf(r,s,!1),a={},l=new Set;return r_(t,{allKeys:!0},(h,_,y,w)=>{if(w===void 0)return;let T=i+_,R=o[w];typeof h[n]=="string"&&(R=P.call(this,h[n])),I.call(this,h.$anchor),I.call(this,h.$dynamicAnchor),o[_]=R;function P(D){let se=this.opts.uriResolver.resolve;if(D=Fn(R?se(R,D):D),l.has(D))throw p(D);l.add(D);let H=this.refs[D];return typeof H=="string"&&(H=this.refs[H]),typeof H=="object"?d(h,H.schema,D):D!==Fn(T)&&(D[0]==="#"?(d(h,a[D],D),a[D]=h):this.refs[D]=T),D}function I(D){if(typeof D=="string"){if(!c_.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function d(h,_,y){if(_!==void 0&&!n_(h,_))throw p(y)}function p(h){return new Error(`reference "${h}" resolves to more than one schema`)}}Ve.getSchemaRefs=u_});var Wr=L(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.getData=Zt.KeywordCxt=Zt.validateFunctionCode=void 0;var eh=Pf(),Zf=Kr(),Pl=wl(),$o=Kr(),d_=Lf(),Gr=Mf(),El=Ff(),q=X(),J=At(),p_=Hr(),It=le(),Vr=Fr();function f_(t){if(rh(t)&&(sh(t),nh(t))){g_(t);return}th(t,()=>(0,eh.topBoolOrEmptySchema)(t))}Zt.validateFunctionCode=f_;function th({gen:t,validateName:e,schema:n,schemaEnv:r,opts:s},o){s.code.es5?t.func(e,(0,q._)`${J.default.data}, ${J.default.valCxt}`,r.$async,()=>{t.code((0,q._)`"use strict"; ${Yf(n,s)}`),m_(t,s),t.code(o)}):t.func(e,(0,q._)`${J.default.data}, ${h_(s)}`,r.$async,()=>t.code(Yf(n,s)).code(o))}function h_(t){return(0,q._)`{${J.default.instancePath}="", ${J.default.parentData}, ${J.default.parentDataProperty}, ${J.default.rootData}=${J.default.data}${t.dynamicRef?(0,q._)`, ${J.default.dynamicAnchors}={}`:q.nil}}={}`}function m_(t,e){t.if(J.default.valCxt,()=>{t.var(J.default.instancePath,(0,q._)`${J.default.valCxt}.${J.default.instancePath}`),t.var(J.default.parentData,(0,q._)`${J.default.valCxt}.${J.default.parentData}`),t.var(J.default.parentDataProperty,(0,q._)`${J.default.valCxt}.${J.default.parentDataProperty}`),t.var(J.default.rootData,(0,q._)`${J.default.valCxt}.${J.default.rootData}`),e.dynamicRef&&t.var(J.default.dynamicAnchors,(0,q._)`${J.default.valCxt}.${J.default.dynamicAnchors}`)},()=>{t.var(J.default.instancePath,(0,q._)`""`),t.var(J.default.parentData,(0,q._)`undefined`),t.var(J.default.parentDataProperty,(0,q._)`undefined`),t.var(J.default.rootData,J.default.data),e.dynamicRef&&t.var(J.default.dynamicAnchors,(0,q._)`{}`)})}function g_(t){let{schema:e,opts:n,gen:r}=t;th(t,()=>{n.$comment&&e.$comment&&ih(t),k_(t),r.let(J.default.vErrors,null),r.let(J.default.errors,0),n.unevaluated&&b_(t),oh(t),$_(t)})}function b_(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,q._)`${n}.evaluated`),e.if((0,q._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,q._)`${t.evaluated}.props`,(0,q._)`undefined`)),e.if((0,q._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,q._)`${t.evaluated}.items`,(0,q._)`undefined`))}function Yf(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,q._)`/*# sourceURL=${n} */`:q.nil}function y_(t,e){if(rh(t)&&(sh(t),nh(t))){w_(t,e);return}(0,eh.boolOrEmptySchema)(t,e)}function nh({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function rh(t){return typeof t.schema!="boolean"}function w_(t,e){let{schema:n,gen:r,opts:s}=t;s.$comment&&n.$comment&&ih(t),S_(t),__(t);let o=r.const("_errs",J.default.errors);oh(t,o),r.var(e,(0,q._)`${o} === ${J.default.errors}`)}function sh(t){(0,It.checkUnknownRules)(t),v_(t)}function oh(t,e){if(t.opts.jtd)return Qf(t,[],!1,e);let n=(0,Zf.getSchemaTypes)(t.schema),r=(0,Zf.coerceAndCheckDataType)(t,n);Qf(t,n,!r,e)}function v_(t){let{schema:e,errSchemaPath:n,opts:r,self:s}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,It.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function k_(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,It.checkStrictMode)(t,"default is ignored in the schema root")}function S_(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,p_.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function __(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function ih({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:s}){let o=n.$comment;if(s.$comment===!0)t.code((0,q._)`${J.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,q.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,q._)`${J.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function $_(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=t;n.$async?e.if((0,q._)`${J.default.errors} === 0`,()=>e.return(J.default.data),()=>e.throw((0,q._)`new ${s}(${J.default.vErrors})`)):(e.assign((0,q._)`${r}.errors`,J.default.vErrors),o.unevaluated&&x_(t),e.return((0,q._)`${J.default.errors} === 0`))}function x_({gen:t,evaluated:e,props:n,items:r}){n instanceof q.Name&&t.assign((0,q._)`${e}.props`,n),r instanceof q.Name&&t.assign((0,q._)`${e}.items`,r)}function Qf(t,e,n,r){let{gen:s,schema:o,data:i,allErrors:a,opts:l,self:d}=t,{RULES:p}=d;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,It.schemaHasRulesButRef)(o,p))){s.block(()=>lh(t,"$ref",p.all.$ref.definition));return}l.jtd||T_(t,e),s.block(()=>{for(let _ of p.rules)h(_);h(p.post)});function h(_){(0,Pl.shouldUseGroup)(o,_)&&(_.type?(s.if((0,$o.checkDataType)(_.type,i,l.strictNumbers)),Xf(t,_),e.length===1&&e[0]===_.type&&n&&(s.else(),(0,$o.reportTypeError)(t)),s.endIf()):Xf(t,_),a||s.if((0,q._)`${J.default.errors} === ${r||0}`))}}function Xf(t,e){let{gen:n,schema:r,opts:{useDefaults:s}}=t;s&&(0,d_.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,Pl.shouldUseRule)(r,o)&&lh(t,o.keyword,o.definition,e.type)})}function T_(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(R_(t,e),t.opts.allowUnionTypes||E_(t,e),P_(t,t.dataTypes))}function R_(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{ah(t.dataTypes,n)||Al(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),I_(t,e)}}function E_(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Al(t,"use allowUnionTypes to allow union type keyword")}function P_(t,e){let n=t.self.RULES.all;for(let r in n){let s=n[r];if(typeof s=="object"&&(0,Pl.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>A_(e,i))&&Al(t,`missing type "${o.join(",")}" for keyword "${r}"`)}}}function A_(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function ah(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function I_(t,e){let n=[];for(let r of t.dataTypes)ah(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Al(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,It.checkStrictMode)(t,e,t.opts.strictTypes)}var xo=class{constructor(e,n,r){if((0,Gr.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,It.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",ch(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Gr.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",J.default.errors))}result(e,n,r){this.failResult((0,q.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,q.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,q._)`${n} !== undefined && (${(0,q.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?Vr.reportExtraError:Vr.reportError)(this,this.def.error,n)}$dataError(){(0,Vr.reportError)(this,this.def.$dataError||Vr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Vr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=q.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=q.nil,n=q.nil){if(!this.$data)return;let{gen:r,schemaCode:s,schemaType:o,def:i}=this;r.if((0,q.or)((0,q._)`${s} === undefined`,n)),e!==q.nil&&r.assign(e,!0),(o.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==q.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:s,it:o}=this;return(0,q.or)(i(),a());function i(){if(r.length){if(!(n instanceof q.Name))throw new Error("ajv implementation error");let l=Array.isArray(r)?r:[r];return(0,q._)`${(0,$o.checkDataTypes)(l,n,o.opts.strictNumbers,$o.DataType.Wrong)}`}return q.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,q._)`!${l}(${n})`}return q.nil}}subschema(e,n){let r=(0,El.getSubschema)(this.it,e);(0,El.extendSubschemaData)(r,this.it,e),(0,El.extendSubschemaMode)(r,e);let s={...this.it,...r,items:void 0,props:void 0};return y_(s,n),s}mergeEvaluated(e,n){let{it:r,gen:s}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=It.mergeEvaluated.props(s,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=It.mergeEvaluated.items(s,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:s}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return s.if(n,()=>this.mergeEvaluated(e,q.Name)),!0}};Zt.KeywordCxt=xo;function lh(t,e,n,r){let s=new xo(t,n,e);"code"in n?n.code(s,r):s.$data&&n.validate?(0,Gr.funcKeywordCode)(s,n):"macro"in n?(0,Gr.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,Gr.funcKeywordCode)(s,n)}var C_=/^\/(?:[^~]|~0|~1)*$/,O_=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ch(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let s,o;if(t==="")return J.default.rootData;if(t[0]==="/"){if(!C_.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=J.default.rootData}else{let d=O_.exec(t);if(!d)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+d[1];if(s=d[2],s==="#"){if(p>=e)throw new Error(l("property/index",p));return r[e-p]}if(p>e)throw new Error(l("data",p));if(o=n[e-p],!s)return o}let i=o,a=s.split("/");for(let d of a)d&&(o=(0,q._)`${o}${(0,q.getProperty)((0,It.unescapeJsonPointer)(d))}`,i=(0,q._)`${i} && ${o}`);return i;function l(d,p){return`Cannot access ${d} ${p} levels up, current level is ${e}`}}Zt.getData=ch});var To=L(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});var Il=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Cl.default=Il});var Jr=L(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var Ol=Hr(),Nl=class extends Error{constructor(e,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Ol.resolveUrl)(e,n,r),this.missingSchema=(0,Ol.normalizeId)((0,Ol.getFullPath)(e,this.missingRef))}};jl.default=Nl});var Eo=L(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var ht=X(),N_=To(),pn=At(),mt=Hr(),uh=le(),j_=Wr(),Kn=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,mt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};lt.SchemaEnv=Kn;function zl(t){let e=dh.call(this,t);if(e)return e;let n=(0,mt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ht.CodeGen(this.scope,{es5:r,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:N_.default,code:(0,ht._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let d={gen:i,allErrors:this.opts.allErrors,data:pn.default.data,parentData:pn.default.parentData,parentDataProperty:pn.default.parentDataProperty,dataNames:[pn.default.data],dataPathArr:[ht.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ht.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:ht.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ht._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,j_.validateFunctionCode)(d),i.optimize(this.opts.code.optimize);let h=i.toString();p=`${i.scopeRefs(pn.default.scope)}return ${h}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let y=new Function(`${pn.default.self}`,`${pn.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:y}),y.errors=null,y.schema=t.schema,y.schemaEnv=t,t.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:l,validateCode:h,scopeValues:i._values}),this.opts.unevaluated){let{props:w,items:T}=d;y.evaluated={props:w instanceof ht.Name?void 0:w,items:T instanceof ht.Name?void 0:T,dynamicProps:w instanceof ht.Name,dynamicItems:T instanceof ht.Name},y.source&&(y.source.evaluated=(0,ht.stringify)(y.evaluated))}return t.validate=y,t}catch(h){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),h}finally{this._compilations.delete(t)}}lt.compileSchema=zl;function L_(t,e,n){var r;n=(0,mt.resolveUrl)(this.opts.uriResolver,e,n);let s=t.refs[n];if(s)return s;let o=U_.call(this,t,n);if(o===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(o=new Kn({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=z_.call(this,o)}lt.resolveRef=L_;function z_(t){return(0,mt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:zl.call(this,t)}function dh(t){for(let e of this._compilations)if(D_(e,t))return e}lt.getCompilingSchema=dh;function D_(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function U_(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Ro.call(this,t,e)}function Ro(t,e){let n=this.opts.uriResolver.parse(e),r=(0,mt._getFullPath)(this.opts.uriResolver,n),s=(0,mt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===s)return Ll.call(this,n,t);let o=(0,mt.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Ro.call(this,t,i);return typeof a?.schema!="object"?void 0:Ll.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||zl.call(this,i),o===(0,mt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,d=a[l];return d&&(s=(0,mt.resolveUrl)(this.opts.uriResolver,s,d)),new Kn({schema:a,schemaId:l,root:t,baseId:s})}return Ll.call(this,n,i)}}lt.resolveSchema=Ro;var q_=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ll(t,{baseId:e,schema:n,root:r}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let l=n[(0,uh.unescapeFragment)(a)];if(l===void 0)return;n=l;let d=typeof n=="object"&&n[this.opts.schemaId];!q_.has(a)&&d&&(e=(0,mt.resolveUrl)(this.opts.uriResolver,e,d))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,uh.schemaHasRulesButRef)(n,this.RULES)){let a=(0,mt.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=Ro.call(this,r,a)}let{schemaId:i}=this.opts;if(o=o||new Kn({schema:n,schemaId:i,root:r,baseId:e}),o.schema!==o.root.schema)return o}});var ph=L((EO,M_)=>{M_.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var ql=L((PO,yh)=>{"use strict";var B_=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),hh=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Dl=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),mh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),F_=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ul(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var K_=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function fh(t){return t.length=0,!0}function H_(t,e,n){if(t.length){let r=Ul(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function V_(t){let e=0,n={error:!1,address:"",zone:""},r=[],s=[],o=!1,i=!1,a=H_;for(let l=0;l<t.length;l++){let d=t[l];if(!(d==="["||d==="]"))if(d===":"){if(o===!0&&(i=!0),!a(s,r,n))break;if(++e>7){n.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),r.push(":");continue}else if(d==="%"){if(!a(s,r,n))break;a=fh}else{s.push(d);continue}}return s.length&&(a===fh?n.zone=s.join(""):i?r.push(s.join("")):r.push(Ul(s))),n.address=r.join(""),n}function gh(t){if(G_(t,":")<2)return{host:t,isIPV6:!1};let e=V_(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function G_(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function W_(t){let e=t,n=[],r=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(s===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}var J_={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Z_=/[@/?#:]/g,Y_=/[@/?#]/g;function bh(t,e){let n=e?Y_:Z_;return n.lastIndex=0,t.replace(n,r=>J_[r])}function Q_(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(Dl(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&mh(i)?n+=i:n+="%"+o,r+=2;continue}}n+=t[r]}return n}function X_(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(Dl(r)){let s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&mh(o)?e+=o:e+="%"+s,n+=2;continue}}F_(t[n])?e+=t[n]:e+=escape(t[n])}return e}function e$(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(Dl(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function t$(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!hh(n)){let r=gh(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=bh(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}yh.exports={nonSimpleDomain:K_,recomposeAuthority:t$,reescapeHostDelimiters:bh,normalizePercentEncoding:Q_,normalizePathEncoding:X_,escapePreservingEscapes:e$,removeDotSegments:W_,isIPv4:hh,isUUID:B_,normalizeIPv6:gh,stringArrayToHexStripped:Ul}});var _h=L((AO,Sh)=>{"use strict";var{isUUID:n$}=ql(),r$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,s$=["http","https","ws","wss","urn","urn:uuid"];function o$(t){return s$.indexOf(t)!==-1}function Ml(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function wh(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function vh(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function i$(t){return t.secure=Ml(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function a$(t){if((t.port===(Ml(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function l$(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(r$);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let s=`${r}:${e.nid||t.nid}`,o=Bl(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function c$(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),s=`${n}:${e.nid||r}`,o=Bl(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function u$(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!n$(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function d$(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var kh={scheme:"http",domainHost:!0,parse:wh,serialize:vh},p$={scheme:"https",domainHost:kh.domainHost,parse:wh,serialize:vh},Po={scheme:"ws",domainHost:!0,parse:i$,serialize:a$},f$={scheme:"wss",domainHost:Po.domainHost,parse:Po.parse,serialize:Po.serialize},h$={scheme:"urn",parse:l$,serialize:c$,skipNormalize:!0},m$={scheme:"urn:uuid",parse:u$,serialize:d$,skipNormalize:!0},Ao={http:kh,https:p$,ws:Po,wss:f$,urn:h$,"urn:uuid":m$};Object.setPrototypeOf(Ao,null);function Bl(t){return t&&(Ao[t]||Ao[t.toLowerCase()])||void 0}Sh.exports={wsIsSecure:Ml,SCHEMES:Ao,isValidSchemeName:o$,getSchemeHandler:Bl}});var Eh=L((IO,Oo)=>{"use strict";var{normalizeIPv6:g$,removeDotSegments:Zr,recomposeAuthority:b$,normalizePercentEncoding:y$,normalizePathEncoding:w$,escapePreservingEscapes:v$,reescapeHostDelimiters:k$,isIPv4:S$,nonSimpleDomain:_$}=ql(),{SCHEMES:$$,getSchemeHandler:xh}=_h();function x$(t,e){return typeof t=="string"?t=C$(t,e):typeof t=="object"&&(t=Co(fn(t,e),e)),t}function T$(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=Io(t,r),{parsed:i,malformedAuthorityOrPort:a}=Io(e,r);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=Th(s,i,r,!0);return r.skipEscape=!0,fn(l,r)}function Th(t,e,n,r){let s={};return r||(t=Co(fn(t,n),n),e=Co(fn(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Zr(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Zr(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Zr(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Zr(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function R$(t,e,n){let r=$h(t,n),s=$h(e,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function fn(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),s=[],o=xh(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=y$(n.path):(n.path=v$(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");let i=b$(n);if(i!==void 0&&(r.reference!=="suffix"&&s.push("//"),s.push(i),n.path&&n.path[0]!=="/"&&s.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!o||!o.absolutePath)&&(a=Zr(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return n.query!==void 0&&s.push("?",n.query),n.fragment!==void 0&&s.push("#",n.fragment),s.join("")}var E$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,P$=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,A$=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function I$(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Io(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match(P$);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(A$);if(a!==null){let d=a[1],p=d.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",s=!0):d.length!==p.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",s=!0))}let l=t.match(E$);if(l){r.scheme=l[1],r.userinfo=l[3],r.host=l[4],r.port=parseInt(l[5],10),r.path=l[6]||"",r.query=l[7],r.fragment=l[8],isNaN(r.port)&&(r.port=l[5]);let d=I$(r,l);if(d!==void 0&&(r.error=r.error||d,s=!0),r.host)if(S$(r.host)===!1){let _=g$(r.host);r.host=_.host.toLowerCase(),o=_.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let p=xh(n.scheme||r.scheme);if(!n.unicodeSupport&&(!p||!p.unicodeSupport)&&r.host&&(n.domainHost||p&&p.domainHost)&&o===!1&&_$(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(h){r.error=r.error||"Host's domain name can not be converted to ASCII: "+h}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=k$(unescape(r.host),o))),r.path&&(r.path=w$(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}p&&p.parse&&p.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:s}}function Co(t,e){return Io(t,e).parsed}function C$(t,e){return Rh(t,e).normalized}function Rh(t,e){let{parsed:n,malformedAuthorityOrPort:r}=Io(t,e);return{normalized:r?t:fn(n,e),malformedAuthorityOrPort:r}}function $h(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=Rh(t,e);return r?void 0:n}if(typeof t=="object")return fn(t,e)}var Fl={SCHEMES:$$,normalize:x$,resolve:T$,resolveComponent:Th,equal:R$,serialize:fn,parse:Co};Oo.exports=Fl;Oo.exports.default=Fl;Oo.exports.fastUri=Fl});var Ah=L(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var Ph=Eh();Ph.code='require("ajv/dist/runtime/uri").default';Kl.default=Ph});var Dh=L(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.CodeGen=Pe.Name=Pe.nil=Pe.stringify=Pe.str=Pe._=Pe.KeywordCxt=void 0;var O$=Wr();Object.defineProperty(Pe,"KeywordCxt",{enumerable:!0,get:function(){return O$.KeywordCxt}});var Hn=X();Object.defineProperty(Pe,"_",{enumerable:!0,get:function(){return Hn._}});Object.defineProperty(Pe,"str",{enumerable:!0,get:function(){return Hn.str}});Object.defineProperty(Pe,"stringify",{enumerable:!0,get:function(){return Hn.stringify}});Object.defineProperty(Pe,"nil",{enumerable:!0,get:function(){return Hn.nil}});Object.defineProperty(Pe,"Name",{enumerable:!0,get:function(){return Hn.Name}});Object.defineProperty(Pe,"CodeGen",{enumerable:!0,get:function(){return Hn.CodeGen}});var N$=To(),jh=Jr(),j$=yl(),Yr=Eo(),L$=X(),Qr=Hr(),No=Kr(),Vl=le(),Ih=ph(),z$=Ah(),Lh=(t,e)=>new RegExp(t,e);Lh.code="new RegExp";var D$=["removeAdditional","useDefaults","coerceTypes"],U$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),q$={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},M$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ch=200;function B$(t){var e,n,r,s,o,i,a,l,d,p,h,_,y,w,T,R,P,I,D,se,H,Le,Be,nr,yt;let en=t.strict,rr=(e=t.code)===null||e===void 0?void 0:e.optimize,Ct=rr===!0||rr===void 0?1:rr||0,bn=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:Lh,sr=(s=t.uriResolver)!==null&&s!==void 0?s:z$.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:en)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:en)!==null&&l!==void 0?l:!0,strictTypes:(p=(d=t.strictTypes)!==null&&d!==void 0?d:en)!==null&&p!==void 0?p:"log",strictTuples:(_=(h=t.strictTuples)!==null&&h!==void 0?h:en)!==null&&_!==void 0?_:"log",strictRequired:(w=(y=t.strictRequired)!==null&&y!==void 0?y:en)!==null&&w!==void 0?w:!1,code:t.code?{...t.code,optimize:Ct,regExp:bn}:{optimize:Ct,regExp:bn},loopRequired:(T=t.loopRequired)!==null&&T!==void 0?T:Ch,loopEnum:(R=t.loopEnum)!==null&&R!==void 0?R:Ch,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(se=t.schemaId)!==null&&se!==void 0?se:"$id",addUsedSchema:(H=t.addUsedSchema)!==null&&H!==void 0?H:!0,validateSchema:(Le=t.validateSchema)!==null&&Le!==void 0?Le:!0,validateFormats:(Be=t.validateFormats)!==null&&Be!==void 0?Be:!0,unicodeRegExp:(nr=t.unicodeRegExp)!==null&&nr!==void 0?nr:!0,int32range:(yt=t.int32range)!==null&&yt!==void 0?yt:!0,uriResolver:sr}}var Xr=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...B$(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new L$.ValueScope({scope:{},prefixes:U$,es5:n,lines:r}),this.logger=W$(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,j$.getRules)(),Oh.call(this,q$,e,"NOT SUPPORTED"),Oh.call(this,M$,e,"DEPRECATED","warn"),this._metaOpts=V$.call(this),e.formats&&K$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&H$.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),F$.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,s=Ih;r==="id"&&(s={...Ih},s.id=s.$id,delete s.$id),n&&e&&this.addMetaSchema(s,s[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let s=r(n);return"$async"in r||(this.errors=r.errors),s}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return s.call(this,e,n);async function s(p,h){await o.call(this,p.$schema);let _=this._addSchema(p,h);return _.validate||i.call(this,_)}async function o(p){p&&!this.getSchema(p)&&await s.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(h){if(!(h instanceof jh.default))throw h;return a.call(this,h),await l.call(this,h.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:h}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${h} cannot be resolved`)}async function l(p){let h=await d.call(this,p);this.refs[p]||await o.call(this,h.$schema),this.refs[p]||this.addSchema(h,p,n)}async function d(p){let h=this._loading[p];if(h)return h;try{return await(this._loading[p]=r(p))}finally{delete this._loading[p]}}}addSchema(e,n,r,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return n=(0,Qr.normalizeId)(n||o),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,s,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(r,e);if(!s&&n){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let n;for(;typeof(n=Nh.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,s=new Yr.SchemaEnv({schema:{},schemaId:r});if(n=Yr.resolveSchema.call(this,s,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=Nh.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Qr.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Z$.call(this,r,n),!n)return(0,Vl.eachItem)(r,o=>Hl.call(this,o)),this;Q$.call(this,n);let s={...n,type:(0,No.getJSONTypes)(n.type),schemaType:(0,No.getJSONTypes)(n.schemaType)};return(0,Vl.eachItem)(r,s.type.length===0?o=>Hl.call(this,o,s):o=>s.type.forEach(i=>Hl.call(this,o,s,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let s=r.rules.findIndex(o=>o.keyword===e);s>=0&&r.rules.splice(s,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${r}${s.instancePath} ${s.message}`).reduce((s,o)=>s+n+o)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of n){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in r){let l=r[a];if(typeof l!="object")continue;let{$data:d}=l.definition,p=i[a];d&&p&&(i[a]=zh(p))}}return e}_removeAllSchemas(e,n){for(let r in e){let s=e[r];(!n||n.test(r))&&(typeof s=="string"?delete e[r]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[r]))}}_addSchema(e,n,r,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;r=(0,Qr.normalizeId)(i||r);let d=Qr.getSchemaRefs.call(this,e,r);return l=new Yr.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:d}),this._cache.set(l.schema,l),o&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=l),s&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Yr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Yr.compileSchema.call(this,e)}finally{this.opts=n}}};Xr.ValidationError=N$.default;Xr.MissingRefError=jh.default;Pe.default=Xr;function Oh(t,e,n,r="error"){for(let s in t){let o=s;o in e&&this.logger[r](`${n}: option ${s}. ${t[o]}`)}}function Nh(t){return t=(0,Qr.normalizeId)(t),this.schemas[t]||this.refs[t]}function F$(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function K$(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function H$(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function V$(){let t={...this.opts};for(let e of D$)delete t[e];return t}var G$={log(){},warn(){},error(){}};function W$(t){if(t===!1)return G$;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var J$=/^[a-z_$][a-z0-9_$:-]*$/i;function Z$(t,e){let{RULES:n}=this;if((0,Vl.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!J$.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Hl(t,e,n){var r;let s=e?.post;if(n&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:l})=>l===n);if(i||(i={type:n,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,No.getJSONTypes)(e.type),schemaType:(0,No.getJSONTypes)(e.schemaType)}};e.before?Y$.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(l=>this.addKeyword(l))}function Y$(t,e,n){let r=t.rules.findIndex(s=>s.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function Q$(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=zh(e)),t.validateSchema=this.compile(e,!0))}var X$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function zh(t){return{anyOf:[t,X$]}}});var Uh=L(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var ex={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Gl.default=ex});var Fh=L(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.callRef=hn.getValidate=void 0;var tx=Jr(),qh=at(),Ge=X(),Vn=At(),Mh=Eo(),jo=le(),nx={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:l}=r,{root:d}=o;if((n==="#"||n==="#/")&&s===d.baseId)return h();let p=Mh.resolveRef.call(l,d,s,n);if(p===void 0)throw new tx.default(r.opts.uriResolver,s,n);if(p instanceof Mh.SchemaEnv)return _(p);return y(p);function h(){if(o===d)return Lo(t,i,o,o.$async);let w=e.scopeValue("root",{ref:d});return Lo(t,(0,Ge._)`${w}.validate`,d,d.$async)}function _(w){let T=Bh(t,w);Lo(t,T,w,w.$async)}function y(w){let T=e.scopeValue("schema",a.code.source===!0?{ref:w,code:(0,Ge.stringify)(w)}:{ref:w}),R=e.name("valid"),P=t.subschema({schema:w,dataTypes:[],schemaPath:Ge.nil,topSchemaRef:T,errSchemaPath:n},R);t.mergeEvaluated(P),t.ok(R)}}};function Bh(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Ge._)`${n.scopeValue("wrapper",{ref:e})}.validate`}hn.getValidate=Bh;function Lo(t,e,n,r){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,d=l.passContext?Vn.default.this:Ge.nil;r?p():h();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let w=s.let("valid");s.try(()=>{s.code((0,Ge._)`await ${(0,qh.callValidateCode)(t,e,d)}`),y(e),i||s.assign(w,!0)},T=>{s.if((0,Ge._)`!(${T} instanceof ${o.ValidationError})`,()=>s.throw(T)),_(T),i||s.assign(w,!1)}),t.ok(w)}function h(){t.result((0,qh.callValidateCode)(t,e,d),()=>y(e),()=>_(e))}function _(w){let T=(0,Ge._)`${w}.errors`;s.assign(Vn.default.vErrors,(0,Ge._)`${Vn.default.vErrors} === null ? ${T} : ${Vn.default.vErrors}.concat(${T})`),s.assign(Vn.default.errors,(0,Ge._)`${Vn.default.vErrors}.length`)}function y(w){var T;if(!o.opts.unevaluated)return;let R=(T=n?.validate)===null||T===void 0?void 0:T.evaluated;if(o.props!==!0)if(R&&!R.dynamicProps)R.props!==void 0&&(o.props=jo.mergeEvaluated.props(s,R.props,o.props));else{let P=s.var("props",(0,Ge._)`${w}.evaluated.props`);o.props=jo.mergeEvaluated.props(s,P,o.props,Ge.Name)}if(o.items!==!0)if(R&&!R.dynamicItems)R.items!==void 0&&(o.items=jo.mergeEvaluated.items(s,R.items,o.items));else{let P=s.var("items",(0,Ge._)`${w}.evaluated.items`);o.items=jo.mergeEvaluated.items(s,P,o.items,Ge.Name)}}}hn.callRef=Lo;hn.default=nx});var Kh=L(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var rx=Uh(),sx=Fh(),ox=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",rx.default,sx.default];Wl.default=ox});var Hh=L(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var zo=X(),Yt=zo.operators,Do={maximum:{okStr:"<=",ok:Yt.LTE,fail:Yt.GT},minimum:{okStr:">=",ok:Yt.GTE,fail:Yt.LT},exclusiveMaximum:{okStr:"<",ok:Yt.LT,fail:Yt.GTE},exclusiveMinimum:{okStr:">",ok:Yt.GT,fail:Yt.LTE}},ix={message:({keyword:t,schemaCode:e})=>(0,zo.str)`must be ${Do[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,zo._)`{comparison: ${Do[t].okStr}, limit: ${e}}`},ax={keyword:Object.keys(Do),type:"number",schemaType:"number",$data:!0,error:ix,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,zo._)`${n} ${Do[e].fail} ${r} || isNaN(${n})`)}};Jl.default=ax});var Vh=L(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var es=X(),lx={message:({schemaCode:t})=>(0,es.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,es._)`{multipleOf: ${t}}`},cx={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:lx,code(t){let{gen:e,data:n,schemaCode:r,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,es._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,es._)`${i} !== parseInt(${i})`;t.fail$data((0,es._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Zl.default=cx});var Wh=L(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});function Gh(t){let e=t.length,n=0,r=0,s;for(;r<e;)n++,s=t.charCodeAt(r++),s>=55296&&s<=56319&&r<e&&(s=t.charCodeAt(r),(s&64512)===56320&&r++);return n}Yl.default=Gh;Gh.code='require("ajv/dist/runtime/ucs2length").default'});var Jh=L(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var mn=X(),ux=le(),dx=Wh(),px={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,mn.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,mn._)`{limit: ${t}}`},fx={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:px,code(t){let{keyword:e,data:n,schemaCode:r,it:s}=t,o=e==="maxLength"?mn.operators.GT:mn.operators.LT,i=s.opts.unicode===!1?(0,mn._)`${n}.length`:(0,mn._)`${(0,ux.useFunc)(t.gen,dx.default)}(${n})`;t.fail$data((0,mn._)`${i} ${o} ${r}`)}};Ql.default=fx});var Zh=L(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var hx=at(),mx=le(),Gn=X(),gx={message:({schemaCode:t})=>(0,Gn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Gn._)`{pattern: ${t}}`},bx={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:gx,code(t){let{gen:e,data:n,$data:r,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:l}=i.opts.code,d=l.code==="new RegExp"?(0,Gn._)`new RegExp`:(0,mx.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,Gn._)`${d}(${o}, ${a}).test(${n})`),()=>e.assign(p,!1)),t.fail$data((0,Gn._)`!${p}`)}else{let l=(0,hx.usePattern)(t,s);t.fail$data((0,Gn._)`!${l}.test(${n})`)}}};Xl.default=bx});var Yh=L(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var ts=X(),yx={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,ts.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,ts._)`{limit: ${t}}`},wx={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:yx,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxProperties"?ts.operators.GT:ts.operators.LT;t.fail$data((0,ts._)`Object.keys(${n}).length ${s} ${r}`)}};ec.default=wx});var Qh=L(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var ns=at(),rs=X(),vx=le(),kx={message:({params:{missingProperty:t}})=>(0,rs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,rs._)`{missingProperty: ${t}}`},Sx={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kx,code(t){let{gen:e,schema:n,schemaCode:r,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&n.length===0)return;let l=n.length>=a.loopRequired;if(i.allErrors?d():p(),a.strictRequired){let y=t.parentSchema.properties,{definedProperties:w}=t.it;for(let T of n)if(y?.[T]===void 0&&!w.has(T)){let R=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${T}" is not defined at "${R}" (strictRequired)`;(0,vx.checkStrictMode)(i,P,i.opts.strictRequired)}}function d(){if(l||o)t.block$data(rs.nil,h);else for(let y of n)(0,ns.checkReportMissingProp)(t,y)}function p(){let y=e.let("missing");if(l||o){let w=e.let("valid",!0);t.block$data(w,()=>_(y,w)),t.ok(w)}else e.if((0,ns.checkMissingProp)(t,n,y)),(0,ns.reportMissingProp)(t,y),e.else()}function h(){e.forOf("prop",r,y=>{t.setParams({missingProperty:y}),e.if((0,ns.noPropertyInData)(e,s,y,a.ownProperties),()=>t.error())})}function _(y,w){t.setParams({missingProperty:y}),e.forOf(y,r,()=>{e.assign(w,(0,ns.propertyInData)(e,s,y,a.ownProperties)),e.if((0,rs.not)(w),()=>{t.error(),e.break()})},rs.nil)}}};tc.default=Sx});var Xh=L(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var ss=X(),_x={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,ss.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,ss._)`{limit: ${t}}`},$x={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:_x,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxItems"?ss.operators.GT:ss.operators.LT;t.fail$data((0,ss._)`${n}.length ${s} ${r}`)}};nc.default=$x});var Uo=L(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var em=Tl();em.code='require("ajv/dist/runtime/equal").default';rc.default=em});var tm=L(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});var sc=Kr(),Ae=X(),xx=le(),Tx=Uo(),Rx={message:({params:{i:t,j:e}})=>(0,Ae.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ae._)`{i: ${t}, j: ${e}}`},Ex={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Rx,code(t){let{gen:e,data:n,$data:r,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!r&&!s)return;let l=e.let("valid"),d=o.items?(0,sc.getSchemaTypes)(o.items):[];t.block$data(l,p,(0,Ae._)`${i} === false`),t.ok(l);function p(){let w=e.let("i",(0,Ae._)`${n}.length`),T=e.let("j");t.setParams({i:w,j:T}),e.assign(l,!0),e.if((0,Ae._)`${w} > 1`,()=>(h()?_:y)(w,T))}function h(){return d.length>0&&!d.some(w=>w==="object"||w==="array")}function _(w,T){let R=e.name("item"),P=(0,sc.checkDataTypes)(d,R,a.opts.strictNumbers,sc.DataType.Wrong),I=e.const("indices",(0,Ae._)`{}`);e.for((0,Ae._)`;${w}--;`,()=>{e.let(R,(0,Ae._)`${n}[${w}]`),e.if(P,(0,Ae._)`continue`),d.length>1&&e.if((0,Ae._)`typeof ${R} == "string"`,(0,Ae._)`${R} += "_"`),e.if((0,Ae._)`typeof ${I}[${R}] == "number"`,()=>{e.assign(T,(0,Ae._)`${I}[${R}]`),t.error(),e.assign(l,!1).break()}).code((0,Ae._)`${I}[${R}] = ${w}`)})}function y(w,T){let R=(0,xx.useFunc)(e,Tx.default),P=e.name("outer");e.label(P).for((0,Ae._)`;${w}--;`,()=>e.for((0,Ae._)`${T} = ${w}; ${T}--;`,()=>e.if((0,Ae._)`${R}(${n}[${w}], ${n}[${T}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};oc.default=Ex});var nm=L(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var ic=X(),Px=le(),Ax=Uo(),Ix={message:"must be equal to constant",params:({schemaCode:t})=>(0,ic._)`{allowedValue: ${t}}`},Cx={keyword:"const",$data:!0,error:Ix,code(t){let{gen:e,data:n,$data:r,schemaCode:s,schema:o}=t;r||o&&typeof o=="object"?t.fail$data((0,ic._)`!${(0,Px.useFunc)(e,Ax.default)}(${n}, ${s})`):t.fail((0,ic._)`${o} !== ${n}`)}};ac.default=Cx});var rm=L(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var os=X(),Ox=le(),Nx=Uo(),jx={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,os._)`{allowedValues: ${t}}`},Lx={keyword:"enum",schemaType:"array",$data:!0,error:jx,code(t){let{gen:e,data:n,$data:r,schema:s,schemaCode:o,it:i}=t;if(!r&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,l,d=()=>l??(l=(0,Ox.useFunc)(e,Nx.default)),p;if(a||r)p=e.let("valid"),t.block$data(p,h);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let y=e.const("vSchema",o);p=(0,os.or)(...s.map((w,T)=>_(y,T)))}t.pass(p);function h(){e.assign(p,!1),e.forOf("v",o,y=>e.if((0,os._)`${d()}(${n}, ${y})`,()=>e.assign(p,!0).break()))}function _(y,w){let T=s[w];return typeof T=="object"&&T!==null?(0,os._)`${d()}(${n}, ${y}[${w}])`:(0,os._)`${n} === ${T}`}}};lc.default=Lx});var sm=L(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var zx=Hh(),Dx=Vh(),Ux=Jh(),qx=Zh(),Mx=Yh(),Bx=Qh(),Fx=Xh(),Kx=tm(),Hx=nm(),Vx=rm(),Gx=[zx.default,Dx.default,Ux.default,qx.default,Mx.default,Bx.default,Fx.default,Kx.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Hx.default,Vx.default];cc.default=Gx});var dc=L(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.validateAdditionalItems=void 0;var gn=X(),uc=le(),Wx={message:({params:{len:t}})=>(0,gn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,gn._)`{limit: ${t}}`},Jx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Wx,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,uc.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}om(t,r)}};function om(t,e){let{gen:n,schema:r,data:s,keyword:o,it:i}=t;i.items=!0;let a=n.const("len",(0,gn._)`${s}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,gn._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,uc.alwaysValidSchema)(i,r)){let d=n.var("valid",(0,gn._)`${a} <= ${e.length}`);n.if((0,gn.not)(d),()=>l(d)),t.ok(d)}function l(d){n.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:uc.Type.Num},d),i.allErrors||n.if((0,gn.not)(d),()=>n.break())})}}is.validateAdditionalItems=om;is.default=Jx});var pc=L(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.validateTuple=void 0;var im=X(),qo=le(),Zx=at(),Yx={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return am(t,"additionalItems",e);n.items=!0,!(0,qo.alwaysValidSchema)(n,e)&&t.ok((0,Zx.validateArray)(t))}};function am(t,e,n=t.schema){let{gen:r,parentSchema:s,data:o,keyword:i,it:a}=t;p(s),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=qo.mergeEvaluated.items(r,n.length,a.items));let l=r.name("valid"),d=r.const("len",(0,im._)`${o}.length`);n.forEach((h,_)=>{(0,qo.alwaysValidSchema)(a,h)||(r.if((0,im._)`${d} > ${_}`,()=>t.subschema({keyword:i,schemaProp:_,dataProp:_},l)),t.ok(l))});function p(h){let{opts:_,errSchemaPath:y}=a,w=n.length,T=w===h.minItems&&(w===h.maxItems||h[e]===!1);if(_.strictTuples&&!T){let R=`"${i}" is ${w}-tuple, but minItems or maxItems/${e} are not specified or different at path "${y}"`;(0,qo.checkStrictMode)(a,R,_.strictTuples)}}}as.validateTuple=am;as.default=Yx});var lm=L(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Qx=pc(),Xx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Qx.validateTuple)(t,"items")};fc.default=Xx});var um=L(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var cm=X(),eT=le(),tT=at(),nT=dc(),rT={message:({params:{len:t}})=>(0,cm.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,cm._)`{limit: ${t}}`},sT={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:rT,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:s}=n;r.items=!0,!(0,eT.alwaysValidSchema)(r,e)&&(s?(0,nT.validateAdditionalItems)(t,s):t.ok((0,tT.validateArray)(t)))}};hc.default=sT});var dm=L(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var ct=X(),Mo=le(),oT={message:({params:{min:t,max:e}})=>e===void 0?(0,ct.str)`must contain at least ${t} valid item(s)`:(0,ct.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ct._)`{minContains: ${t}}`:(0,ct._)`{minContains: ${t}, maxContains: ${e}}`},iT={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:oT,code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t,i,a,{minContains:l,maxContains:d}=r;o.opts.next?(i=l===void 0?1:l,a=d):i=1;let p=e.const("len",(0,ct._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Mo.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Mo.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Mo.alwaysValidSchema)(o,n)){let T=(0,ct._)`${p} >= ${i}`;a!==void 0&&(T=(0,ct._)`${T} && ${p} <= ${a}`),t.pass(T);return}o.items=!0;let h=e.name("valid");a===void 0&&i===1?y(h,()=>e.if(h,()=>e.break())):i===0?(e.let(h,!0),a!==void 0&&e.if((0,ct._)`${s}.length > 0`,_)):(e.let(h,!1),_()),t.result(h,()=>t.reset());function _(){let T=e.name("_valid"),R=e.let("count",0);y(T,()=>e.if(T,()=>w(R)))}function y(T,R){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:Mo.Type.Num,compositeRule:!0},T),R()})}function w(T){e.code((0,ct._)`${T}++`),a===void 0?e.if((0,ct._)`${T} >= ${i}`,()=>e.assign(h,!0).break()):(e.if((0,ct._)`${T} > ${a}`,()=>e.assign(h,!1).break()),i===1?e.assign(h,!0):e.if((0,ct._)`${T} >= ${i}`,()=>e.assign(h,!0)))}}};mc.default=iT});var hm=L(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.validateSchemaDeps=St.validatePropertyDeps=St.error=void 0;var gc=X(),aT=le(),ls=at();St.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,gc.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,gc._)`{property: ${t},
|
|
1234
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,Y._)`[${s}]`)}}}function t_({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${n}]`,r))}function El(t,e,n,r=Bn.Correct){let s=r===Bn.Correct?Y.operators.EQ:Y.operators.NEQ,o;switch(t){case"null":return(0,Y._)`${e} ${s} null`;case"array":o=(0,Y._)`Array.isArray(${e})`;break;case"object":o=(0,Y._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,Y._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,Y._)`typeof ${e} ${s} ${t}`}return r===Bn.Correct?o:(0,Y.not)(o);function i(a=Y.nil){return(0,Y.and)((0,Y._)`typeof ${e} == "number"`,a,n?(0,Y._)`isFinite(${e})`:Y.nil)}}Le.checkDataType=El;function Pl(t,e,n,r){if(t.length===1)return El(t[0],e,n,r);let s,o=(0,Zf.toHash)(t);if(o.array&&o.object){let i=(0,Y._)`typeof ${e} != "object"`;s=o.null?i:(0,Y._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=Y.nil;o.number&&delete o.integer;for(let i in o)s=(0,Y.and)(s,El(i,e,n,r));return s}Le.checkDataTypes=Pl;var n_={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function Al(t){let e=r_(t);(0,ZS.reportError)(e,n_)}Le.reportTypeError=Al;function r_(t){let{gen:e,data:n,schema:r}=t,s=(0,Zf.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:t}}});var eh=L(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.assignDefaults=void 0;var Fn=ee(),s_=le();function o_(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let s in n)Xf(t,s,n[s].default);else e==="array"&&Array.isArray(r)&&r.forEach((s,o)=>Xf(t,o,s.default))}To.assignDefaults=o_;function Xf(t,e,n){let{gen:r,compositeRule:s,data:o,opts:i}=t;if(n===void 0)return;let a=(0,Fn._)`${o}${(0,Fn.getProperty)(e)}`;if(s){(0,s_.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Fn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Fn._)`${l} || ${a} === null || ${a} === ""`),r.if(l,(0,Fn._)`${a} = ${(0,Fn.stringify)(n)}`)}});var lt=L(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.validateUnion=me.validateArray=me.usePattern=me.callValidateCode=me.schemaProperties=me.allSchemaProperties=me.noPropertyInData=me.propertyInData=me.isOwnProperty=me.hasPropFunc=me.reportMissingProp=me.checkMissingProp=me.checkReportMissingProp=void 0;var ye=ee(),Il=le(),Jt=Ct(),i_=le();function a_(t,e){let{gen:n,data:r,it:s}=t;n.if(Ol(n,r,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ye._)`${e}`},!0),t.error()})}me.checkReportMissingProp=a_;function l_({gen:t,data:e,it:{opts:n}},r,s){return(0,ye.or)(...r.map(o=>(0,ye.and)(Ol(t,e,o,n.ownProperties),(0,ye._)`${s} = ${o}`)))}me.checkMissingProp=l_;function c_(t,e){t.setParams({missingProperty:e},!0),t.error()}me.reportMissingProp=c_;function th(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ye._)`Object.prototype.hasOwnProperty`})}me.hasPropFunc=th;function Cl(t,e,n){return(0,ye._)`${th(t)}.call(${e}, ${n})`}me.isOwnProperty=Cl;function d_(t,e,n,r){let s=(0,ye._)`${e}${(0,ye.getProperty)(n)} !== undefined`;return r?(0,ye._)`${s} && ${Cl(t,e,n)}`:s}me.propertyInData=d_;function Ol(t,e,n,r){let s=(0,ye._)`${e}${(0,ye.getProperty)(n)} === undefined`;return r?(0,ye.or)(s,(0,ye.not)(Cl(t,e,n))):s}me.noPropertyInData=Ol;function nh(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}me.allSchemaProperties=nh;function u_(t,e){return nh(e).filter(n=>!(0,Il.alwaysValidSchema)(t,e[n]))}me.schemaProperties=u_;function p_({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:s,errorPath:o},it:i},a,l,p){let u=p?(0,ye._)`${t}, ${e}, ${r}${s}`:e,m=[[Jt.default.instancePath,(0,ye.strConcat)(Jt.default.instancePath,o)],[Jt.default.parentData,i.parentData],[Jt.default.parentDataProperty,i.parentDataProperty],[Jt.default.rootData,Jt.default.rootData]];i.opts.dynamicRef&&m.push([Jt.default.dynamicAnchors,Jt.default.dynamicAnchors]);let x=(0,ye._)`${u}, ${n.object(...m)}`;return l!==ye.nil?(0,ye._)`${a}.call(${l}, ${x})`:(0,ye._)`${a}(${x})`}me.callValidateCode=p_;var f_=(0,ye._)`new RegExp`;function h_({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(n,r);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,ye._)`${s.code==="new RegExp"?f_:(0,i_.useFunc)(t,s)}(${n}, ${r})`})}me.usePattern=h_;function m_(t){let{gen:e,data:n,keyword:r,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let l=e.const("len",(0,ye._)`${n}.length`);e.forRange("i",0,l,p=>{t.subschema({keyword:r,dataProp:p,dataPropType:Il.Type.Num},o),e.if((0,ye.not)(o),a)})}}me.validateArray=m_;function g_(t){let{gen:e,schema:n,keyword:r,it:s}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(l=>(0,Il.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((l,p)=>{let u=t.subschema({keyword:r,schemaProp:p,compositeRule:!0},a);e.assign(i,(0,ye._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,ye.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}me.validateUnion=g_});var oh=L(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.validateKeywordUsage=kt.validSchemaType=kt.funcKeywordCode=kt.macroKeywordCode=void 0;var Fe=ee(),fn=Ct(),y_=lt(),b_=Hr();function w_(t,e){let{gen:n,keyword:r,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=sh(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let p=n.name("valid");t.subschema({schema:a,schemaPath:Fe.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},p),t.pass(p,()=>t.error(!0))}kt.macroKeywordCode=w_;function v_(t,e){var n;let{gen:r,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;S_(l,e);let p=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,u=sh(r,s,p),m=r.let("valid");t.block$data(m,x),t.ok((n=e.valid)!==null&&n!==void 0?n:m);function x(){if(e.errors===!1)R(),e.modifying&&rh(t),E(()=>t.error());else{let P=e.async?v():k();e.modifying&&rh(t),E(()=>k_(t,P))}}function v(){let P=r.let("ruleErrs",null);return r.try(()=>R((0,Fe._)`await `),I=>r.assign(m,!1).if((0,Fe._)`${I} instanceof ${l.ValidationError}`,()=>r.assign(P,(0,Fe._)`${I}.errors`),()=>r.throw(I))),P}function k(){let P=(0,Fe._)`${u}.errors`;return r.assign(P,null),R(Fe.nil),P}function R(P=e.async?(0,Fe._)`await `:Fe.nil){let I=l.opts.passContext?fn.default.this:fn.default.self,U=!("compile"in e&&!a||e.schema===!1);r.assign(m,(0,Fe._)`${P}${(0,y_.callValidateCode)(t,u,I,U)}`,e.modifying)}function E(P){var I;r.if((0,Fe.not)((I=e.valid)!==null&&I!==void 0?I:m),P)}}kt.funcKeywordCode=v_;function rh(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Fe._)`${r.parentData}[${r.parentDataProperty}]`))}function k_(t,e){let{gen:n}=t;n.if((0,Fe._)`Array.isArray(${e})`,()=>{n.assign(fn.default.vErrors,(0,Fe._)`${fn.default.vErrors} === null ? ${e} : ${fn.default.vErrors}.concat(${e})`).assign(fn.default.errors,(0,Fe._)`${fn.default.vErrors}.length`),(0,b_.extendErrors)(t)},()=>t.error())}function S_({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function sh(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Fe.stringify)(n)})}function __(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}kt.validSchemaType=__;function $_({schema:t,opts:e,self:n,errSchemaPath:r},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${r}": `+n.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(l);else throw new Error(l)}}kt.validateKeywordUsage=$_});var ah=L(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.extendSubschemaMode=Zt.extendSubschemaData=Zt.getSubschema=void 0;var St=ee(),ih=le();function x_(t,{keyword:e,schemaProp:n,schema:r,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,St._)`${t.schemaPath}${(0,St.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,St._)`${t.schemaPath}${(0,St.getProperty)(e)}${(0,St.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,ih.escapeFragment)(n)}`}}if(r!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Zt.getSubschema=x_;function R_(t,e,{dataProp:n,dataPropType:r,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:p,dataPathArr:u,opts:m}=e,x=a.let("data",(0,St._)`${e.data}${(0,St.getProperty)(n)}`,!0);l(x),t.errorPath=(0,St.str)`${p}${(0,ih.getErrorPath)(n,r,m.jsPropertySyntax)}`,t.parentDataProperty=(0,St._)`${n}`,t.dataPathArr=[...u,t.parentDataProperty]}if(s!==void 0){let p=s instanceof St.Name?s:a.let("data",s,!0);l(p),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(p){t.data=p,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,p]}}Zt.extendSubschemaData=R_;function T_(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:s,allErrors:o}){r!==void 0&&(t.compositeRule=r),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=n}Zt.extendSubschemaMode=T_});var Nl=L((eN,lh)=>{"use strict";lh.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,s,o;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(s=r;s--!==0;)if(!t(e[s],n[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(o=Object.keys(e),r=o.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[s]))return!1;for(s=r;s--!==0;){var i=o[s];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var dh=L((tN,ch)=>{"use strict";var Yt=ch.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},s=n.post||function(){};Eo(e,r,s,t,"",t)};Yt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Yt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Yt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Yt.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Eo(t,e,n,r,s,o,i,a,l,p){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,s,o,i,a,l,p);for(var u in r){var m=r[u];if(Array.isArray(m)){if(u in Yt.arrayKeywords)for(var x=0;x<m.length;x++)Eo(t,e,n,m[x],s+"/"+u+"/"+x,o,s,u,r,x)}else if(u in Yt.propsKeywords){if(m&&typeof m=="object")for(var v in m)Eo(t,e,n,m[v],s+"/"+u+"/"+E_(v),o,s,u,r,v)}else(u in Yt.keywords||t.allKeys&&!(u in Yt.skipKeywords))&&Eo(t,e,n,m,s+"/"+u,o,s,u,r)}n(r,s,o,i,a,l,p)}}function E_(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Vr=L(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.getSchemaRefs=We.resolveUrl=We.normalizeId=We._getFullPath=We.getFullPath=We.inlineRef=void 0;var P_=le(),A_=Nl(),I_=dh(),C_=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function O_(t,e=!0){return typeof t=="boolean"?!0:e===!0?!jl(t):e?uh(t)<=e:!1}We.inlineRef=O_;var N_=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function jl(t){for(let e in t){if(N_.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(jl)||typeof n=="object"&&jl(n))return!0}return!1}function uh(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!C_.has(n)&&(typeof t[n]=="object"&&(0,P_.eachItem)(t[n],r=>e+=uh(r)),e===1/0))return 1/0}return e}function ph(t,e="",n){n!==!1&&(e=Hn(e));let r=t.parse(e);return fh(t,r)}We.getFullPath=ph;function fh(t,e){return t.serialize(e).split("#")[0]+"#"}We._getFullPath=fh;var j_=/#\/?$/;function Hn(t){return t?t.replace(j_,""):""}We.normalizeId=Hn;function L_(t,e,n){return n=Hn(n),t.resolve(e,n)}We.resolveUrl=L_;var D_=/^[a-z_][-a-z0-9._]*$/i;function U_(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,s=Hn(t[n]||e),o={"":s},i=ph(r,s,!1),a={},l=new Set;return I_(t,{allKeys:!0},(m,x,v,k)=>{if(k===void 0)return;let R=i+x,E=o[k];typeof m[n]=="string"&&(E=P.call(this,m[n])),I.call(this,m.$anchor),I.call(this,m.$dynamicAnchor),o[x]=E;function P(U){let se=this.opts.uriResolver.resolve;if(U=Hn(E?se(E,U):U),l.has(U))throw u(U);l.add(U);let V=this.refs[U];return typeof V=="string"&&(V=this.refs[V]),typeof V=="object"?p(m,V.schema,U):U!==Hn(R)&&(U[0]==="#"?(p(m,a[U],U),a[U]=m):this.refs[U]=R),U}function I(U){if(typeof U=="string"){if(!D_.test(U))throw new Error(`invalid anchor "${U}"`);P.call(this,`#${U}`)}}}),a;function p(m,x,v){if(x!==void 0&&!A_(m,x))throw u(v)}function u(m){return new Error(`reference "${m}" resolves to more than one schema`)}}We.getSchemaRefs=U_});var Jr=L(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.getData=Qt.KeywordCxt=Qt.validateFunctionCode=void 0;var bh=Gf(),hh=Kr(),Dl=Tl(),Po=Kr(),z_=eh(),Wr=oh(),Ll=ah(),q=ee(),Z=Ct(),q_=Vr(),Ot=le(),Gr=Hr();function M_(t){if(kh(t)&&(Sh(t),vh(t))){H_(t);return}wh(t,()=>(0,bh.topBoolOrEmptySchema)(t))}Qt.validateFunctionCode=M_;function wh({gen:t,validateName:e,schema:n,schemaEnv:r,opts:s},o){s.code.es5?t.func(e,(0,q._)`${Z.default.data}, ${Z.default.valCxt}`,r.$async,()=>{t.code((0,q._)`"use strict"; ${mh(n,s)}`),F_(t,s),t.code(o)}):t.func(e,(0,q._)`${Z.default.data}, ${B_(s)}`,r.$async,()=>t.code(mh(n,s)).code(o))}function B_(t){return(0,q._)`{${Z.default.instancePath}="", ${Z.default.parentData}, ${Z.default.parentDataProperty}, ${Z.default.rootData}=${Z.default.data}${t.dynamicRef?(0,q._)`, ${Z.default.dynamicAnchors}={}`:q.nil}}={}`}function F_(t,e){t.if(Z.default.valCxt,()=>{t.var(Z.default.instancePath,(0,q._)`${Z.default.valCxt}.${Z.default.instancePath}`),t.var(Z.default.parentData,(0,q._)`${Z.default.valCxt}.${Z.default.parentData}`),t.var(Z.default.parentDataProperty,(0,q._)`${Z.default.valCxt}.${Z.default.parentDataProperty}`),t.var(Z.default.rootData,(0,q._)`${Z.default.valCxt}.${Z.default.rootData}`),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,q._)`${Z.default.valCxt}.${Z.default.dynamicAnchors}`)},()=>{t.var(Z.default.instancePath,(0,q._)`""`),t.var(Z.default.parentData,(0,q._)`undefined`),t.var(Z.default.parentDataProperty,(0,q._)`undefined`),t.var(Z.default.rootData,Z.default.data),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,q._)`{}`)})}function H_(t){let{schema:e,opts:n,gen:r}=t;wh(t,()=>{n.$comment&&e.$comment&&$h(t),J_(t),r.let(Z.default.vErrors,null),r.let(Z.default.errors,0),n.unevaluated&&K_(t),_h(t),Q_(t)})}function K_(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,q._)`${n}.evaluated`),e.if((0,q._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,q._)`${t.evaluated}.props`,(0,q._)`undefined`)),e.if((0,q._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,q._)`${t.evaluated}.items`,(0,q._)`undefined`))}function mh(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,q._)`/*# sourceURL=${n} */`:q.nil}function V_(t,e){if(kh(t)&&(Sh(t),vh(t))){G_(t,e);return}(0,bh.boolOrEmptySchema)(t,e)}function vh({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function kh(t){return typeof t.schema!="boolean"}function G_(t,e){let{schema:n,gen:r,opts:s}=t;s.$comment&&n.$comment&&$h(t),Z_(t),Y_(t);let o=r.const("_errs",Z.default.errors);_h(t,o),r.var(e,(0,q._)`${o} === ${Z.default.errors}`)}function Sh(t){(0,Ot.checkUnknownRules)(t),W_(t)}function _h(t,e){if(t.opts.jtd)return gh(t,[],!1,e);let n=(0,hh.getSchemaTypes)(t.schema),r=(0,hh.coerceAndCheckDataType)(t,n);gh(t,n,!r,e)}function W_(t){let{schema:e,errSchemaPath:n,opts:r,self:s}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Ot.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function J_(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Ot.checkStrictMode)(t,"default is ignored in the schema root")}function Z_(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,q_.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Y_(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function $h({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:s}){let o=n.$comment;if(s.$comment===!0)t.code((0,q._)`${Z.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,q.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,q._)`${Z.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function Q_(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=t;n.$async?e.if((0,q._)`${Z.default.errors} === 0`,()=>e.return(Z.default.data),()=>e.throw((0,q._)`new ${s}(${Z.default.vErrors})`)):(e.assign((0,q._)`${r}.errors`,Z.default.vErrors),o.unevaluated&&X_(t),e.return((0,q._)`${Z.default.errors} === 0`))}function X_({gen:t,evaluated:e,props:n,items:r}){n instanceof q.Name&&t.assign((0,q._)`${e}.props`,n),r instanceof q.Name&&t.assign((0,q._)`${e}.items`,r)}function gh(t,e,n,r){let{gen:s,schema:o,data:i,allErrors:a,opts:l,self:p}=t,{RULES:u}=p;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,Ot.schemaHasRulesButRef)(o,u))){s.block(()=>Rh(t,"$ref",u.all.$ref.definition));return}l.jtd||e$(t,e),s.block(()=>{for(let x of u.rules)m(x);m(u.post)});function m(x){(0,Dl.shouldUseGroup)(o,x)&&(x.type?(s.if((0,Po.checkDataType)(x.type,i,l.strictNumbers)),yh(t,x),e.length===1&&e[0]===x.type&&n&&(s.else(),(0,Po.reportTypeError)(t)),s.endIf()):yh(t,x),a||s.if((0,q._)`${Z.default.errors} === ${r||0}`))}}function yh(t,e){let{gen:n,schema:r,opts:{useDefaults:s}}=t;s&&(0,z_.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,Dl.shouldUseRule)(r,o)&&Rh(t,o.keyword,o.definition,e.type)})}function e$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(t$(t,e),t.opts.allowUnionTypes||n$(t,e),r$(t,t.dataTypes))}function t$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{xh(t.dataTypes,n)||Ul(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),o$(t,e)}}function n$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ul(t,"use allowUnionTypes to allow union type keyword")}function r$(t,e){let n=t.self.RULES.all;for(let r in n){let s=n[r];if(typeof s=="object"&&(0,Dl.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>s$(e,i))&&Ul(t,`missing type "${o.join(",")}" for keyword "${r}"`)}}}function s$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function xh(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function o$(t,e){let n=[];for(let r of t.dataTypes)xh(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Ul(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Ot.checkStrictMode)(t,e,t.opts.strictTypes)}var Ao=class{constructor(e,n,r){if((0,Wr.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Ot.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Th(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Wr.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Z.default.errors))}result(e,n,r){this.failResult((0,q.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,q.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,q._)`${n} !== undefined && (${(0,q.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?Gr.reportExtraError:Gr.reportError)(this,this.def.error,n)}$dataError(){(0,Gr.reportError)(this,this.def.$dataError||Gr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Gr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=q.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=q.nil,n=q.nil){if(!this.$data)return;let{gen:r,schemaCode:s,schemaType:o,def:i}=this;r.if((0,q.or)((0,q._)`${s} === undefined`,n)),e!==q.nil&&r.assign(e,!0),(o.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==q.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:s,it:o}=this;return(0,q.or)(i(),a());function i(){if(r.length){if(!(n instanceof q.Name))throw new Error("ajv implementation error");let l=Array.isArray(r)?r:[r];return(0,q._)`${(0,Po.checkDataTypes)(l,n,o.opts.strictNumbers,Po.DataType.Wrong)}`}return q.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,q._)`!${l}(${n})`}return q.nil}}subschema(e,n){let r=(0,Ll.getSubschema)(this.it,e);(0,Ll.extendSubschemaData)(r,this.it,e),(0,Ll.extendSubschemaMode)(r,e);let s={...this.it,...r,items:void 0,props:void 0};return V_(s,n),s}mergeEvaluated(e,n){let{it:r,gen:s}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Ot.mergeEvaluated.props(s,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Ot.mergeEvaluated.items(s,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:s}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return s.if(n,()=>this.mergeEvaluated(e,q.Name)),!0}};Qt.KeywordCxt=Ao;function Rh(t,e,n,r){let s=new Ao(t,n,e);"code"in n?n.code(s,r):s.$data&&n.validate?(0,Wr.funcKeywordCode)(s,n):"macro"in n?(0,Wr.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,Wr.funcKeywordCode)(s,n)}var i$=/^\/(?:[^~]|~0|~1)*$/,a$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Th(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let s,o;if(t==="")return Z.default.rootData;if(t[0]==="/"){if(!i$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Z.default.rootData}else{let p=a$.exec(t);if(!p)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+p[1];if(s=p[2],s==="#"){if(u>=e)throw new Error(l("property/index",u));return r[e-u]}if(u>e)throw new Error(l("data",u));if(o=n[e-u],!s)return o}let i=o,a=s.split("/");for(let p of a)p&&(o=(0,q._)`${o}${(0,q.getProperty)((0,Ot.unescapeJsonPointer)(p))}`,i=(0,q._)`${i} && ${o}`);return i;function l(p,u){return`Cannot access ${p} ${u} levels up, current level is ${e}`}}Qt.getData=Th});var Io=L(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var zl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ql.default=zl});var Zr=L(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var Ml=Vr(),Bl=class extends Error{constructor(e,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Ml.resolveUrl)(e,n,r),this.missingSchema=(0,Ml.normalizeId)((0,Ml.getFullPath)(e,this.missingRef))}};Fl.default=Bl});var Oo=L(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.resolveSchema=ct.getCompilingSchema=ct.resolveRef=ct.compileSchema=ct.SchemaEnv=void 0;var gt=ee(),l$=Io(),hn=Ct(),yt=Vr(),Eh=le(),c$=Jr(),Kn=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,yt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};ct.SchemaEnv=Kn;function Kl(t){let e=Ph.call(this,t);if(e)return e;let n=(0,yt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new gt.CodeGen(this.scope,{es5:r,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:l$.default,code:(0,gt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let p={gen:i,allErrors:this.opts.allErrors,data:hn.default.data,parentData:hn.default.parentData,parentDataProperty:hn.default.parentDataProperty,dataNames:[hn.default.data],dataPathArr:[gt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,gt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:gt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,gt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,c$.validateFunctionCode)(p),i.optimize(this.opts.code.optimize);let m=i.toString();u=`${i.scopeRefs(hn.default.scope)}return ${m}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let v=new Function(`${hn.default.self}`,`${hn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:v}),v.errors=null,v.schema=t.schema,v.schemaEnv=t,t.$async&&(v.$async=!0),this.opts.code.source===!0&&(v.source={validateName:l,validateCode:m,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:R}=p;v.evaluated={props:k instanceof gt.Name?void 0:k,items:R instanceof gt.Name?void 0:R,dynamicProps:k instanceof gt.Name,dynamicItems:R instanceof gt.Name},v.source&&(v.source.evaluated=(0,gt.stringify)(v.evaluated))}return t.validate=v,t}catch(m){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),m}finally{this._compilations.delete(t)}}ct.compileSchema=Kl;function d$(t,e,n){var r;n=(0,yt.resolveUrl)(this.opts.uriResolver,e,n);let s=t.refs[n];if(s)return s;let o=f$.call(this,t,n);if(o===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(o=new Kn({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=u$.call(this,o)}ct.resolveRef=d$;function u$(t){return(0,yt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Kl.call(this,t)}function Ph(t){for(let e of this._compilations)if(p$(e,t))return e}ct.getCompilingSchema=Ph;function p$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function f$(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Co.call(this,t,e)}function Co(t,e){let n=this.opts.uriResolver.parse(e),r=(0,yt._getFullPath)(this.opts.uriResolver,n),s=(0,yt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===s)return Hl.call(this,n,t);let o=(0,yt.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Co.call(this,t,i);return typeof a?.schema!="object"?void 0:Hl.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Kl.call(this,i),o===(0,yt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,p=a[l];return p&&(s=(0,yt.resolveUrl)(this.opts.uriResolver,s,p)),new Kn({schema:a,schemaId:l,root:t,baseId:s})}return Hl.call(this,n,i)}}ct.resolveSchema=Co;var h$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Hl(t,{baseId:e,schema:n,root:r}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let l=n[(0,Eh.unescapeFragment)(a)];if(l===void 0)return;n=l;let p=typeof n=="object"&&n[this.opts.schemaId];!h$.has(a)&&p&&(e=(0,yt.resolveUrl)(this.opts.uriResolver,e,p))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,Eh.schemaHasRulesButRef)(n,this.RULES)){let a=(0,yt.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=Co.call(this,r,a)}let{schemaId:i}=this.opts;if(o=o||new Kn({schema:n,schemaId:i,root:r,baseId:e}),o.schema!==o.root.schema)return o}});var Ah=L((aN,m$)=>{m$.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Wl=L((lN,Lh)=>{"use strict";var g$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ch=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Vl=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Oh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),y$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Gl(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var b$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ih(t){return t.length=0,!0}function w$(t,e,n){if(t.length){let r=Gl(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function v$(t){let e=0,n={error:!1,address:"",zone:""},r=[],s=[],o=!1,i=!1,a=w$;for(let l=0;l<t.length;l++){let p=t[l];if(!(p==="["||p==="]"))if(p===":"){if(o===!0&&(i=!0),!a(s,r,n))break;if(++e>7){n.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),r.push(":");continue}else if(p==="%"){if(!a(s,r,n))break;a=Ih}else{s.push(p);continue}}return s.length&&(a===Ih?n.zone=s.join(""):i?r.push(s.join("")):r.push(Gl(s))),n.address=r.join(""),n}function Nh(t){if(k$(t,":")<2)return{host:t,isIPV6:!1};let e=v$(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function k$(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function S$(t){let e=t,n=[],r=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(s===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}var _$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},$$=/[@/?#:]/g,x$=/[@/?#]/g;function jh(t,e){let n=e?x$:$$;return n.lastIndex=0,t.replace(n,r=>_$[r])}function R$(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(Vl(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&Oh(i)?n+=i:n+="%"+o,r+=2;continue}}n+=t[r]}return n}function T$(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(Vl(r)){let s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&Oh(o)?e+=o:e+="%"+s,n+=2;continue}}y$(t[n])?e+=t[n]:e+=escape(t[n])}return e}function E$(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(Vl(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function P$(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Ch(n)){let r=Nh(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=jh(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Lh.exports={nonSimpleDomain:b$,recomposeAuthority:P$,reescapeHostDelimiters:jh,normalizePercentEncoding:R$,normalizePathEncoding:T$,escapePreservingEscapes:E$,removeDotSegments:S$,isIPv4:Ch,isUUID:g$,normalizeIPv6:Nh,stringArrayToHexStripped:Gl}});var Mh=L((cN,qh)=>{"use strict";var{isUUID:A$}=Wl(),I$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,C$=["http","https","ws","wss","urn","urn:uuid"];function O$(t){return C$.indexOf(t)!==-1}function Jl(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Dh(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Uh(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function N$(t){return t.secure=Jl(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function j$(t){if((t.port===(Jl(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function L$(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(I$);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let s=`${r}:${e.nid||t.nid}`,o=Zl(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function D$(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),s=`${n}:${e.nid||r}`,o=Zl(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function U$(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!A$(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function z$(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var zh={scheme:"http",domainHost:!0,parse:Dh,serialize:Uh},q$={scheme:"https",domainHost:zh.domainHost,parse:Dh,serialize:Uh},No={scheme:"ws",domainHost:!0,parse:N$,serialize:j$},M$={scheme:"wss",domainHost:No.domainHost,parse:No.parse,serialize:No.serialize},B$={scheme:"urn",parse:L$,serialize:D$,skipNormalize:!0},F$={scheme:"urn:uuid",parse:U$,serialize:z$,skipNormalize:!0},jo={http:zh,https:q$,ws:No,wss:M$,urn:B$,"urn:uuid":F$};Object.setPrototypeOf(jo,null);function Zl(t){return t&&(jo[t]||jo[t.toLowerCase()])||void 0}qh.exports={wsIsSecure:Jl,SCHEMES:jo,isValidSchemeName:O$,getSchemeHandler:Zl}});var Vh=L((dN,Uo)=>{"use strict";var{normalizeIPv6:H$,removeDotSegments:Yr,recomposeAuthority:K$,normalizePercentEncoding:V$,normalizePathEncoding:G$,escapePreservingEscapes:W$,reescapeHostDelimiters:J$,isIPv4:Z$,nonSimpleDomain:Y$}=Wl(),{SCHEMES:Q$,getSchemeHandler:Fh}=Mh();function X$(t,e){return typeof t=="string"?t=ix(t,e):typeof t=="object"&&(t=Do(mn(t,e),e)),t}function ex(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=Lo(t,r),{parsed:i,malformedAuthorityOrPort:a}=Lo(e,r);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=Hh(s,i,r,!0);return r.skipEscape=!0,mn(l,r)}function Hh(t,e,n,r){let s={};return r||(t=Do(mn(t,n),n),e=Do(mn(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Yr(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Yr(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Yr(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Yr(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function tx(t,e,n){let r=Bh(t,n),s=Bh(e,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function mn(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),s=[],o=Fh(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=V$(n.path):(n.path=W$(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");let i=K$(n);if(i!==void 0&&(r.reference!=="suffix"&&s.push("//"),s.push(i),n.path&&n.path[0]!=="/"&&s.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!o||!o.absolutePath)&&(a=Yr(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return n.query!==void 0&&s.push("?",n.query),n.fragment!==void 0&&s.push("#",n.fragment),s.join("")}var nx=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,rx=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,sx=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function ox(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Lo(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match(rx);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(sx);if(a!==null){let p=a[1],u=p.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",s=!0):p.length!==u.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",s=!0))}let l=t.match(nx);if(l){r.scheme=l[1],r.userinfo=l[3],r.host=l[4],r.port=parseInt(l[5],10),r.path=l[6]||"",r.query=l[7],r.fragment=l[8],isNaN(r.port)&&(r.port=l[5]);let p=ox(r,l);if(p!==void 0&&(r.error=r.error||p,s=!0),r.host)if(Z$(r.host)===!1){let x=H$(r.host);r.host=x.host.toLowerCase(),o=x.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let u=Fh(n.scheme||r.scheme);if(!n.unicodeSupport&&(!u||!u.unicodeSupport)&&r.host&&(n.domainHost||u&&u.domainHost)&&o===!1&&Y$(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(m){r.error=r.error||"Host's domain name can not be converted to ASCII: "+m}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=J$(unescape(r.host),o))),r.path&&(r.path=G$(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}u&&u.parse&&u.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:s}}function Do(t,e){return Lo(t,e).parsed}function ix(t,e){return Kh(t,e).normalized}function Kh(t,e){let{parsed:n,malformedAuthorityOrPort:r}=Lo(t,e);return{normalized:r?t:mn(n,e),malformedAuthorityOrPort:r}}function Bh(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=Kh(t,e);return r?void 0:n}if(typeof t=="object")return mn(t,e)}var Yl={SCHEMES:Q$,normalize:X$,resolve:ex,resolveComponent:Hh,equal:tx,serialize:mn,parse:Do};Uo.exports=Yl;Uo.exports.default=Yl;Uo.exports.fastUri=Yl});var Wh=L(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var Gh=Vh();Gh.code='require("ajv/dist/runtime/uri").default';Ql.default=Gh});var nm=L(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=void 0;var ax=Jr();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return ax.KeywordCxt}});var Vn=ee();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Vn._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Vn.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Vn.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Vn.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Vn.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Vn.CodeGen}});var lx=Io(),Xh=Zr(),cx=Rl(),Qr=Oo(),dx=ee(),Xr=Vr(),zo=Kr(),ec=le(),Jh=Ah(),ux=Wh(),em=(t,e)=>new RegExp(t,e);em.code="new RegExp";var px=["removeAdditional","useDefaults","coerceTypes"],fx=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),hx={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},mx={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Zh=200;function gx(t){var e,n,r,s,o,i,a,l,p,u,m,x,v,k,R,E,P,I,U,se,V,De,He,rr,Nt;let Ze=t.strict,sr=(e=t.code)===null||e===void 0?void 0:e.optimize,fs=sr===!0||sr===void 0?1:sr||0,jt=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:em,or=(s=t.uriResolver)!==null&&s!==void 0?s:ux.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:Ze)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:Ze)!==null&&l!==void 0?l:!0,strictTypes:(u=(p=t.strictTypes)!==null&&p!==void 0?p:Ze)!==null&&u!==void 0?u:"log",strictTuples:(x=(m=t.strictTuples)!==null&&m!==void 0?m:Ze)!==null&&x!==void 0?x:"log",strictRequired:(k=(v=t.strictRequired)!==null&&v!==void 0?v:Ze)!==null&&k!==void 0?k:!1,code:t.code?{...t.code,optimize:fs,regExp:jt}:{optimize:fs,regExp:jt},loopRequired:(R=t.loopRequired)!==null&&R!==void 0?R:Zh,loopEnum:(E=t.loopEnum)!==null&&E!==void 0?E:Zh,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(U=t.inlineRefs)!==null&&U!==void 0?U:!0,schemaId:(se=t.schemaId)!==null&&se!==void 0?se:"$id",addUsedSchema:(V=t.addUsedSchema)!==null&&V!==void 0?V:!0,validateSchema:(De=t.validateSchema)!==null&&De!==void 0?De:!0,validateFormats:(He=t.validateFormats)!==null&&He!==void 0?He:!0,unicodeRegExp:(rr=t.unicodeRegExp)!==null&&rr!==void 0?rr:!0,int32range:(Nt=t.int32range)!==null&&Nt!==void 0?Nt:!0,uriResolver:or}}var es=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...gx(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new dx.ValueScope({scope:{},prefixes:fx,es5:n,lines:r}),this.logger=Sx(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,cx.getRules)(),Yh.call(this,hx,e,"NOT SUPPORTED"),Yh.call(this,mx,e,"DEPRECATED","warn"),this._metaOpts=vx.call(this),e.formats&&bx.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&wx.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),yx.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,s=Jh;r==="id"&&(s={...Jh},s.id=s.$id,delete s.$id),n&&e&&this.addMetaSchema(s,s[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let s=r(n);return"$async"in r||(this.errors=r.errors),s}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return s.call(this,e,n);async function s(u,m){await o.call(this,u.$schema);let x=this._addSchema(u,m);return x.validate||i.call(this,x)}async function o(u){u&&!this.getSchema(u)&&await s.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(m){if(!(m instanceof Xh.default))throw m;return a.call(this,m),await l.call(this,m.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:m}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${m} cannot be resolved`)}async function l(u){let m=await p.call(this,u);this.refs[u]||await o.call(this,m.$schema),this.refs[u]||this.addSchema(m,u,n)}async function p(u){let m=this._loading[u];if(m)return m;try{return await(this._loading[u]=r(u))}finally{delete this._loading[u]}}}addSchema(e,n,r,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return n=(0,Xr.normalizeId)(n||o),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,s,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(r,e);if(!s&&n){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let n;for(;typeof(n=Qh.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,s=new Qr.SchemaEnv({schema:{},schemaId:r});if(n=Qr.resolveSchema.call(this,s,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=Qh.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Xr.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if($x.call(this,r,n),!n)return(0,ec.eachItem)(r,o=>Xl.call(this,o)),this;Rx.call(this,n);let s={...n,type:(0,zo.getJSONTypes)(n.type),schemaType:(0,zo.getJSONTypes)(n.schemaType)};return(0,ec.eachItem)(r,s.type.length===0?o=>Xl.call(this,o,s):o=>s.type.forEach(i=>Xl.call(this,o,s,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let s=r.rules.findIndex(o=>o.keyword===e);s>=0&&r.rules.splice(s,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${r}${s.instancePath} ${s.message}`).reduce((s,o)=>s+n+o)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of n){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in r){let l=r[a];if(typeof l!="object")continue;let{$data:p}=l.definition,u=i[a];p&&u&&(i[a]=tm(u))}}return e}_removeAllSchemas(e,n){for(let r in e){let s=e[r];(!n||n.test(r))&&(typeof s=="string"?delete e[r]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[r]))}}_addSchema(e,n,r,s=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;r=(0,Xr.normalizeId)(i||r);let p=Xr.getSchemaRefs.call(this,e,r);return l=new Qr.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:p}),this._cache.set(l.schema,l),o&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=l),s&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Qr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{Qr.compileSchema.call(this,e)}finally{this.opts=n}}};es.ValidationError=lx.default;es.MissingRefError=Xh.default;Ae.default=es;function Yh(t,e,n,r="error"){for(let s in t){let o=s;o in e&&this.logger[r](`${n}: option ${s}. ${t[o]}`)}}function Qh(t){return t=(0,Xr.normalizeId)(t),this.schemas[t]||this.refs[t]}function yx(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function bx(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function wx(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function vx(){let t={...this.opts};for(let e of px)delete t[e];return t}var kx={log(){},warn(){},error(){}};function Sx(t){if(t===!1)return kx;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var _x=/^[a-z_$][a-z0-9_$:-]*$/i;function $x(t,e){let{RULES:n}=this;if((0,ec.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!_x.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Xl(t,e,n){var r;let s=e?.post;if(n&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:l})=>l===n);if(i||(i={type:n,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,zo.getJSONTypes)(e.type),schemaType:(0,zo.getJSONTypes)(e.schemaType)}};e.before?xx.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(l=>this.addKeyword(l))}function xx(t,e,n){let r=t.rules.findIndex(s=>s.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function Rx(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=tm(e)),t.validateSchema=this.compile(e,!0))}var Tx={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function tm(t){return{anyOf:[t,Tx]}}});var rm=L(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Ex={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};tc.default=Ex});var am=L(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.callRef=gn.getValidate=void 0;var Px=Zr(),sm=lt(),Je=ee(),Gn=Ct(),om=Oo(),qo=le(),Ax={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:l}=r,{root:p}=o;if((n==="#"||n==="#/")&&s===p.baseId)return m();let u=om.resolveRef.call(l,p,s,n);if(u===void 0)throw new Px.default(r.opts.uriResolver,s,n);if(u instanceof om.SchemaEnv)return x(u);return v(u);function m(){if(o===p)return Mo(t,i,o,o.$async);let k=e.scopeValue("root",{ref:p});return Mo(t,(0,Je._)`${k}.validate`,p,p.$async)}function x(k){let R=im(t,k);Mo(t,R,k,k.$async)}function v(k){let R=e.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,Je.stringify)(k)}:{ref:k}),E=e.name("valid"),P=t.subschema({schema:k,dataTypes:[],schemaPath:Je.nil,topSchemaRef:R,errSchemaPath:n},E);t.mergeEvaluated(P),t.ok(E)}}};function im(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Je._)`${n.scopeValue("wrapper",{ref:e})}.validate`}gn.getValidate=im;function Mo(t,e,n,r){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,p=l.passContext?Gn.default.this:Je.nil;r?u():m();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=s.let("valid");s.try(()=>{s.code((0,Je._)`await ${(0,sm.callValidateCode)(t,e,p)}`),v(e),i||s.assign(k,!0)},R=>{s.if((0,Je._)`!(${R} instanceof ${o.ValidationError})`,()=>s.throw(R)),x(R),i||s.assign(k,!1)}),t.ok(k)}function m(){t.result((0,sm.callValidateCode)(t,e,p),()=>v(e),()=>x(e))}function x(k){let R=(0,Je._)`${k}.errors`;s.assign(Gn.default.vErrors,(0,Je._)`${Gn.default.vErrors} === null ? ${R} : ${Gn.default.vErrors}.concat(${R})`),s.assign(Gn.default.errors,(0,Je._)`${Gn.default.vErrors}.length`)}function v(k){var R;if(!o.opts.unevaluated)return;let E=(R=n?.validate)===null||R===void 0?void 0:R.evaluated;if(o.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(o.props=qo.mergeEvaluated.props(s,E.props,o.props));else{let P=s.var("props",(0,Je._)`${k}.evaluated.props`);o.props=qo.mergeEvaluated.props(s,P,o.props,Je.Name)}if(o.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(o.items=qo.mergeEvaluated.items(s,E.items,o.items));else{let P=s.var("items",(0,Je._)`${k}.evaluated.items`);o.items=qo.mergeEvaluated.items(s,P,o.items,Je.Name)}}}gn.callRef=Mo;gn.default=Ax});var lm=L(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var Ix=rm(),Cx=am(),Ox=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Ix.default,Cx.default];nc.default=Ox});var cm=L(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var Bo=ee(),Xt=Bo.operators,Fo={maximum:{okStr:"<=",ok:Xt.LTE,fail:Xt.GT},minimum:{okStr:">=",ok:Xt.GTE,fail:Xt.LT},exclusiveMaximum:{okStr:"<",ok:Xt.LT,fail:Xt.GTE},exclusiveMinimum:{okStr:">",ok:Xt.GT,fail:Xt.LTE}},Nx={message:({keyword:t,schemaCode:e})=>(0,Bo.str)`must be ${Fo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Bo._)`{comparison: ${Fo[t].okStr}, limit: ${e}}`},jx={keyword:Object.keys(Fo),type:"number",schemaType:"number",$data:!0,error:Nx,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Bo._)`${n} ${Fo[e].fail} ${r} || isNaN(${n})`)}};rc.default=jx});var dm=L(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var ts=ee(),Lx={message:({schemaCode:t})=>(0,ts.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ts._)`{multipleOf: ${t}}`},Dx={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Lx,code(t){let{gen:e,data:n,schemaCode:r,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,ts._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,ts._)`${i} !== parseInt(${i})`;t.fail$data((0,ts._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};sc.default=Dx});var pm=L(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});function um(t){let e=t.length,n=0,r=0,s;for(;r<e;)n++,s=t.charCodeAt(r++),s>=55296&&s<=56319&&r<e&&(s=t.charCodeAt(r),(s&64512)===56320&&r++);return n}oc.default=um;um.code='require("ajv/dist/runtime/ucs2length").default'});var fm=L(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var yn=ee(),Ux=le(),zx=pm(),qx={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,yn.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,yn._)`{limit: ${t}}`},Mx={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:qx,code(t){let{keyword:e,data:n,schemaCode:r,it:s}=t,o=e==="maxLength"?yn.operators.GT:yn.operators.LT,i=s.opts.unicode===!1?(0,yn._)`${n}.length`:(0,yn._)`${(0,Ux.useFunc)(t.gen,zx.default)}(${n})`;t.fail$data((0,yn._)`${i} ${o} ${r}`)}};ic.default=Mx});var hm=L(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var Bx=lt(),Fx=le(),Wn=ee(),Hx={message:({schemaCode:t})=>(0,Wn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Wn._)`{pattern: ${t}}`},Kx={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Hx,code(t){let{gen:e,data:n,$data:r,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:l}=i.opts.code,p=l.code==="new RegExp"?(0,Wn._)`new RegExp`:(0,Fx.useFunc)(e,l),u=e.let("valid");e.try(()=>e.assign(u,(0,Wn._)`${p}(${o}, ${a}).test(${n})`),()=>e.assign(u,!1)),t.fail$data((0,Wn._)`!${u}`)}else{let l=(0,Bx.usePattern)(t,s);t.fail$data((0,Wn._)`!${l}.test(${n})`)}}};ac.default=Kx});var mm=L(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var ns=ee(),Vx={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,ns.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,ns._)`{limit: ${t}}`},Gx={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Vx,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxProperties"?ns.operators.GT:ns.operators.LT;t.fail$data((0,ns._)`Object.keys(${n}).length ${s} ${r}`)}};lc.default=Gx});var gm=L(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var rs=lt(),ss=ee(),Wx=le(),Jx={message:({params:{missingProperty:t}})=>(0,ss.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ss._)`{missingProperty: ${t}}`},Zx={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Jx,code(t){let{gen:e,schema:n,schemaCode:r,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&n.length===0)return;let l=n.length>=a.loopRequired;if(i.allErrors?p():u(),a.strictRequired){let v=t.parentSchema.properties,{definedProperties:k}=t.it;for(let R of n)if(v?.[R]===void 0&&!k.has(R)){let E=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${R}" is not defined at "${E}" (strictRequired)`;(0,Wx.checkStrictMode)(i,P,i.opts.strictRequired)}}function p(){if(l||o)t.block$data(ss.nil,m);else for(let v of n)(0,rs.checkReportMissingProp)(t,v)}function u(){let v=e.let("missing");if(l||o){let k=e.let("valid",!0);t.block$data(k,()=>x(v,k)),t.ok(k)}else e.if((0,rs.checkMissingProp)(t,n,v)),(0,rs.reportMissingProp)(t,v),e.else()}function m(){e.forOf("prop",r,v=>{t.setParams({missingProperty:v}),e.if((0,rs.noPropertyInData)(e,s,v,a.ownProperties),()=>t.error())})}function x(v,k){t.setParams({missingProperty:v}),e.forOf(v,r,()=>{e.assign(k,(0,rs.propertyInData)(e,s,v,a.ownProperties)),e.if((0,ss.not)(k),()=>{t.error(),e.break()})},ss.nil)}}};cc.default=Zx});var ym=L(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var os=ee(),Yx={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,os.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,os._)`{limit: ${t}}`},Qx={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Yx,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxItems"?os.operators.GT:os.operators.LT;t.fail$data((0,os._)`${n}.length ${s} ${r}`)}};dc.default=Qx});var Ho=L(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var bm=Nl();bm.code='require("ajv/dist/runtime/equal").default';uc.default=bm});var wm=L(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var pc=Kr(),Ie=ee(),Xx=le(),eR=Ho(),tR={message:({params:{i:t,j:e}})=>(0,Ie.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ie._)`{i: ${t}, j: ${e}}`},nR={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:tR,code(t){let{gen:e,data:n,$data:r,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!r&&!s)return;let l=e.let("valid"),p=o.items?(0,pc.getSchemaTypes)(o.items):[];t.block$data(l,u,(0,Ie._)`${i} === false`),t.ok(l);function u(){let k=e.let("i",(0,Ie._)`${n}.length`),R=e.let("j");t.setParams({i:k,j:R}),e.assign(l,!0),e.if((0,Ie._)`${k} > 1`,()=>(m()?x:v)(k,R))}function m(){return p.length>0&&!p.some(k=>k==="object"||k==="array")}function x(k,R){let E=e.name("item"),P=(0,pc.checkDataTypes)(p,E,a.opts.strictNumbers,pc.DataType.Wrong),I=e.const("indices",(0,Ie._)`{}`);e.for((0,Ie._)`;${k}--;`,()=>{e.let(E,(0,Ie._)`${n}[${k}]`),e.if(P,(0,Ie._)`continue`),p.length>1&&e.if((0,Ie._)`typeof ${E} == "string"`,(0,Ie._)`${E} += "_"`),e.if((0,Ie._)`typeof ${I}[${E}] == "number"`,()=>{e.assign(R,(0,Ie._)`${I}[${E}]`),t.error(),e.assign(l,!1).break()}).code((0,Ie._)`${I}[${E}] = ${k}`)})}function v(k,R){let E=(0,Xx.useFunc)(e,eR.default),P=e.name("outer");e.label(P).for((0,Ie._)`;${k}--;`,()=>e.for((0,Ie._)`${R} = ${k}; ${R}--;`,()=>e.if((0,Ie._)`${E}(${n}[${k}], ${n}[${R}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};fc.default=nR});var vm=L(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var hc=ee(),rR=le(),sR=Ho(),oR={message:"must be equal to constant",params:({schemaCode:t})=>(0,hc._)`{allowedValue: ${t}}`},iR={keyword:"const",$data:!0,error:oR,code(t){let{gen:e,data:n,$data:r,schemaCode:s,schema:o}=t;r||o&&typeof o=="object"?t.fail$data((0,hc._)`!${(0,rR.useFunc)(e,sR.default)}(${n}, ${s})`):t.fail((0,hc._)`${o} !== ${n}`)}};mc.default=iR});var km=L(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var is=ee(),aR=le(),lR=Ho(),cR={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,is._)`{allowedValues: ${t}}`},dR={keyword:"enum",schemaType:"array",$data:!0,error:cR,code(t){let{gen:e,data:n,$data:r,schema:s,schemaCode:o,it:i}=t;if(!r&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,l,p=()=>l??(l=(0,aR.useFunc)(e,lR.default)),u;if(a||r)u=e.let("valid"),t.block$data(u,m);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let v=e.const("vSchema",o);u=(0,is.or)(...s.map((k,R)=>x(v,R)))}t.pass(u);function m(){e.assign(u,!1),e.forOf("v",o,v=>e.if((0,is._)`${p()}(${n}, ${v})`,()=>e.assign(u,!0).break()))}function x(v,k){let R=s[k];return typeof R=="object"&&R!==null?(0,is._)`${p()}(${n}, ${v}[${k}])`:(0,is._)`${n} === ${R}`}}};gc.default=dR});var Sm=L(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var uR=cm(),pR=dm(),fR=fm(),hR=hm(),mR=mm(),gR=gm(),yR=ym(),bR=wm(),wR=vm(),vR=km(),kR=[uR.default,pR.default,fR.default,hR.default,mR.default,gR.default,yR.default,bR.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},wR.default,vR.default];yc.default=kR});var wc=L(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.validateAdditionalItems=void 0;var bn=ee(),bc=le(),SR={message:({params:{len:t}})=>(0,bn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,bn._)`{limit: ${t}}`},_R={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:SR,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,bc.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}_m(t,r)}};function _m(t,e){let{gen:n,schema:r,data:s,keyword:o,it:i}=t;i.items=!0;let a=n.const("len",(0,bn._)`${s}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,bn._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,bc.alwaysValidSchema)(i,r)){let p=n.var("valid",(0,bn._)`${a} <= ${e.length}`);n.if((0,bn.not)(p),()=>l(p)),t.ok(p)}function l(p){n.forRange("i",e.length,a,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:bc.Type.Num},p),i.allErrors||n.if((0,bn.not)(p),()=>n.break())})}}as.validateAdditionalItems=_m;as.default=_R});var vc=L(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.validateTuple=void 0;var $m=ee(),Ko=le(),$R=lt(),xR={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return xm(t,"additionalItems",e);n.items=!0,!(0,Ko.alwaysValidSchema)(n,e)&&t.ok((0,$R.validateArray)(t))}};function xm(t,e,n=t.schema){let{gen:r,parentSchema:s,data:o,keyword:i,it:a}=t;u(s),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Ko.mergeEvaluated.items(r,n.length,a.items));let l=r.name("valid"),p=r.const("len",(0,$m._)`${o}.length`);n.forEach((m,x)=>{(0,Ko.alwaysValidSchema)(a,m)||(r.if((0,$m._)`${p} > ${x}`,()=>t.subschema({keyword:i,schemaProp:x,dataProp:x},l)),t.ok(l))});function u(m){let{opts:x,errSchemaPath:v}=a,k=n.length,R=k===m.minItems&&(k===m.maxItems||m[e]===!1);if(x.strictTuples&&!R){let E=`"${i}" is ${k}-tuple, but minItems or maxItems/${e} are not specified or different at path "${v}"`;(0,Ko.checkStrictMode)(a,E,x.strictTuples)}}}ls.validateTuple=xm;ls.default=xR});var Rm=L(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var RR=vc(),TR={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,RR.validateTuple)(t,"items")};kc.default=TR});var Em=L(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Tm=ee(),ER=le(),PR=lt(),AR=wc(),IR={message:({params:{len:t}})=>(0,Tm.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Tm._)`{limit: ${t}}`},CR={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:IR,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:s}=n;r.items=!0,!(0,ER.alwaysValidSchema)(r,e)&&(s?(0,AR.validateAdditionalItems)(t,s):t.ok((0,PR.validateArray)(t)))}};Sc.default=CR});var Pm=L(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var dt=ee(),Vo=le(),OR={message:({params:{min:t,max:e}})=>e===void 0?(0,dt.str)`must contain at least ${t} valid item(s)`:(0,dt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dt._)`{minContains: ${t}}`:(0,dt._)`{minContains: ${t}, maxContains: ${e}}`},NR={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:OR,code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t,i,a,{minContains:l,maxContains:p}=r;o.opts.next?(i=l===void 0?1:l,a=p):i=1;let u=e.const("len",(0,dt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Vo.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Vo.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Vo.alwaysValidSchema)(o,n)){let R=(0,dt._)`${u} >= ${i}`;a!==void 0&&(R=(0,dt._)`${R} && ${u} <= ${a}`),t.pass(R);return}o.items=!0;let m=e.name("valid");a===void 0&&i===1?v(m,()=>e.if(m,()=>e.break())):i===0?(e.let(m,!0),a!==void 0&&e.if((0,dt._)`${s}.length > 0`,x)):(e.let(m,!1),x()),t.result(m,()=>t.reset());function x(){let R=e.name("_valid"),E=e.let("count",0);v(R,()=>e.if(R,()=>k(E)))}function v(R,E){e.forRange("i",0,u,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:Vo.Type.Num,compositeRule:!0},R),E()})}function k(R){e.code((0,dt._)`${R}++`),a===void 0?e.if((0,dt._)`${R} >= ${i}`,()=>e.assign(m,!0).break()):(e.if((0,dt._)`${R} > ${a}`,()=>e.assign(m,!1).break()),i===1?e.assign(m,!0):e.if((0,dt._)`${R} >= ${i}`,()=>e.assign(m,!0)))}}};_c.default=NR});var Cm=L(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.validateSchemaDeps=_t.validatePropertyDeps=_t.error=void 0;var $c=ee(),jR=le(),cs=lt();_t.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,$c.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,$c._)`{property: ${t},
|
|
1090
1235
|
missingProperty: ${r},
|
|
1091
1236
|
depsCount: ${e},
|
|
1092
|
-
deps: ${n}}`};var lT={keyword:"dependencies",type:"object",schemaType:"object",error:St.error,code(t){let[e,n]=cT(t);pm(t,e),fm(t,n)}};function cT({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let s=Array.isArray(t[r])?e:n;s[r]=t[r]}return[e,n]}function pm(t,e=t.schema){let{gen:n,data:r,it:s}=t;if(Object.keys(e).length===0)return;let o=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,ls.propertyInData)(n,r,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?n.if(l,()=>{for(let d of a)(0,ls.checkReportMissingProp)(t,d)}):(n.if((0,gc._)`${l} && (${(0,ls.checkMissingProp)(t,a,o)})`),(0,ls.reportMissingProp)(t,o),n.else())}}St.validatePropertyDeps=pm;function fm(t,e=t.schema){let{gen:n,data:r,keyword:s,it:o}=t,i=n.name("valid");for(let a in e)(0,aT.alwaysValidSchema)(o,e[a])||(n.if((0,ls.propertyInData)(n,r,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>n.var(i,!0)),t.ok(i))}St.validateSchemaDeps=fm;St.default=lT});var gm=L(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var mm=X(),uT=le(),dT={message:"property name must be valid",params:({params:t})=>(0,mm._)`{propertyName: ${t.propertyName}}`},pT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:dT,code(t){let{gen:e,schema:n,data:r,it:s}=t;if((0,uT.alwaysValidSchema)(s,n))return;let o=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,mm.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};bc.default=pT});var wc=L(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Bo=at(),gt=X(),fT=At(),Fo=le(),hT={message:"must NOT have additional properties",params:({params:t})=>(0,gt._)`{additionalProperty: ${t.additionalProperty}}`},mT={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:hT,code(t){let{gen:e,schema:n,parentSchema:r,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Fo.alwaysValidSchema)(i,n))return;let d=(0,Bo.allSchemaProperties)(r.properties),p=(0,Bo.allSchemaProperties)(r.patternProperties);h(),t.ok((0,gt._)`${o} === ${fT.default.errors}`);function h(){e.forIn("key",s,R=>{!d.length&&!p.length?w(R):e.if(_(R),()=>w(R))})}function _(R){let P;if(d.length>8){let I=(0,Fo.schemaRefOrVal)(i,r.properties,"properties");P=(0,Bo.isOwnProperty)(e,I,R)}else d.length?P=(0,gt.or)(...d.map(I=>(0,gt._)`${R} === ${I}`)):P=gt.nil;return p.length&&(P=(0,gt.or)(P,...p.map(I=>(0,gt._)`${(0,Bo.usePattern)(t,I)}.test(${R})`))),(0,gt.not)(P)}function y(R){e.code((0,gt._)`delete ${s}[${R}]`)}function w(R){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){y(R);return}if(n===!1){t.setParams({additionalProperty:R}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Fo.alwaysValidSchema)(i,n)){let P=e.name("valid");l.removeAdditional==="failing"?(T(R,P,!1),e.if((0,gt.not)(P),()=>{t.reset(),y(R)})):(T(R,P),a||e.if((0,gt.not)(P),()=>e.break()))}}function T(R,P,I){let D={keyword:"additionalProperties",dataProp:R,dataPropType:Fo.Type.Str};I===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};yc.default=mT});var wm=L(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var gT=Wr(),bm=at(),vc=le(),ym=wc(),bT={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t;o.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&ym.default.code(new gT.KeywordCxt(o,ym.default,"additionalProperties"));let i=(0,bm.allSchemaProperties)(n);for(let h of i)o.definedProperties.add(h);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=vc.mergeEvaluated.props(e,(0,vc.toHash)(i),o.props));let a=i.filter(h=>!(0,vc.alwaysValidSchema)(o,n[h]));if(a.length===0)return;let l=e.name("valid");for(let h of a)d(h)?p(h):(e.if((0,bm.propertyInData)(e,s,h,o.opts.ownProperties)),p(h),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(h),t.ok(l);function d(h){return o.opts.useDefaults&&!o.compositeRule&&n[h].default!==void 0}function p(h){t.subschema({keyword:"properties",schemaProp:h,dataProp:h},l)}}};kc.default=bT});var _m=L(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var vm=at(),Ko=X(),km=le(),Sm=le(),yT={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,vm.allSchemaProperties)(n),l=a.filter(T=>(0,km.alwaysValidSchema)(o,n[T]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let d=i.strictSchema&&!i.allowMatchingProperties&&s.properties,p=e.name("valid");o.props!==!0&&!(o.props instanceof Ko.Name)&&(o.props=(0,Sm.evaluatedPropsToName)(e,o.props));let{props:h}=o;_();function _(){for(let T of a)d&&y(T),o.allErrors?w(T):(e.var(p,!0),w(T),e.if(p))}function y(T){for(let R in d)new RegExp(T).test(R)&&(0,km.checkStrictMode)(o,`property ${R} matches pattern ${T} (use allowMatchingProperties)`)}function w(T){e.forIn("key",r,R=>{e.if((0,Ko._)`${(0,vm.usePattern)(t,T)}.test(${R})`,()=>{let P=l.includes(T);P||t.subschema({keyword:"patternProperties",schemaProp:T,dataProp:R,dataPropType:Sm.Type.Str},p),o.opts.unevaluated&&h!==!0?e.assign((0,Ko._)`${h}[${R}]`,!0):!P&&!o.allErrors&&e.if((0,Ko.not)(p),()=>e.break())})})}}};Sc.default=yT});var $m=L(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var wT=le(),vT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,wT.alwaysValidSchema)(r,n)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};_c.default=vT});var xm=L($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var kT=at(),ST={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kT.validateUnion,error:{message:"must match a schema in anyOf"}};$c.default=ST});var Tm=L(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Ho=X(),_T=le(),$T={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ho._)`{passingSchemas: ${t.passing}}`},xT={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:$T,code(t){let{gen:e,schema:n,parentSchema:r,it:s}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(s.opts.discriminator&&r.discriminator)return;let o=n,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(d),t.result(i,()=>t.reset(),()=>t.error(!0));function d(){o.forEach((p,h)=>{let _;(0,_T.alwaysValidSchema)(s,p)?e.var(l,!0):_=t.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},l),h>0&&e.if((0,Ho._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Ho._)`[${a}, ${h}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,h),_&&t.mergeEvaluated(_,Ho.Name)})})}}};xc.default=xT});var Rm=L(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var TT=le(),RT={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let s=e.name("valid");n.forEach((o,i)=>{if((0,TT.alwaysValidSchema)(r,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Tc.default=RT});var Am=L(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var Vo=X(),Pm=le(),ET={message:({params:t})=>(0,Vo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Vo._)`{failingKeyword: ${t.ifClause}}`},PT={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ET,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Pm.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let s=Em(r,"then"),o=Em(r,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),s&&o){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,d("then",p),d("else",p))}else s?e.if(a,d("then")):e.if((0,Vo.not)(a),d("else"));t.pass(i,()=>t.error(!0));function l(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(p)}function d(p,h){return()=>{let _=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(_,i),h?e.assign(h,(0,Vo._)`${p}`):t.setParams({ifClause:p})}}}};function Em(t,e){let n=t.schema[e];return n!==void 0&&!(0,Pm.alwaysValidSchema)(t,n)}Rc.default=PT});var Im=L(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var AT=le(),IT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,AT.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Ec.default=IT});var Cm=L(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var CT=dc(),OT=lm(),NT=pc(),jT=um(),LT=dm(),zT=hm(),DT=gm(),UT=wc(),qT=wm(),MT=_m(),BT=$m(),FT=xm(),KT=Tm(),HT=Rm(),VT=Am(),GT=Im();function WT(t=!1){let e=[BT.default,FT.default,KT.default,HT.default,VT.default,GT.default,DT.default,UT.default,zT.default,qT.default,MT.default];return t?e.push(OT.default,jT.default):e.push(CT.default,NT.default),e.push(LT.default),e}Pc.default=WT});var Om=L(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var ve=X(),JT={message:({schemaCode:t})=>(0,ve.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ve._)`{format: ${t}}`},ZT={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:JT,code(t,e){let{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:d,schemaEnv:p,self:h}=a;if(!l.validateFormats)return;s?_():y();function _(){let w=n.scopeValue("formats",{ref:h.formats,code:l.code.formats}),T=n.const("fDef",(0,ve._)`${w}[${i}]`),R=n.let("fType"),P=n.let("format");n.if((0,ve._)`typeof ${T} == "object" && !(${T} instanceof RegExp)`,()=>n.assign(R,(0,ve._)`${T}.type || "string"`).assign(P,(0,ve._)`${T}.validate`),()=>n.assign(R,(0,ve._)`"string"`).assign(P,T)),t.fail$data((0,ve.or)(I(),D()));function I(){return l.strictSchema===!1?ve.nil:(0,ve._)`${i} && !${P}`}function D(){let se=p.$async?(0,ve._)`(${T}.async ? await ${P}(${r}) : ${P}(${r}))`:(0,ve._)`${P}(${r})`,H=(0,ve._)`(typeof ${P} == "function" ? ${se} : ${P}.test(${r}))`;return(0,ve._)`${P} && ${P} !== true && ${R} === ${e} && !${H}`}}function y(){let w=h.formats[o];if(!w){I();return}if(w===!0)return;let[T,R,P]=D(w);T===e&&t.pass(se());function I(){if(l.strictSchema===!1){h.logger.warn(H());return}throw new Error(H());function H(){return`unknown format "${o}" ignored in schema at path "${d}"`}}function D(H){let Le=H instanceof RegExp?(0,ve.regexpCode)(H):l.code.formats?(0,ve._)`${l.code.formats}${(0,ve.getProperty)(o)}`:void 0,Be=n.scopeValue("formats",{key:o,ref:H,code:Le});return typeof H=="object"&&!(H instanceof RegExp)?[H.type||"string",H.validate,(0,ve._)`${Be}.validate`]:["string",H,Be]}function se(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!p.$async)throw new Error("async format in sync schema");return(0,ve._)`await ${P}(${r})`}return typeof R=="function"?(0,ve._)`${P}(${r})`:(0,ve._)`${P}.test(${r})`}}}};Ac.default=ZT});var Nm=L(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var YT=Om(),QT=[YT.default];Ic.default=QT});var jm=L(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.contentVocabulary=Wn.metadataVocabulary=void 0;Wn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Wn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var zm=L(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var XT=Kh(),eR=sm(),tR=Cm(),nR=Nm(),Lm=jm(),rR=[XT.default,eR.default,(0,tR.default)(),nR.default,Lm.metadataVocabulary,Lm.contentVocabulary];Cc.default=rR});var Um=L(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.DiscrError=void 0;var Dm;(function(t){t.Tag="tag",t.Mapping="mapping"})(Dm||(Go.DiscrError=Dm={}))});var Mm=L(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var Jn=X(),Oc=Um(),qm=Eo(),sR=Jr(),oR=le(),iR={message:({params:{discrError:t,tagName:e}})=>t===Oc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Jn._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},aR={keyword:"discriminator",type:"object",schemaType:"object",error:iR,code(t){let{gen:e,data:n,schema:r,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),d=e.const("tag",(0,Jn._)`${n}${(0,Jn.getProperty)(a)}`);e.if((0,Jn._)`typeof ${d} == "string"`,()=>p(),()=>t.error(!1,{discrError:Oc.DiscrError.Tag,tag:d,tagName:a})),t.ok(l);function p(){let y=_();e.if(!1);for(let w in y)e.elseIf((0,Jn._)`${d} === ${w}`),e.assign(l,h(y[w]));e.else(),t.error(!1,{discrError:Oc.DiscrError.Mapping,tag:d,tagName:a}),e.endIf()}function h(y){let w=e.name("valid"),T=t.subschema({keyword:"oneOf",schemaProp:y},w);return t.mergeEvaluated(T,Jn.Name),w}function _(){var y;let w={},T=P(s),R=!0;for(let se=0;se<i.length;se++){let H=i[se];if(H?.$ref&&!(0,oR.schemaHasRulesButRef)(H,o.self.RULES)){let Be=H.$ref;if(H=qm.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,Be),H instanceof qm.SchemaEnv&&(H=H.schema),H===void 0)throw new sR.default(o.opts.uriResolver,o.baseId,Be)}let Le=(y=H?.properties)===null||y===void 0?void 0:y[a];if(typeof Le!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);R=R&&(T||P(H)),I(Le,se)}if(!R)throw new Error(`discriminator: "${a}" must be required`);return w;function P({required:se}){return Array.isArray(se)&&se.includes(a)}function I(se,H){if(se.const)D(se.const,H);else if(se.enum)for(let Le of se.enum)D(Le,H);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(se,H){if(typeof se!="string"||se in w)throw new Error(`discriminator: "${a}" values must be unique strings`);w[se]=H}}}};Nc.default=aR});var Bm=L((wN,lR)=>{lR.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Lc=L((ye,jc)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var cR=Dh(),uR=zm(),dR=Mm(),Fm=Bm(),pR=["/properties"],Wo="http://json-schema.org/draft-07/schema",Zn=class extends cR.default{_addVocabularies(){super._addVocabularies(),uR.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(dR.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Fm,pR):Fm;this.addMetaSchema(e,Wo,!1),this.refs["http://json-schema.org/schema"]=Wo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wo)?Wo:void 0)}};ye.Ajv=Zn;jc.exports=ye=Zn;jc.exports.Ajv=Zn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Zn;var fR=Wr();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return fR.KeywordCxt}});var Yn=X();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Yn._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Yn.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Yn.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Yn.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Yn.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Yn.CodeGen}});var hR=To();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return hR.default}});var mR=Jr();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return mR.default}})});var Ym=L($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.formatNames=$t.fastFormats=$t.fullFormats=void 0;function _t(t,e){return{validate:t,compare:e}}$t.fullFormats={date:_t(Gm,qc),time:_t(Dc(!0),Mc),"date-time":_t(Km(!0),Jm),"iso-time":_t(Dc(),Wm),"iso-date-time":_t(Km(),Zm),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:kR,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ER,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:SR,int32:{type:"number",validate:xR},int64:{type:"number",validate:TR},float:{type:"number",validate:Vm},double:{type:"number",validate:Vm},password:!0,binary:!0};$t.fastFormats={...$t.fullFormats,date:_t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,qc),time:_t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Mc),"date-time":_t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Jm),"iso-time":_t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Wm),"iso-date-time":_t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Zm),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};$t.formatNames=Object.keys($t.fullFormats);function gR(t){return t%4===0&&(t%100!==0||t%400===0)}var bR=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,yR=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Gm(t){let e=bR.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],s=+e[3];return r>=1&&r<=12&&s>=1&&s<=(r===2&&gR(n)?29:yR[r])}function qc(t,e){if(t&&e)return t>e?1:t<e?-1:0}var zc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Dc(t){return function(n){let r=zc.exec(n);if(!r)return!1;let s=+r[1],o=+r[2],i=+r[3],a=r[4],l=r[5]==="-"?-1:1,d=+(r[6]||0),p=+(r[7]||0);if(d>23||p>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let h=o-p*l,_=s-d*l-(h<0?1:0);return(_===23||_===-1)&&(h===59||h===-1)&&i<61}}function Mc(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function Wm(t,e){if(!(t&&e))return;let n=zc.exec(t),r=zc.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var Uc=/t|\s/i;function Km(t){let e=Dc(t);return function(r){let s=r.split(Uc);return s.length===2&&Gm(s[0])&&e(s[1])}}function Jm(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function Zm(t,e){if(!(t&&e))return;let[n,r]=t.split(Uc),[s,o]=e.split(Uc),i=qc(n,s);if(i!==void 0)return i||Mc(r,o)}var wR=/\/|:/,vR=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function kR(t){return wR.test(t)&&vR.test(t)}var Hm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function SR(t){return Hm.lastIndex=0,Hm.test(t)}var _R=-(2**31),$R=2**31-1;function xR(t){return Number.isInteger(t)&&t<=$R&&t>=_R}function TR(t){return Number.isInteger(t)}function Vm(){return!0}var RR=/[^\\]\\Z/;function ER(t){if(RR.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Qm=L(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.formatLimitDefinition=void 0;var PR=Lc(),bt=X(),Qt=bt.operators,Jo={formatMaximum:{okStr:"<=",ok:Qt.LTE,fail:Qt.GT},formatMinimum:{okStr:">=",ok:Qt.GTE,fail:Qt.LT},formatExclusiveMaximum:{okStr:"<",ok:Qt.LT,fail:Qt.GTE},formatExclusiveMinimum:{okStr:">",ok:Qt.GT,fail:Qt.LTE}},AR={message:({keyword:t,schemaCode:e})=>(0,bt.str)`should be ${Jo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,bt._)`{comparison: ${Jo[t].okStr}, limit: ${e}}`};Qn.formatLimitDefinition={keyword:Object.keys(Jo),type:"string",schemaType:"string",$data:!0,error:AR,code(t){let{gen:e,data:n,schemaCode:r,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let l=new PR.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?d():p();function d(){let _=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),y=e.const("fmt",(0,bt._)`${_}[${l.schemaCode}]`);t.fail$data((0,bt.or)((0,bt._)`typeof ${y} != "object"`,(0,bt._)`${y} instanceof RegExp`,(0,bt._)`typeof ${y}.compare != "function"`,h(y)))}function p(){let _=l.schema,y=a.formats[_];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${s}": format "${_}" does not define "compare" function`);let w=e.scopeValue("formats",{key:_,ref:y,code:i.code.formats?(0,bt._)`${i.code.formats}${(0,bt.getProperty)(_)}`:void 0});t.fail$data(h(w))}function h(_){return(0,bt._)`${_}.compare(${n}, ${r}) ${Jo[s].fail} 0`}},dependencies:["format"]};var IR=t=>(t.addKeyword(Qn.formatLimitDefinition),t);Qn.default=IR});var ng=L((cs,tg)=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});var Xn=Ym(),CR=Qm(),Bc=X(),Xm=new Bc.Name("fullFormats"),OR=new Bc.Name("fastFormats"),Fc=(t,e={keywords:!0})=>{if(Array.isArray(e))return eg(t,e,Xn.fullFormats,Xm),t;let[n,r]=e.mode==="fast"?[Xn.fastFormats,OR]:[Xn.fullFormats,Xm],s=e.formats||Xn.formatNames;return eg(t,s,n,r),e.keywords&&(0,CR.default)(t),t};Fc.get=(t,e="full")=>{let r=(e==="fast"?Xn.fastFormats:Xn.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function eg(t,e,n,r){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Bc._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}tg.exports=cs=Fc;Object.defineProperty(cs,"__esModule",{value:!0});cs.default=Fc});function NR(){let t=new rg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,sg.default)(t),t}var rg,sg,Zo,og=j(()=>{rg=su(Lc(),1),sg=su(ng(),1);Zo=class{constructor(e){this._ajv=e??NR()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var Yo,ig=j(()=>{Ln();Yo=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],d=l.some(p=>p.type==="tool_use");if(i){if(o.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(l.filter(_=>_.type==="tool_use").map(_=>_.id)),h=new Set(o.filter(_=>_.type==="tool_result").map(_=>_.toolUseId));if(p.size!==h.size||![...p].every(_=>h.has(_)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Cr,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},jn,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function ag(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function lg(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var cg=j(()=>{});var Qo,ug=j(()=>{ff();Ln();og();Sr();ig();cg();Qo=class extends fo{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ir.options.map((r,s)=>[r,s])),this.isMessageIgnored=(r,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Zo,this.setRequestHandler(ra,r=>this._oninitialize(r)),this.setNotificationHandler(sa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(da,async(r,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Ir.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Yo(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=pf(this._capabilities,e)}setRequestHandler(e,n){let s=Mt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=An(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(l,d)=>{let p=qt(Nn,l);if(!p.success){let w=p.error instanceof Error?p.error.message:String(p.error);throw new U(B.InvalidParams,`Invalid tools/call request: ${w}`)}let{params:h}=p.data,_=await Promise.resolve(n(l,d));if(h.task){let w=qt(Cn,_);if(!w.success){let T=w.error instanceof Error?w.error.message:String(w.error);throw new U(B.InvalidParams,`Invalid task creation result: ${T}`)}return w.data}let y=qt(eo,_);if(!y.success){let w=y.error instanceof Error?y.error.message:String(y.error);throw new U(B.InvalidParams,`Invalid tools/call result: ${w}`)}return y.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){lg(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&ag(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:up.includes(n)?n:Qi,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ds)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],s=Array.isArray(r.content)?r.content:[r.content],o=s.some(d=>d.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(d=>d.type==="tool_use");if(o){if(s.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let d=new Set(a.filter(h=>h.type==="tool_use").map(h=>h.id)),p=new Set(s.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(d.size!==p.size||![...d].every(h=>p.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},pa,n):this.request({method:"sampling/createMessage",params:e},Cr,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},jn,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},jn,n);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new U(B.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof U?i:new U(B.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},fa,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function Kc(t){return!!t&&typeof t=="object"&&pg in t}function fg(t){return t[pg]?.complete}var pg,dg,hg=j(()=>{pg=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(dg||(dg={}))});var mg=j(()=>{});function LR(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!jR.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,s,o)=>o.indexOf(r)===s);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function zR(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Hc(t){let e=LR(t);return zR(t,e.warnings),e.isValid}var jR,gg=j(()=>{jR=/^[A-Za-z0-9._-]{1,128}$/});var Xo,bg=j(()=>{Xo=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let s={taskSupport:"required",...n.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,s,n._meta,r)}}});import{ZodOptional as DR}from"zod";function vg(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function kg(t){return"_def"in t||"_zod"in t||vg(t)}function Vc(t){return typeof t!="object"||t===null||kg(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(vg)}function yg(t){if(t){if(Vc(t))return sn(t);if(!kg(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function qR(t){let e=Mt(t);return e?Object.entries(e).map(([n,r])=>{let s=lp(r),o=cp(r);return{name:n,description:s,required:!o}}):[]}function Xt(t){let n=Mt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=An(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function wg(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ei,UR,us,Sg=j(()=>{ug();Sr();Za();Ln();hg();mg();gg();bg();ei=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Qo(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Xo(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Xt(Xs)),this.server.assertCanSetRequestHandler(Xt(Nn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Xs,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let s=Pn(n.inputSchema);return s?Ga(s,{strictUnions:!0,pipeStrategy:"input"}):UR})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let s=Pn(n.outputSchema);s&&(r.outputSchema=Ga(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Nn,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new U(B.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new U(B.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new U(B.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new U(B.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),l=await this.executeToolHandler(r,a,n);return s||await this.validateToolOutput(r,l,e.params.name),l}catch(r){if(r instanceof U&&r.code===B.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let o=Pn(e.inputSchema)??e.inputSchema,i=await Os(o,n);if(!i.success){let a="error"in i?i.error:"Unknown error",l=Ns(a);throw new U(B.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${l}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new U(B.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let s=Pn(e.outputSchema),o=await Os(s,n.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Ns(i);throw new U(B.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let s=e.handler;if("createTask"in s){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(n,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(n,r))}else{let i=s;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,n.params.arguments,n.params.name),o=e.handler,i={...r,taskStore:r.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),l=a.task.taskId,d=a.task,p=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(_=>setTimeout(_,p));let h=await r.taskStore.getTask(l);if(!h)throw new U(B.InternalError,`Task ${l} not found during polling`);d=h}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Xt(to)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(to,async e=>{switch(e.params.ref.type){case"ref/prompt":return Tp(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Rp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(B.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new U(B.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new U(B.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return us;let o=Mt(r.argsSchema)?.[e.params.argument.name];if(!Kc(o))return us;let i=fg(o);if(!i)return us;let a=await i(e.params.argument.value,e.params.context);return wg(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return us;throw new U(B.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return us;let o=await s(e.params.argument.value,e.params.context);return wg(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Xt(Ws)),this.server.assertCanSetRequestHandler(Xt(Js)),this.server.assertCanSetRequestHandler(Xt(Zs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ws,async(e,n)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(n);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...r,...s]}}),this.server.setRequestHandler(Js,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Zs,async(e,n)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new U(B.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,n)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,n)}throw new U(B.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Xt(Ys)),this.server.assertCanSetRequestHandler(Xt(Qs)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ys,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?qR(n.argsSchema):void 0}))})),this.server.setRequestHandler(Qs,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new U(B.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new U(B.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=Pn(r.argsSchema),o=await Os(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",d=Ns(l);throw new U(B.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${d}`)}let i=o.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let s=r.callback;return await Promise.resolve(s(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let s;typeof r[0]=="object"&&(s=r.shift());let o=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,n,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,s){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let o=this._createRegisteredResource(e,r.title,n,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,n,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,n,r,s,o){let i={name:e,title:n,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==r&&(delete this._registeredResources[r],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,n,r,s,o){let i={resourceTemplate:r,title:n,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(delete this._registeredResourceTemplates[e],d.name&&(this._registeredResourceTemplates[d.name]=i)),typeof d.title<"u"&&(i.title=d.title),typeof d.template<"u"&&(i.resourceTemplate=d.template),typeof d.metadata<"u"&&(i.metadata=d.metadata),typeof d.callback<"u"&&(i.readCallback=d.callback),typeof d.enabled<"u"&&(i.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(d=>!!r.completeCallback(d))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,s,o){let i={title:n,description:r,argsSchema:s===void 0?void 0:sn(s),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=sn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,s&&Object.values(s).some(l=>{let d=l instanceof DR?l._def?.innerType:l;return Kc(d)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,s,o,i,a,l,d){Hc(e);let p={title:n,description:r,inputSchema:yg(s),outputSchema:yg(o),annotations:i,execution:a,_meta:l,handler:d,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:h=>{typeof h.name<"u"&&h.name!==e&&(typeof h.name=="string"&&Hc(h.name),delete this._registeredTools[e],h.name&&(this._registeredTools[h.name]=p)),typeof h.title<"u"&&(p.title=h.title),typeof h.description<"u"&&(p.description=h.description),typeof h.paramsSchema<"u"&&(p.inputSchema=sn(h.paramsSchema)),typeof h.outputSchema<"u"&&(p.outputSchema=sn(h.outputSchema)),typeof h.callback<"u"&&(p.handler=h.callback),typeof h.annotations<"u"&&(p.annotations=h.annotations),typeof h._meta<"u"&&(p._meta=h._meta),typeof h.enabled<"u"&&(p.enabled=h.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,s,o,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let l=n[0];if(Vc(l))s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Vc(n[0])&&(i=n.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(d=>typeof d=="object"&&d!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:l,_meta:d}=n;return this._createRegisteredTool(e,s,o,i,a,l,{taskSupport:"forbidden"},d,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let s;n.length>1&&(s=n.shift());let o=n[0],i=this._createRegisteredPrompt(e,void 0,r,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=n,a=this._createRegisteredPrompt(e,s,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},UR={type:"object",properties:{}};us={completion:{values:[],hasMore:!1}}});function BR(t){return yp.parse(JSON.parse(t))}function _g(t){return JSON.stringify(t)+`
|
|
1093
|
-
`}var
|
|
1094
|
-
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
1237
|
+
deps: ${n}}`};var LR={keyword:"dependencies",type:"object",schemaType:"object",error:_t.error,code(t){let[e,n]=DR(t);Am(t,e),Im(t,n)}};function DR({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let s=Array.isArray(t[r])?e:n;s[r]=t[r]}return[e,n]}function Am(t,e=t.schema){let{gen:n,data:r,it:s}=t;if(Object.keys(e).length===0)return;let o=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,cs.propertyInData)(n,r,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?n.if(l,()=>{for(let p of a)(0,cs.checkReportMissingProp)(t,p)}):(n.if((0,$c._)`${l} && (${(0,cs.checkMissingProp)(t,a,o)})`),(0,cs.reportMissingProp)(t,o),n.else())}}_t.validatePropertyDeps=Am;function Im(t,e=t.schema){let{gen:n,data:r,keyword:s,it:o}=t,i=n.name("valid");for(let a in e)(0,jR.alwaysValidSchema)(o,e[a])||(n.if((0,cs.propertyInData)(n,r,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>n.var(i,!0)),t.ok(i))}_t.validateSchemaDeps=Im;_t.default=LR});var Nm=L(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Om=ee(),UR=le(),zR={message:"property name must be valid",params:({params:t})=>(0,Om._)`{propertyName: ${t.propertyName}}`},qR={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:zR,code(t){let{gen:e,schema:n,data:r,it:s}=t;if((0,UR.alwaysValidSchema)(s,n))return;let o=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,Om.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};xc.default=qR});var Tc=L(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var Go=lt(),bt=ee(),MR=Ct(),Wo=le(),BR={message:"must NOT have additional properties",params:({params:t})=>(0,bt._)`{additionalProperty: ${t.additionalProperty}}`},FR={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:BR,code(t){let{gen:e,schema:n,parentSchema:r,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Wo.alwaysValidSchema)(i,n))return;let p=(0,Go.allSchemaProperties)(r.properties),u=(0,Go.allSchemaProperties)(r.patternProperties);m(),t.ok((0,bt._)`${o} === ${MR.default.errors}`);function m(){e.forIn("key",s,E=>{!p.length&&!u.length?k(E):e.if(x(E),()=>k(E))})}function x(E){let P;if(p.length>8){let I=(0,Wo.schemaRefOrVal)(i,r.properties,"properties");P=(0,Go.isOwnProperty)(e,I,E)}else p.length?P=(0,bt.or)(...p.map(I=>(0,bt._)`${E} === ${I}`)):P=bt.nil;return u.length&&(P=(0,bt.or)(P,...u.map(I=>(0,bt._)`${(0,Go.usePattern)(t,I)}.test(${E})`))),(0,bt.not)(P)}function v(E){e.code((0,bt._)`delete ${s}[${E}]`)}function k(E){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){v(E);return}if(n===!1){t.setParams({additionalProperty:E}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Wo.alwaysValidSchema)(i,n)){let P=e.name("valid");l.removeAdditional==="failing"?(R(E,P,!1),e.if((0,bt.not)(P),()=>{t.reset(),v(E)})):(R(E,P),a||e.if((0,bt.not)(P),()=>e.break()))}}function R(E,P,I){let U={keyword:"additionalProperties",dataProp:E,dataPropType:Wo.Type.Str};I===!1&&Object.assign(U,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(U,P)}}};Rc.default=FR});var Dm=L(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var HR=Jr(),jm=lt(),Ec=le(),Lm=Tc(),KR={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t;o.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Lm.default.code(new HR.KeywordCxt(o,Lm.default,"additionalProperties"));let i=(0,jm.allSchemaProperties)(n);for(let m of i)o.definedProperties.add(m);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Ec.mergeEvaluated.props(e,(0,Ec.toHash)(i),o.props));let a=i.filter(m=>!(0,Ec.alwaysValidSchema)(o,n[m]));if(a.length===0)return;let l=e.name("valid");for(let m of a)p(m)?u(m):(e.if((0,jm.propertyInData)(e,s,m,o.opts.ownProperties)),u(m),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(m),t.ok(l);function p(m){return o.opts.useDefaults&&!o.compositeRule&&n[m].default!==void 0}function u(m){t.subschema({keyword:"properties",schemaProp:m,dataProp:m},l)}}};Pc.default=KR});var Mm=L(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var Um=lt(),Jo=ee(),zm=le(),qm=le(),VR={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,Um.allSchemaProperties)(n),l=a.filter(R=>(0,zm.alwaysValidSchema)(o,n[R]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let p=i.strictSchema&&!i.allowMatchingProperties&&s.properties,u=e.name("valid");o.props!==!0&&!(o.props instanceof Jo.Name)&&(o.props=(0,qm.evaluatedPropsToName)(e,o.props));let{props:m}=o;x();function x(){for(let R of a)p&&v(R),o.allErrors?k(R):(e.var(u,!0),k(R),e.if(u))}function v(R){for(let E in p)new RegExp(R).test(E)&&(0,zm.checkStrictMode)(o,`property ${E} matches pattern ${R} (use allowMatchingProperties)`)}function k(R){e.forIn("key",r,E=>{e.if((0,Jo._)`${(0,Um.usePattern)(t,R)}.test(${E})`,()=>{let P=l.includes(R);P||t.subschema({keyword:"patternProperties",schemaProp:R,dataProp:E,dataPropType:qm.Type.Str},u),o.opts.unevaluated&&m!==!0?e.assign((0,Jo._)`${m}[${E}]`,!0):!P&&!o.allErrors&&e.if((0,Jo.not)(u),()=>e.break())})})}}};Ac.default=VR});var Bm=L(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var GR=le(),WR={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,GR.alwaysValidSchema)(r,n)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Ic.default=WR});var Fm=L(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var JR=lt(),ZR={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:JR.validateUnion,error:{message:"must match a schema in anyOf"}};Cc.default=ZR});var Hm=L(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var Zo=ee(),YR=le(),QR={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Zo._)`{passingSchemas: ${t.passing}}`},XR={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:QR,code(t){let{gen:e,schema:n,parentSchema:r,it:s}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(s.opts.discriminator&&r.discriminator)return;let o=n,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(p),t.result(i,()=>t.reset(),()=>t.error(!0));function p(){o.forEach((u,m)=>{let x;(0,YR.alwaysValidSchema)(s,u)?e.var(l,!0):x=t.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},l),m>0&&e.if((0,Zo._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Zo._)`[${a}, ${m}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,m),x&&t.mergeEvaluated(x,Zo.Name)})})}}};Oc.default=XR});var Km=L(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var eT=le(),tT={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let s=e.name("valid");n.forEach((o,i)=>{if((0,eT.alwaysValidSchema)(r,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Nc.default=tT});var Wm=L(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var Yo=ee(),Gm=le(),nT={message:({params:t})=>(0,Yo.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Yo._)`{failingKeyword: ${t.ifClause}}`},rT={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:nT,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Gm.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let s=Vm(r,"then"),o=Vm(r,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),s&&o){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,p("then",u),p("else",u))}else s?e.if(a,p("then")):e.if((0,Yo.not)(a),p("else"));t.pass(i,()=>t.error(!0));function l(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function p(u,m){return()=>{let x=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(x,i),m?e.assign(m,(0,Yo._)`${u}`):t.setParams({ifClause:u})}}}};function Vm(t,e){let n=t.schema[e];return n!==void 0&&!(0,Gm.alwaysValidSchema)(t,n)}jc.default=rT});var Jm=L(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var sT=le(),oT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,sT.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Lc.default=oT});var Zm=L(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var iT=wc(),aT=Rm(),lT=vc(),cT=Em(),dT=Pm(),uT=Cm(),pT=Nm(),fT=Tc(),hT=Dm(),mT=Mm(),gT=Bm(),yT=Fm(),bT=Hm(),wT=Km(),vT=Wm(),kT=Jm();function ST(t=!1){let e=[gT.default,yT.default,bT.default,wT.default,vT.default,kT.default,pT.default,fT.default,uT.default,hT.default,mT.default];return t?e.push(aT.default,cT.default):e.push(iT.default,lT.default),e.push(dT.default),e}Dc.default=ST});var Ym=L(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var ke=ee(),_T={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},$T={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:_T,code(t,e){let{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:p,schemaEnv:u,self:m}=a;if(!l.validateFormats)return;s?x():v();function x(){let k=n.scopeValue("formats",{ref:m.formats,code:l.code.formats}),R=n.const("fDef",(0,ke._)`${k}[${i}]`),E=n.let("fType"),P=n.let("format");n.if((0,ke._)`typeof ${R} == "object" && !(${R} instanceof RegExp)`,()=>n.assign(E,(0,ke._)`${R}.type || "string"`).assign(P,(0,ke._)`${R}.validate`),()=>n.assign(E,(0,ke._)`"string"`).assign(P,R)),t.fail$data((0,ke.or)(I(),U()));function I(){return l.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${P}`}function U(){let se=u.$async?(0,ke._)`(${R}.async ? await ${P}(${r}) : ${P}(${r}))`:(0,ke._)`${P}(${r})`,V=(0,ke._)`(typeof ${P} == "function" ? ${se} : ${P}.test(${r}))`;return(0,ke._)`${P} && ${P} !== true && ${E} === ${e} && !${V}`}}function v(){let k=m.formats[o];if(!k){I();return}if(k===!0)return;let[R,E,P]=U(k);R===e&&t.pass(se());function I(){if(l.strictSchema===!1){m.logger.warn(V());return}throw new Error(V());function V(){return`unknown format "${o}" ignored in schema at path "${p}"`}}function U(V){let De=V instanceof RegExp?(0,ke.regexpCode)(V):l.code.formats?(0,ke._)`${l.code.formats}${(0,ke.getProperty)(o)}`:void 0,He=n.scopeValue("formats",{key:o,ref:V,code:De});return typeof V=="object"&&!(V instanceof RegExp)?[V.type||"string",V.validate,(0,ke._)`${He}.validate`]:["string",V,He]}function se(){if(typeof k=="object"&&!(k instanceof RegExp)&&k.async){if(!u.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${P}(${r})`}return typeof E=="function"?(0,ke._)`${P}(${r})`:(0,ke._)`${P}.test(${r})`}}}};Uc.default=$T});var Qm=L(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var xT=Ym(),RT=[xT.default];zc.default=RT});var Xm=L(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.contentVocabulary=Jn.metadataVocabulary=void 0;Jn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Jn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var tg=L(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var TT=lm(),ET=Sm(),PT=Zm(),AT=Qm(),eg=Xm(),IT=[TT.default,ET.default,(0,PT.default)(),AT.default,eg.metadataVocabulary,eg.contentVocabulary];qc.default=IT});var rg=L(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.DiscrError=void 0;var ng;(function(t){t.Tag="tag",t.Mapping="mapping"})(ng||(Qo.DiscrError=ng={}))});var og=L(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Zn=ee(),Mc=rg(),sg=Oo(),CT=Zr(),OT=le(),NT={message:({params:{discrError:t,tagName:e}})=>t===Mc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Zn._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},jT={keyword:"discriminator",type:"object",schemaType:"object",error:NT,code(t){let{gen:e,data:n,schema:r,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),p=e.const("tag",(0,Zn._)`${n}${(0,Zn.getProperty)(a)}`);e.if((0,Zn._)`typeof ${p} == "string"`,()=>u(),()=>t.error(!1,{discrError:Mc.DiscrError.Tag,tag:p,tagName:a})),t.ok(l);function u(){let v=x();e.if(!1);for(let k in v)e.elseIf((0,Zn._)`${p} === ${k}`),e.assign(l,m(v[k]));e.else(),t.error(!1,{discrError:Mc.DiscrError.Mapping,tag:p,tagName:a}),e.endIf()}function m(v){let k=e.name("valid"),R=t.subschema({keyword:"oneOf",schemaProp:v},k);return t.mergeEvaluated(R,Zn.Name),k}function x(){var v;let k={},R=P(s),E=!0;for(let se=0;se<i.length;se++){let V=i[se];if(V?.$ref&&!(0,OT.schemaHasRulesButRef)(V,o.self.RULES)){let He=V.$ref;if(V=sg.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,He),V instanceof sg.SchemaEnv&&(V=V.schema),V===void 0)throw new CT.default(o.opts.uriResolver,o.baseId,He)}let De=(v=V?.properties)===null||v===void 0?void 0:v[a];if(typeof De!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);E=E&&(R||P(V)),I(De,se)}if(!E)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:se}){return Array.isArray(se)&&se.includes(a)}function I(se,V){if(se.const)U(se.const,V);else if(se.enum)for(let De of se.enum)U(De,V);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function U(se,V){if(typeof se!="string"||se in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[se]=V}}}};Bc.default=jT});var ig=L((QN,LT)=>{LT.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Hc=L((be,Fc)=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.MissingRefError=be.ValidationError=be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=be.Ajv=void 0;var DT=nm(),UT=tg(),zT=og(),ag=ig(),qT=["/properties"],Xo="http://json-schema.org/draft-07/schema",Yn=class extends DT.default{_addVocabularies(){super._addVocabularies(),UT.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(zT.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ag,qT):ag;this.addMetaSchema(e,Xo,!1),this.refs["http://json-schema.org/schema"]=Xo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Xo)?Xo:void 0)}};be.Ajv=Yn;Fc.exports=be=Yn;Fc.exports.Ajv=Yn;Object.defineProperty(be,"__esModule",{value:!0});be.default=Yn;var MT=Jr();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return MT.KeywordCxt}});var Qn=ee();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return Qn._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return Qn.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return Qn.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return Qn.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return Qn.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return Qn.CodeGen}});var BT=Io();Object.defineProperty(be,"ValidationError",{enumerable:!0,get:function(){return BT.default}});var FT=Zr();Object.defineProperty(be,"MissingRefError",{enumerable:!0,get:function(){return FT.default}})});var mg=L(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.formatNames=xt.fastFormats=xt.fullFormats=void 0;function $t(t,e){return{validate:t,compare:e}}xt.fullFormats={date:$t(ug,Wc),time:$t(Vc(!0),Jc),"date-time":$t(lg(!0),fg),"iso-time":$t(Vc(),pg),"iso-date-time":$t(lg(),hg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:JT,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:nE,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:ZT,int32:{type:"number",validate:XT},int64:{type:"number",validate:eE},float:{type:"number",validate:dg},double:{type:"number",validate:dg},password:!0,binary:!0};xt.fastFormats={...xt.fullFormats,date:$t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Wc),time:$t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Jc),"date-time":$t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,fg),"iso-time":$t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,pg),"iso-date-time":$t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,hg),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};xt.formatNames=Object.keys(xt.fullFormats);function HT(t){return t%4===0&&(t%100!==0||t%400===0)}var KT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,VT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ug(t){let e=KT.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],s=+e[3];return r>=1&&r<=12&&s>=1&&s<=(r===2&&HT(n)?29:VT[r])}function Wc(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Kc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Vc(t){return function(n){let r=Kc.exec(n);if(!r)return!1;let s=+r[1],o=+r[2],i=+r[3],a=r[4],l=r[5]==="-"?-1:1,p=+(r[6]||0),u=+(r[7]||0);if(p>23||u>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let m=o-u*l,x=s-p*l-(m<0?1:0);return(x===23||x===-1)&&(m===59||m===-1)&&i<61}}function Jc(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function pg(t,e){if(!(t&&e))return;let n=Kc.exec(t),r=Kc.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var Gc=/t|\s/i;function lg(t){let e=Vc(t);return function(r){let s=r.split(Gc);return s.length===2&&ug(s[0])&&e(s[1])}}function fg(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function hg(t,e){if(!(t&&e))return;let[n,r]=t.split(Gc),[s,o]=e.split(Gc),i=Wc(n,s);if(i!==void 0)return i||Jc(r,o)}var GT=/\/|:/,WT=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function JT(t){return GT.test(t)&&WT.test(t)}var cg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function ZT(t){return cg.lastIndex=0,cg.test(t)}var YT=-(2**31),QT=2**31-1;function XT(t){return Number.isInteger(t)&&t<=QT&&t>=YT}function eE(t){return Number.isInteger(t)}function dg(){return!0}var tE=/[^\\]\\Z/;function nE(t){if(tE.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var gg=L(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.formatLimitDefinition=void 0;var rE=Hc(),wt=ee(),en=wt.operators,ei={formatMaximum:{okStr:"<=",ok:en.LTE,fail:en.GT},formatMinimum:{okStr:">=",ok:en.GTE,fail:en.LT},formatExclusiveMaximum:{okStr:"<",ok:en.LT,fail:en.GTE},formatExclusiveMinimum:{okStr:">",ok:en.GT,fail:en.LTE}},sE={message:({keyword:t,schemaCode:e})=>(0,wt.str)`should be ${ei[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wt._)`{comparison: ${ei[t].okStr}, limit: ${e}}`};Xn.formatLimitDefinition={keyword:Object.keys(ei),type:"string",schemaType:"string",$data:!0,error:sE,code(t){let{gen:e,data:n,schemaCode:r,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let l=new rE.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?p():u();function p(){let x=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),v=e.const("fmt",(0,wt._)`${x}[${l.schemaCode}]`);t.fail$data((0,wt.or)((0,wt._)`typeof ${v} != "object"`,(0,wt._)`${v} instanceof RegExp`,(0,wt._)`typeof ${v}.compare != "function"`,m(v)))}function u(){let x=l.schema,v=a.formats[x];if(!v||v===!0)return;if(typeof v!="object"||v instanceof RegExp||typeof v.compare!="function")throw new Error(`"${s}": format "${x}" does not define "compare" function`);let k=e.scopeValue("formats",{key:x,ref:v,code:i.code.formats?(0,wt._)`${i.code.formats}${(0,wt.getProperty)(x)}`:void 0});t.fail$data(m(k))}function m(x){return(0,wt._)`${x}.compare(${n}, ${r}) ${ei[s].fail} 0`}},dependencies:["format"]};var oE=t=>(t.addKeyword(Xn.formatLimitDefinition),t);Xn.default=oE});var vg=L((ds,wg)=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var er=mg(),iE=gg(),Zc=ee(),yg=new Zc.Name("fullFormats"),aE=new Zc.Name("fastFormats"),Yc=(t,e={keywords:!0})=>{if(Array.isArray(e))return bg(t,e,er.fullFormats,yg),t;let[n,r]=e.mode==="fast"?[er.fastFormats,aE]:[er.fullFormats,yg],s=e.formats||er.formatNames;return bg(t,s,n,r),e.keywords&&(0,iE.default)(t),t};Yc.get=(t,e="full")=>{let r=(e==="fast"?er.fastFormats:er.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function bg(t,e,n,r){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Zc._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}wg.exports=ds=Yc;Object.defineProperty(ds,"__esModule",{value:!0});ds.default=Yc});function lE(){let t=new kg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Sg.default)(t),t}var kg,Sg,ti,_g=j(()=>{kg=pd(Hc(),1),Sg=pd(vg(),1);ti=class{constructor(e){this._ajv=e??lE()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var ni,$g=j(()=>{Dn();ni=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],p=l.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!p)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(p){let u=new Set(l.filter(x=>x.type==="tool_use").map(x=>x.id)),m=new Set(o.filter(x=>x.type==="tool_result").map(x=>x.toolUseId));if(u.size!==m.size||![...u].every(x=>m.has(x)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Or,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Ln,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function xg(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Rg(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Tg=j(()=>{});var ri,Eg=j(()=>{If();Dn();_g();_r();$g();Tg();ri=class extends bo{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Cr.options.map((r,s)=>[r,s])),this.isMessageIgnored=(r,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new ti,this.setRequestHandler(ua,r=>this._oninitialize(r)),this.setNotificationHandler(pa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(wa,async(r,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Cr.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ni(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Af(this._capabilities,e)}setRequestHandler(e,n){let s=Ft(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=In(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(l,p)=>{let u=Bt(jn,l);if(!u.success){let k=u.error instanceof Error?u.error.message:String(u.error);throw new z(F.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:m}=u.data,x=await Promise.resolve(n(l,p));if(m.task){let k=Bt(On,x);if(!k.success){let R=k.error instanceof Error?k.error.message:String(k.error);throw new z(F.InvalidParams,`Invalid task creation result: ${R}`)}return k.data}let v=Bt(oo,x);if(!v.success){let k=v.error instanceof Error?v.error.message:String(v.error);throw new z(F.InvalidParams,`Invalid tools/call result: ${k}`)}return v.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Rg(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&xg(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ep.includes(n)?n:ia,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Fs)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],s=Array.isArray(r.content)?r.content:[r.content],o=s.some(p=>p.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(p=>p.type==="tool_use");if(o){if(s.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let p=new Set(a.filter(m=>m.type==="tool_use").map(m=>m.id)),u=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(p.size!==u.size||![...p].every(m=>u.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},va,n):this.request({method:"sampling/createMessage",params:e},Or,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},Ln,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},Ln,n);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new z(F.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(F.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},ka,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function Qc(t){return!!t&&typeof t=="object"&&Ag in t}function Ig(t){return t[Ag]?.complete}var Ag,Pg,Cg=j(()=>{Ag=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Pg||(Pg={}))});var Og=j(()=>{});function dE(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!cE.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,s,o)=>o.indexOf(r)===s);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function uE(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Xc(t){let e=dE(t);return uE(t,e.warnings),e.isValid}var cE,Ng=j(()=>{cE=/^[A-Za-z0-9._-]{1,128}$/});var si,jg=j(()=>{si=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let s={taskSupport:"required",...n.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,s,n._meta,r)}}});import{ZodOptional as pE}from"zod";function Ug(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function zg(t){return"_def"in t||"_zod"in t||Ug(t)}function ed(t){return typeof t!="object"||t===null||zg(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Ug)}function Lg(t){if(t){if(ed(t))return an(t);if(!zg(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function hE(t){let e=Ft(t);return e?Object.entries(e).map(([n,r])=>{let s=Rp(r),o=Tp(r);return{name:n,description:s,required:!o}}):[]}function tn(t){let n=Ft(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=In(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function Dg(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var oi,fE,us,qg=j(()=>{Eg();_r();sl();Dn();Cg();Og();Ng();jg();oi=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ri(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new si(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(tn(so)),this.server.assertCanSetRequestHandler(tn(jn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(so,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let s=An(n.inputSchema);return s?tl(s,{strictUnions:!0,pipeStrategy:"input"}):fE})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let s=An(n.outputSchema);s&&(r.outputSchema=tl(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(jn,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new z(F.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new z(F.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new z(F.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new z(F.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),l=await this.executeToolHandler(r,a,n);return s||await this.validateToolOutput(r,l,e.params.name),l}catch(r){if(r instanceof z&&r.code===F.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let o=An(e.inputSchema)??e.inputSchema,i=await Us(o,n);if(!i.success){let a="error"in i?i.error:"Unknown error",l=zs(a);throw new z(F.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${l}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new z(F.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let s=An(e.outputSchema),o=await Us(s,n.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=zs(i);throw new z(F.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let s=e.handler;if("createTask"in s){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(n,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(n,r))}else{let i=s;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,n.params.arguments,n.params.name),o=e.handler,i={...r,taskStore:r.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),l=a.task.taskId,p=a.task,u=p.pollInterval??5e3;for(;p.status!=="completed"&&p.status!=="failed"&&p.status!=="cancelled";){await new Promise(x=>setTimeout(x,u));let m=await r.taskStore.getTask(l);if(!m)throw new z(F.InternalError,`Task ${l} not found during polling`);p=m}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(tn(io)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(io,async e=>{switch(e.params.ref.type){case"ref/prompt":return Hp(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Kp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(F.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new z(F.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new z(F.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return us;let o=Ft(r.argsSchema)?.[e.params.argument.name];if(!Qc(o))return us;let i=Ig(o);if(!i)return us;let a=await i(e.params.argument.value,e.params.context);return Dg(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return us;throw new z(F.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return us;let o=await s(e.params.argument.value,e.params.context);return Dg(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(tn(Xs)),this.server.assertCanSetRequestHandler(tn(eo)),this.server.assertCanSetRequestHandler(tn(to)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Xs,async(e,n)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(n);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...r,...s]}}),this.server.setRequestHandler(eo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(to,async(e,n)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new z(F.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,n)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,n)}throw new z(F.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(tn(no)),this.server.assertCanSetRequestHandler(tn(ro)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(no,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?hE(n.argsSchema):void 0}))})),this.server.setRequestHandler(ro,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new z(F.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new z(F.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=An(r.argsSchema),o=await Us(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",p=zs(l);throw new z(F.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${p}`)}let i=o.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let s=r.callback;return await Promise.resolve(s(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let s;typeof r[0]=="object"&&(s=r.shift());let o=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,n,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,s){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let o=this._createRegisteredResource(e,r.title,n,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,n,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,n,r,s,o){let i={name:e,title:n,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==r&&(delete this._registeredResources[r],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,n,r,s,o){let i={resourceTemplate:r,title:n,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(delete this._registeredResourceTemplates[e],p.name&&(this._registeredResourceTemplates[p.name]=i)),typeof p.title<"u"&&(i.title=p.title),typeof p.template<"u"&&(i.resourceTemplate=p.template),typeof p.metadata<"u"&&(i.metadata=p.metadata),typeof p.callback<"u"&&(i.readCallback=p.callback),typeof p.enabled<"u"&&(i.enabled=p.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(p=>!!r.completeCallback(p))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,s,o){let i={title:n,description:r,argsSchema:s===void 0?void 0:an(s),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=an(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,s&&Object.values(s).some(l=>{let p=l instanceof pE?l._def?.innerType:l;return Qc(p)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,s,o,i,a,l,p){Xc(e);let u={title:n,description:r,inputSchema:Lg(s),outputSchema:Lg(o),annotations:i,execution:a,_meta:l,handler:p,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:m=>{typeof m.name<"u"&&m.name!==e&&(typeof m.name=="string"&&Xc(m.name),delete this._registeredTools[e],m.name&&(this._registeredTools[m.name]=u)),typeof m.title<"u"&&(u.title=m.title),typeof m.description<"u"&&(u.description=m.description),typeof m.paramsSchema<"u"&&(u.inputSchema=an(m.paramsSchema)),typeof m.outputSchema<"u"&&(u.outputSchema=an(m.outputSchema)),typeof m.callback<"u"&&(u.handler=m.callback),typeof m.annotations<"u"&&(u.annotations=m.annotations),typeof m._meta<"u"&&(u._meta=m._meta),typeof m.enabled<"u"&&(u.enabled=m.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,s,o,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let l=n[0];if(ed(l))s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!ed(n[0])&&(i=n.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(p=>typeof p=="object"&&p!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:l,_meta:p}=n;return this._createRegisteredTool(e,s,o,i,a,l,{taskSupport:"forbidden"},p,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let s;n.length>1&&(s=n.shift());let o=n[0],i=this._createRegisteredPrompt(e,void 0,r,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=n,a=this._createRegisteredPrompt(e,s,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},fE={type:"object",properties:{}};us={completion:{values:[],hasMore:!1}}});function gE(t){return Lp.parse(JSON.parse(t))}function Mg(t){return JSON.stringify(t)+`
|
|
1238
|
+
`}var mE,ii,Bg=j(()=>{Dn();mE=10*1024*1024,ii=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??mE}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
1239
|
+
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),gE(n)}clear(){this._buffer=void 0}}});import Fg from"node:process";var ai,Hg=j(()=>{Bg();ai=class{constructor(e=Fg.stdin,n=Fg.stdout,r){this._stdin=e,this._stdout=n,this._started=!1,this._ondata=s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=s=>{this.onerror?.(s)},this._readBuffer=new ii({maxBufferSize:r?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let r=Mg(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var Kg,Vg=j(()=>{Kg=[]});var ty={};ud(ty,{AUTHORING_MCP_SERVER_NAME:()=>Yg,AUTHORING_MCP_SERVER_VERSION:()=>Qg,AUTHORING_RESOURCES:()=>vE,AUTHORING_TOOLS:()=>wE,AUTHORING_TOOLS_PUBLIC:()=>ey,buildAuthoringMcpServer:()=>Xg,runAuthoringMcpServer:()=>kE});import{promises as yE}from"node:fs";import{resolve as Gg}from"node:path";import{z as M}from"zod";function Zg(){return Jg??=import("../mcp/grounding.js").then(e=>e,()=>null),Jg}function Se(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function bE(t,e={}){let n=e.fetchImpl??fetch;try{let r=await n(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return r.ok?((await r.json()).extensions??[]).map(o=>o.hookId).filter(o=>typeof o=="string"):null}catch{return null}}async function Xg(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let v=await ut(t.baseUrl);if(!v)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:v.baseUrl,token:v.token}}let n=t.grounding??{},r=await Zg(),s=null;if(r)try{let v=await e();s={surface:"mcp-authoring",baseUrl:v.baseUrl,token:v.token}}catch{s=null}let o=r&&s?await r.loadActiveSources(s,n):[],i={...n,loadActiveSourcesImpl:async()=>o},a=[],l=[];if(r&&s){try{a=await r.listMcpPromptSkills(s,i)}catch{a=[]}try{l=(await r.listRecipesForSurface(s,i)).map(v=>({id:v.id,record_type:v.record_type,intent:v.intent}))}catch{l=[]}}let p=s?await bE(s,n):null,u=new oi({name:Yg,version:Qg},r?{instructions:r.renderAuthoringInstructions({baseUrl:s?.baseUrl??t.baseUrl??"this instance",sources:o,recipeIntents:l,promptNames:a.map(v=>v.id),deployedExtensions:p,docsToken:n.docsToken??r.docsPublicToken()})}:void 0);if(r&&s){let v=s;for(let k of a)u.registerPrompt(k.id,{title:k.name,description:k.description},async()=>{let R=await r.getMcpPromptSkill(v,k.id,n);if(!R)throw new Error(`unknown prompt: ${k.id}`);return{description:R.description,messages:[{role:"user",content:{type:"text",text:(R.prompts??[]).join(`
|
|
1095
1240
|
|
|
1096
|
-
`)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:y,token:w}=await e(),T=await fetch(`${y}/v1/catalog/records`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog fetch failed: ${T.status}`);return ke(await T.json())}),p.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:M.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:M.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:y,source:w})=>{let{baseUrl:T,token:R}=await e(),P=w?`?source=${encodeURIComponent(w)}`:"",I=await fetch(`${T}/v1/catalog/records/${encodeURIComponent(y)}${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${y}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return ke(await I.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:M.array(M.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:M.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:y,source:w})=>{let{baseUrl:T,token:R}=await e(),P=new URLSearchParams({types:y.join(",")});w&&P.set("source",w);let I=await fetch(`${T}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${y.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return ke(await I.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:y,token:w}=await e(),T=await fetch(`${y}/v1/catalog/census`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog census failed: ${T.status}`);return ke(await T.json())}),p.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:M.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:M.enum(Ag).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:M.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:y,kind:w,limit:T})=>{let{baseUrl:R,token:P}=await e(),I=new URLSearchParams({q:y});w&&I.set("kind",w),T!==void 0&&I.set("limit",String(T));let D=await fetch(`${R}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return ke(await D.json())}),p.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:M.enum(Ag),externalId:M.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:y,externalId:w})=>{let{baseUrl:T,token:R}=await e(),P=await fetch(`${T}/v1/catalog/objects/${encodeURIComponent(y)}/${encodeURIComponent(w)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${y}:${w} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return ke(await P.json())}),p.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:M.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:M.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:y,limit:w})=>{let{baseUrl:T,token:R}=await e(),P=new URLSearchParams({q:y});w!==void 0&&P.set("limit",String(w));let I=await fetch(`${T}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return ke(await I.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:M.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:y})=>{let{baseUrl:w,token:T}=await e(),R=await fetch(`${w}/v1/kb/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!R.ok&&R.status!==404)throw new Error(`kb document fetch failed: ${R.status}`);return ke(await R.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:M.boolean().optional()}},async({recordsOnly:y})=>{let{baseUrl:w,token:T}=await e();return{content:[{type:"text",text:await Nt({baseUrl:w,token:T,recordsOnly:y})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:M.string(),event:M.string().optional(),template:M.enum(["require-field","enforce-format","blank"]).optional(),field:M.string().optional(),regex:M.string().optional(),source:M.string().optional(),id:M.string().optional()}},async y=>{let w=_n("hook",{recordType:y.recordType,event:y.event,template:y.template,field:y.field,regex:y.regex,source:y.source,id:y.id});return ke({path:w.relativePath,content:w.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:M.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:M.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:M.string().optional().describe("Target record type (defaults to the trigger record type)."),event:M.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:M.string().optional()}},async y=>{let w=_n("conduit",{recordType:y.recordType,source:y.source,to:y.to,toRecordType:y.toRecordType,event:y.event,id:y.id});return ke({path:w.relativePath,content:w.content})}),p.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:M.string().describe("The extension TS source."),samplesDir:M.string().optional().describe('Samples directory (default "samples").')}},async({source:y,samplesDir:w})=>{let T=Pg(process.cwd(),w??"samples"),R=await dr(T),P=await _s(y,R.map(D=>D.fixture)),I=P.filter(D=>!D.pass).length;return ke({total:P.length,passed:P.length-I,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:M.string(),recordType:M.string(),event:M.string(),source:M.string().describe('Adapter id or "standalone".'),sourceCode:M.string().describe("The verbatim extension TS."),extensionKind:M.string().optional()}},async y=>{let{baseUrl:w,token:T}=await e(),P=await new F({baseUrl:w,token:T}).deploy({id:y.id,recordType:y.recordType,event:y.event,source:y.source,sourceCode:y.sourceCode,extensionKind:y.extensionKind});return ke(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:M.string(),limit:M.number().int().positive().optional()}},async({id:y,limit:w})=>{let{baseUrl:T,token:R}=await e(),P=new F({baseUrl:T,token:R});return ke({id:y,logs:await P.logs(y,w)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:y,token:w}=await e(),T=new F({baseUrl:y,token:w});return ke(await T.appsList())}),p.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:M.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:M.string().optional().describe("Display name (defaults to the slug)."),description:M.string().optional().describe("Short description.")}},async({slug:y,name:w,description:T})=>{let{baseUrl:R,token:P}=await e(),I=new F({baseUrl:R,token:P});return ke(await I.appsCreate({slug:y,name:w,description:T}))}),p.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:M.string().describe("App slug or id.")}},async({app:y})=>{let{baseUrl:w,token:T}=await e(),R=new F({baseUrl:w,token:T});return ke(await R.appsPull(y))}),p.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:M.string().describe("App slug or id."),files:M.record(M.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:M.string().optional().describe("Short note stored with the revision.")}},async({app:y,files:w,note:T})=>{let{baseUrl:R,token:P}=await e(),I=new F({baseUrl:R,token:P});return ke(await I.appsPush(y,w,{note:T}))});let h=M.object({name:M.string().describe("Field name (lowercase identifier)."),type:M.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:M.boolean().optional()}),_=M.object({slug:M.string().describe("Table slug; the physical table is cr_<slug>."),displayName:M.string().optional(),fields:M.array(h).describe("At least one field."),rowLevelOwner:M.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:y,token:w}=await e(),T=new F({baseUrl:y,token:w});return ke(await T.tablesList())}),p.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:w})=>{let{baseUrl:T,token:R}=await e(),P=new F({baseUrl:T,token:R});return ke(await P.tablesPlan({tables:y,claimedBy:w}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:w})=>{let{baseUrl:T,token:R}=await e(),P=new F({baseUrl:T,token:R});return ke(await P.tablesApply({tables:y,claimedBy:w}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async y=>{let{baseUrl:w,token:T}=await e(),P=await(await fetch(`${w}/v1/catalog/records`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}})).text();return{contents:[{uri:y.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async y=>{let{baseUrl:w,token:T}=await e(),R=await Nt({baseUrl:w,token:T});return{contents:[{uri:y.href,mimeType:"text/plain",text:R}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async y=>{let w=Pg(process.cwd(),"samples"),T=[];try{T=(await FR.readdir(w)).filter(P=>P.endsWith(".json"))}catch{T=[]}let R=await dr(w);return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({files:T,samples:R.map(P=>P.fixture)},null,2)}]}}),p.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async y=>{let w=await Cg(),T=[];if(w){let{baseUrl:R,token:P}=await e();T=await w.listRecipesForSurface({surface:"mcp-authoring",baseUrl:R,token:P},n)}return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({recipes:T})}]}}),p}async function GR(t={}){let e=await jg(t),n=new ni;await e.connect(n)}var Ag,Ig,Og,Ng,Lg,HR,VR,Dg=j(()=>{Sg();Tg();yi();lr();jt();Ri();Ni();Eg();Ag=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Og="turbobase-authoring",Ng="0.1.0";Lg=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],HR=[...Lg,...Rg],VR=["catalog:///","types://all","samples:///","recipes:///"]});yi();lr();jt();Ri();import{spawn as Qc}from"node:child_process";import{promises as re}from"node:fs";import{homedir as WR}from"node:os";import{basename as qg,dirname as er,join as Ye,relative as ri,resolve as ue,sep as Yc}from"node:path";import{Command as JR}from"commander";xi();import{promises as Ru}from"node:fs";function xu(t,e){return e===t?"same-type-merge":"different-type-mint"}var Eu=4;function Ei(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=vn(t,"id"),n=vn(t,"on"),r=vn(t,"source"),s=vn(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=vn(o,"source"),a=vn(o,"recordType"),l=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!r||!s||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:n,fromSource:r,fromRecordType:s,toSource:i,toRecordType:a,cycleBudget:l?Number(l[1]):Eu}}function vn(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function kb(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function Pu(t,e,n="fixture"){let r=e.name??n,s=[],o;try{o=Ei(t)}catch(l){return{fixtureName:r,conduit:_b(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=kb(e),a=Object.entries(e.atlasLinks??{}).map(([l,d])=>({key:l,resolved:d}));try{let l=await Ss(t),p=!!(await ur(l,i,{member:"when",timeoutMs:200})).whenResult;s.push({name:"from.when",status:p?"passed":"failed",detail:p?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let h=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${h} vs cycleBudget=${o.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!p)return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let _=await ur(l,i,{member:"transform",timeoutMs:200}),y=_.effects.logs,w=_.effects.result;if(!w||typeof w!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let T=w,R=xu(o.fromRecordType,o.toRecordType),{wouldWriteBindings:P,masterAction:I}=Sb(o,R,e);return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,transformResult:T,applyBranch:R,wouldWriteBindings:P,masterAction:I,logs:y}}catch(l){return{fixtureName:r,conduit:o,guards:s,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function Sb(t,e,n){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:n.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function _b(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Eu}}async function Au(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function Iu(t){let e=await Ru.readFile(t,"utf8");return JSON.parse(e)}function Cu(t){return Ru.readFile(t,"utf8")}function Ou(t,e){let n=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${n.id}]: WHEN-FAILED (conduit short-circuited)`;let r=[];r.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),r.push(`conduit: ${n.id}`),r.push(`route: ${n.fromSource}.${n.fromRecordType} \u2192 ${n.toSource}.${n.toRecordType}${n.on?` on=${n.on}`:""}`),r.push(""),r.push("guards (dispatch order):");for(let s of t.guards){let o=s.status==="passed"?"\u2713":s.status==="failed"?"\u2717":"\u2298";r.push(` ${o} ${s.name} [${s.status}] \u2014 ${s.detail}`)}if(r.push(""),r.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)r.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let s of t.atlasResolutions)r.push(` ${s.key} \u2192 ${s.resolved===null?"null (no Atlas link \u2014 noted)":s.resolved}`);if(!t.whenPassed)return r.push(""),r.push("transform: SKIPPED (from.when gate did not fire)."),r.join(`
|
|
1097
|
-
`);if(r.push(""),r.push("transform \u2192 patch:"),r.push(
|
|
1098
|
-
`)}function
|
|
1241
|
+
`)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:v,token:k}=await e(),R=await fetch(`${v}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return Se(await R.json())}),u.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:M.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:M.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:v,source:k})=>{let{baseUrl:R,token:E}=await e(),P=k?`?source=${encodeURIComponent(k)}`:"",I=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(v)}${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${v}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return Se(await I.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:M.array(M.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:M.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:v,source:k})=>{let{baseUrl:R,token:E}=await e(),P=new URLSearchParams({types:v.join(",")});k&&P.set("source",k);let I=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${v.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return Se(await I.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:v,token:k}=await e(),R=await fetch(`${v}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return Se(await R.json())}),u.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:M.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:M.enum(Wg).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:M.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:v,kind:k,limit:R})=>{let{baseUrl:E,token:P}=await e(),I=new URLSearchParams({q:v});k&&I.set("kind",k),R!==void 0&&I.set("limit",String(R));let U=await fetch(`${E}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!U.ok)throw new Error(`catalog object search failed: ${U.status}`);return Se(await U.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:M.enum(Wg),externalId:M.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:v,externalId:k})=>{let{baseUrl:R,token:E}=await e(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(v)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${v}:${k} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return Se(await P.json())}),u.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:M.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:M.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:v,limit:k})=>{let{baseUrl:R,token:E}=await e(),P=new URLSearchParams({q:v});k!==void 0&&P.set("limit",String(k));let I=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return Se(await I.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:M.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:v})=>{let{baseUrl:k,token:R}=await e(),E=await fetch(`${k}/v1/kb/document/${encodeURIComponent(v)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!E.ok&&E.status!==404)throw new Error(`kb document fetch failed: ${E.status}`);return Se(await E.json())}),u.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:M.boolean().optional()}},async({recordsOnly:v})=>{let{baseUrl:k,token:R}=await e();return{content:[{type:"text",text:await Dt({baseUrl:k,token:R,recordsOnly:v})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:M.string(),event:M.string().optional(),template:M.enum(["require-field","enforce-format","blank"]).optional(),field:M.string().optional(),regex:M.string().optional(),source:M.string().optional(),id:M.string().optional()}},async v=>{let k=Mt("hook",{recordType:v.recordType,event:v.event,template:v.template,field:v.field,regex:v.regex,source:v.source,id:v.id});return Se({path:k.relativePath,content:k.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:M.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:M.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:M.string().optional().describe("Target record type (defaults to the trigger record type)."),event:M.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:M.string().optional()}},async v=>{let k=Mt("conduit",{recordType:v.recordType,source:v.source,to:v.to,toRecordType:v.toRecordType,event:v.event,id:v.id});return Se({path:k.relativePath,content:k.content})}),u.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:M.string().describe("The extension TS source."),samplesDir:M.string().optional().describe('Samples directory (default "samples").')}},async({source:v,samplesDir:k})=>{let R=Gg(process.cwd(),k??"samples"),E=await pr(R),P=await xs(v,E.map(U=>U.fixture)),I=P.filter(U=>!U.pass).length;return Se({total:P.length,passed:P.length-I,results:P})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:M.string(),recordType:M.string(),event:M.string(),source:M.string().describe('Adapter id or "standalone".'),sourceCode:M.string().describe("The verbatim extension TS."),extensionKind:M.string().optional()}},async v=>{let{baseUrl:k,token:R}=await e(),P=await new B({baseUrl:k,token:R}).deploy({id:v.id,recordType:v.recordType,event:v.event,source:v.source,sourceCode:v.sourceCode,extensionKind:v.extensionKind});return Se(P)}),u.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:M.string(),limit:M.number().int().positive().optional()}},async({id:v,limit:k})=>{let{baseUrl:R,token:E}=await e(),P=new B({baseUrl:R,token:E});return Se({id:v,logs:await P.logs(v,k)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:v,token:k}=await e(),R=new B({baseUrl:v,token:k});return Se(await R.appsList())}),u.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:M.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:M.string().optional().describe("Display name (defaults to the slug)."),description:M.string().optional().describe("Short description.")}},async({slug:v,name:k,description:R})=>{let{baseUrl:E,token:P}=await e(),I=new B({baseUrl:E,token:P});return Se(await I.appsCreate({slug:v,name:k,description:R}))}),u.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:M.string().describe("App slug or id.")}},async({app:v})=>{let{baseUrl:k,token:R}=await e(),E=new B({baseUrl:k,token:R});return Se(await E.appsPull(v))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:M.string().describe("App slug or id."),files:M.record(M.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:M.string().optional().describe("Short note stored with the revision.")}},async({app:v,files:k,note:R})=>{let{baseUrl:E,token:P}=await e(),I=new B({baseUrl:E,token:P});return Se(await I.appsPush(v,k,{note:R}))});let m=M.object({name:M.string().describe("Field name (lowercase identifier)."),type:M.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:M.boolean().optional()}),x=M.object({slug:M.string().describe("Table slug; the physical table is cr_<slug>."),displayName:M.string().optional(),fields:M.array(m).describe("At least one field."),rowLevelOwner:M.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:v,token:k}=await e(),R=new B({baseUrl:v,token:k});return Se(await R.tablesList())}),u.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:M.array(x),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:k})=>{let{baseUrl:R,token:E}=await e(),P=new B({baseUrl:R,token:E});return Se(await P.tablesPlan({tables:v,claimedBy:k}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:M.array(x),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:k})=>{let{baseUrl:R,token:E}=await e(),P=new B({baseUrl:R,token:E});return Se(await P.tablesApply({tables:v,claimedBy:k}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async v=>{let{baseUrl:k,token:R}=await e(),P=await(await fetch(`${k}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}})).text();return{contents:[{uri:v.href,mimeType:"application/json",text:P}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async v=>{let{baseUrl:k,token:R}=await e(),E=await Dt({baseUrl:k,token:R});return{contents:[{uri:v.href,mimeType:"text/plain",text:E}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async v=>{let k=Gg(process.cwd(),"samples"),R=[];try{R=(await yE.readdir(k)).filter(P=>P.endsWith(".json"))}catch{R=[]}let E=await pr(k);return{contents:[{uri:v.href,mimeType:"application/json",text:JSON.stringify({files:R,samples:E.map(P=>P.fixture)},null,2)}]}}),u.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async v=>{let k=await Zg(),R=[];if(k){let{baseUrl:E,token:P}=await e();R=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:E,token:P},n)}return{contents:[{uri:v.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),u}async function kE(t={}){let e=await Xg(t),n=new ai;await e.connect(n)}var Wg,Jg,Yg,Qg,ey,wE,vE,ny=j(()=>{qg();Hg();xi();cr();Tt();Ni();Ps();Vg();Wg=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Yg="turbobase-authoring",Qg="0.1.0";ey=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],wE=[...ey,...Kg],vE=["catalog:///","types://all","samples:///","recipes:///"]});xi();cr();Tt();Ni();import{spawn as id}from"node:child_process";import{promises as re}from"node:fs";import{homedir as SE}from"node:os";import{basename as sy,dirname as tr,join as Qe,relative as ci,resolve as de,sep as od}from"node:path";import{Command as _E}from"commander";Ci();import{promises as jd}from"node:fs";function Od(t,e){return e===t?"same-type-merge":"different-type-mint"}var Ld=4;function ji(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=kn(t,"id"),n=kn(t,"on"),r=kn(t,"source"),s=kn(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=kn(o,"source"),a=kn(o,"recordType"),l=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!r||!s||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:n,fromSource:r,fromRecordType:s,toSource:i,toRecordType:a,cycleBudget:l?Number(l[1]):Ld}}function kn(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function zy(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function Dd(t,e,n="fixture"){let r=e.name??n,s=[],o;try{o=ji(t)}catch(l){return{fixtureName:r,conduit:My(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=zy(e),a=Object.entries(e.atlasLinks??{}).map(([l,p])=>({key:l,resolved:p}));try{let l=await $s(t),u=!!(await ur(l,i,{member:"when",timeoutMs:200})).whenResult;s.push({name:"from.when",status:u?"passed":"failed",detail:u?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let m=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${m} vs cycleBudget=${o.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!u)return{fixtureName:r,conduit:o,guards:s,whenPassed:u,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let x=await ur(l,i,{member:"transform",timeoutMs:200}),v=x.effects.logs,k=x.effects.result;if(!k||typeof k!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let R=k,E=Od(o.fromRecordType,o.toRecordType),{wouldWriteBindings:P,masterAction:I}=qy(o,E,e);return{fixtureName:r,conduit:o,guards:s,whenPassed:u,atlasResolutions:a,transformResult:R,applyBranch:E,wouldWriteBindings:P,masterAction:I,logs:v}}catch(l){return{fixtureName:r,conduit:o,guards:s,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function qy(t,e,n){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:n.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function My(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Ld}}async function Ud(t){return Promise.reject(new Error("`replay --against sandbox` requires a running sandbox (TURBOBASE_SANDBOX=1 + a local DB). No local Postgres / k3d in this environment \u2014 deferred to a DB-backed run. Use `replay --fixture <file>` for the offline transform/apply-branch dry-run."))}async function zd(t){let e=await jd.readFile(t,"utf8");return JSON.parse(e)}function qd(t){return jd.readFile(t,"utf8")}function Md(t,e){let n=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${n.id}]: WHEN-FAILED (conduit short-circuited)`;let r=[];r.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),r.push(`conduit: ${n.id}`),r.push(`route: ${n.fromSource}.${n.fromRecordType} \u2192 ${n.toSource}.${n.toRecordType}${n.on?` on=${n.on}`:""}`),r.push(""),r.push("guards (dispatch order):");for(let s of t.guards){let o=s.status==="passed"?"\u2713":s.status==="failed"?"\u2717":"\u2298";r.push(` ${o} ${s.name} [${s.status}] \u2014 ${s.detail}`)}if(r.push(""),r.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)r.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let s of t.atlasResolutions)r.push(` ${s.key} \u2192 ${s.resolved===null?"null (no Atlas link \u2014 noted)":s.resolved}`);if(!t.whenPassed)return r.push(""),r.push("transform: SKIPPED (from.when gate did not fire)."),r.join(`
|
|
1242
|
+
`);if(r.push(""),r.push("transform \u2192 patch:"),r.push(By(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&r.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){r.push(""),r.push("conduit logs:");for(let s of t.logs)r.push(` [${s.level}] ${s.message}${s.meta?` ${JSON.stringify(s.meta)}`:""}`)}r.push(""),r.push(`apply-branch: ${t.applyBranch}`),r.push(` ${t.masterAction}`),r.push(""),r.push("bindings that WOULD be written (txn_source_link):");for(let s of t.wouldWriteBindings)r.push(` ${s.source} role=${s.role} external_id=${s.externalId??"null"} \u2014 ${s.why}`);return r.join(`
|
|
1243
|
+
`)}function By(t,e){return t.split(`
|
|
1099
1244
|
`).map(n=>e+n).join(`
|
|
1100
|
-
`)}var
|
|
1245
|
+
`)}var Fy="2026-01-01",Bd="2026-01-01T00:00:00.000Z";function Hy(t,e){let n=t.trim().toLowerCase();return n==="boolean"||n==="bool"?!1:n==="smallint"||n==="integer"||n==="int"||n==="int2"||n==="int4"||n==="int8"||n==="bigint"||n==="serial"||n==="bigserial"?1:n==="numeric"||n==="decimal"||n==="real"||n==="double precision"||n==="float4"||n==="float8"||n==="money"?0:n==="date"?Fy:n.startsWith("timestamp")?Bd:n.startsWith("time")?"00:00:00":n==="json"||n==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:Bd}:{}:n==="uuid"?"00000000-0000-0000-0000-000000000000":n==="array"||n.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function Ky(t){let e={};for(let n of t.columns)e[n.name]=Hy(n.pgType,n.name);return e}function Vy(t,e={}){let n=e.event??"before_save";return{name:`${t.recordType} ${n} (generated)`,context:{recordType:t.recordType,event:n,source:t.source,payload:Ky(t)},expect:e.expect??"pass"}}function Fd(t,e={}){return t.map(n=>({recordType:n.recordType,fixture:Vy(n,e)}))}import{promises as Hd}from"node:fs";import{join as Kd,relative as Gy,sep as Wy}from"node:path";var Jy=67324752,Zy=33639248,Yy=101010256,Qy=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function Xy(t){let e=4294967295;for(let n=0;n<t.length;n++)e=Qy[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}async function eb(t){let e=[];async function n(r){let s=await Hd.readdir(r,{withFileTypes:!0});for(let o of s){let i=Kd(r,o.name);o.isDirectory()?await n(i):o.isFile()&&e.push(Gy(t,i).split(Wy).join("/"))}}return await n(t),e.sort(),e}async function Vd(t){let e=await eb(t),n=[],r=[],s=0;for(let a of e){let l=Buffer.from(a,"utf8"),p=await Hd.readFile(Kd(t,a)),u=Xy(p),m=Buffer.alloc(30+l.length);m.writeUInt32LE(Jy,0),m.writeUInt16LE(20,4),m.writeUInt16LE(0,6),m.writeUInt16LE(0,8),m.writeUInt32LE(u,14),m.writeUInt32LE(p.length,18),m.writeUInt32LE(p.length,22),m.writeUInt16LE(l.length,26),l.copy(m,30),n.push(m,p);let x=Buffer.alloc(46+l.length);x.writeUInt32LE(Zy,0),x.writeUInt16LE(20,4),x.writeUInt16LE(20,6),x.writeUInt16LE(0,10),x.writeUInt32LE(u,16),x.writeUInt32LE(p.length,20),x.writeUInt32LE(p.length,24),x.writeUInt16LE(l.length,28),x.writeUInt32LE(s,42),l.copy(x,46),r.push(x),s+=m.length+p.length}let o=Buffer.concat(r),i=Buffer.alloc(22);return i.writeUInt32LE(Yy,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(o.length,12),i.writeUInt32LE(s,16),{buffer:Buffer.concat([...n,o,i]),fileCount:e.length}}function tb(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function Rs(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function nb(t){let e=Gd(t,"from"),n=Gd(t,"to");return{fromSource:e?Rs(e,"source"):void 0,fromRecordType:e?Rs(e,"recordType"):void 0,toSource:n?Rs(n,"source"):void 0,toRecordType:n?Rs(n,"recordType"):void 0}}function Gd(t,e){let n=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!n)return null;let r=0,s=n.index+n[0].length-1;for(let o=s;o<t.length;o+=1){let i=t[o];if(i==="{")r+=1;else if(i==="}"&&(r-=1,r===0))return t.slice(s+1,o)}return null}function rb(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let n=e.index+e[0].length,r=0,s=null,o=n;for(;o<t.length;o+=1){let l=t[o];if(s){l==="\\"?o+=1:l===s&&(s=null);continue}if(l==="'"||l==='"'||l==="`"){s=l;continue}if(l==="("||l==="{"||l==="[")r+=1;else if(l===")"||l==="}"||l==="]"){if(r===0)break;r-=1}else if(l===","&&r===0)break}let i=t.slice(n,o),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function sb(t,e){let n=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return n?Number(n[1]):void 0}function ob(t){return/\bcreatedFrom\b/.test(t)}function Wd(t){let e=tb(t),n=[];if(e==="hook")return{kind:e,warnings:n};let{fromSource:r,toSource:s,fromRecordType:o,toRecordType:i}=nb(t);r&&s&&r===s&&n.push({rule:"same-source-conduit",message:`from.source and to.source are both '${r}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});let a=rb(t);if(a!==null){let p=/\bexternalId\b/.test(a),u=/\bfromSource\b/.test(a);!p&&!u&&n.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}o&&i&&o!==i&&!ob(t)&&n.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let l=sb(t,"cycleBudget");return l!==void 0&&(l<1?n.push({rule:"cycle-budget-too-low",message:`cycleBudget=${l} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):l>20&&n.push({rule:"cycle-budget-too-high",message:`cycleBudget=${l} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:n}}function Jd(t,e,n={}){let r=n.warn??(a=>a),s=n.ok??(a=>a),o=n.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${s("ok")} \u2014 no warnings.`),i.join(`
|
|
1101
1246
|
`);for(let a of e.warnings)i.push(` ${r("WARN")} ${o(`[${a.rule}]`)} ${a.message}`),i.push(` ${o("\u2192 fix:")} ${a.fix}`);return i.push(`
|
|
1102
1247
|
lint: ${r(`${e.warnings.length} warning(s).`)}`),i.join(`
|
|
1103
|
-
`)}function
|
|
1248
|
+
`)}function Zd(t){return t.cases.filter(e=>e.status==="failed").length}function hr(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ib(t){let e=Zd(t),n=[];n.push('<?xml version="1.0" encoding="UTF-8"?>'),n.push(`<testsuite name="${hr(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let r of t.cases){let s=` <testcase name="${hr(r.name)}"`;if(r.status==="passed"){n.push(`${s} />`);continue}n.push(`${s}>`);let o=r.detail??"failed",i=r.type?` type="${hr(r.type)}"`:"";n.push(` <failure${i} message="${hr(o)}">${hr(o)}</failure>`),n.push(" </testcase>")}return n.push("</testsuite>"),`${n.join(`
|
|
1104
1249
|
`)}
|
|
1105
|
-
`}function
|
|
1106
|
-
`}function
|
|
1107
|
-
`)}function
|
|
1108
|
-
`)}function
|
|
1250
|
+
`}function ab(t){let e={suite:t.name,tests:t.cases.length,failures:Zd(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
|
|
1251
|
+
`}function Ts(t,e){return e==="junit"?ib(t):ab(t)}var Ke={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",invert:"\x1B[7m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",grey:"\x1B[90m"},_e={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Sn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],et={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Yd=/\x1b\[[0-9;]*m/g;function Et(t){return t.replace(Yd,"").length}function Li(t,e){return e<=0?1:Math.max(1,Math.ceil(Et(t)/e))}function lb(){return process.env.NO_COLOR!=null&&process.env.NO_COLOR!==""?!1:process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0"?!0:process.env.TERM==="dumb"?!1:process.stdout.isTTY===!0}var Di=lb();function Te(){return Di}function Ui(t){Di=t}function ze(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function tt(t,e){return Di?`${t}${e}${Ke.reset}`:e}var h={bold:t=>tt(Ke.bold,t),dim:t=>tt(Ke.dim,t),red:t=>tt(Ke.red,t),green:t=>tt(Ke.green,t),yellow:t=>tt(Ke.yellow,t),blue:t=>tt(Ke.blue,t),magenta:t=>tt(Ke.magenta,t),cyan:t=>tt(Ke.cyan,t),grey:t=>tt(Ke.grey,t)};var ve={success:t=>`${h.green("\u2713")} ${t}`,error:t=>`${h.red("\u2716")} ${t}`,warn:t=>`${h.yellow("\u26A0")} ${t}`,info:t=>`${h.dim("\xB7")} ${t}`,step:t=>`${h.cyan("\u25B8")} ${t}`},Ut={add:t=>h.green(`+ ${t}`),change:t=>h.yellow(`~ ${t}`),destroy:t=>h.red(`- ${t}`)},cb=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),db=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),ub=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function _n(t){let e=t.toLowerCase();return cb.has(e)?h.green(t):db.has(e)?h.red(t):ub.has(e)?h.yellow(t):t}function zt(t,e=[]){let n=Math.max(Et(t),...e.map(Et),0),r=n+2,s=h.cyan(et.v),o=a=>` ${a}${" ".repeat(n-Et(a))} `,i=[h.cyan(`${et.tl}${et.h.repeat(r)}${et.tr}`),`${s}${h.bold(o(t))}${s}`];if(e.length){i.push(`${h.cyan(et.ml)}${h.dim(et.h.repeat(r))}${h.cyan(et.mr)}`);for(let a of e)i.push(`${s}${o(a)}${s}`)}return i.push(h.cyan(`${et.bl}${et.h.repeat(r)}${et.br}`)),i.join(`
|
|
1252
|
+
`)}function pt(t,e={}){let n=e.indent??" ",r=e.gap??" ",s=e.head?[e.head,...t]:t,o=Math.max(0,...s.map(p=>p.length)),i=[];for(let p=0;p<o;p+=1)i[p]=Math.max(0,...s.map(u=>Et(u[p]??"")));let a=p=>{let u=p.map((m,x)=>{let v=m??"";return x===p.length-1?v:v+" ".repeat(Math.max(0,i[x]-Et(v)))});return n+u.join(r)},l=[];e.head&&(l.push(a(e.head.map(p=>h.bold(p)))),l.push(a(e.head.map((p,u)=>h.dim("\u2500".repeat(i[u]??Et(p)))))));for(let p of t)l.push(a(p));return l.join(`
|
|
1253
|
+
`)}function zi(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${Te()?e.map(r=>tt(Ke.cyan,r)).join(`
|
|
1109
1254
|
`):e.join(`
|
|
1110
1255
|
`)}
|
|
1111
|
-
${
|
|
1112
|
-
`),i}catch(i){throw o(),n&&
|
|
1113
|
-
`),i}}function
|
|
1114
|
-
`),o()},status(l){n=l,o()},done(l){clearInterval(a),i(),
|
|
1115
|
-
`)},stop(){clearInterval(a),i(),
|
|
1116
|
-
`),a(`${
|
|
1117
|
-
`),a(
|
|
1118
|
-
`),
|
|
1119
|
-
`),s(new Error("aborted"));return}if(
|
|
1120
|
-
`){let I=e[i];if(I.disabled)return;
|
|
1121
|
-
`)}),s=n.sleep??
|
|
1122
|
-
`)});if(e.retry){let s=await t.retryBinding(e.retry);return n(`binding: re-enqueued fan-out for ${s.id} \u2192 ${s.sourceSystem} (master ${s.masterTable}/${s.masterRowId}).`),{mode:"retry",id:s.id,retried:s.retried}}let r=await t.bindings({status:e.status,limit:e.limit});if(r.length===0)return n(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let s of r)n(
|
|
1123
|
-
binding: ${r.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:r.length}}
|
|
1256
|
+
${h.dim(` ${t}`)}`}var nt=t=>{process.stderr.write(t)};function Es(){return Te()&&process.stderr.isTTY===!0}function Qd(t,e=15){let n=Math.max(0,Math.min(100,t??0)),r=Math.round(n/100*e);return`${"\u2588".repeat(r)}${h.dim("\u2591".repeat(e-r))}`}async function J(t,e){let n=Es(),r=0,s;n&&(nt(_e.hideCursor),s=setInterval(()=>{nt(`${_e.col0}${_e.clearLine}${h.magenta(Sn[r++%Sn.length])} ${t}`)},80));let o=()=>{s&&clearInterval(s),n&&nt(`${_e.col0}${_e.clearLine}${_e.showCursor}`)};try{let i=await e();return o(),n&&nt(`${ve.success(t)}
|
|
1257
|
+
`),i}catch(i){throw o(),n&&nt(`${ve.error(t)}
|
|
1258
|
+
`),i}}function qi(t){let e=0,n={stage:"queued"},r=!1,s=()=>{let l=h.magenta(Sn[e%Sn.length]),p=h.cyan(n.stage),u=n.runStatus?` ${h.dim(`(${n.runStatus})`)}`:"",m=`${String(Math.round(n.percent??0)).padStart(3)}%`;return`${l} ${t} ${h.dim("\u25B8")} ${p}${u} ${Qd(n.percent)} ${m}`},o=()=>{nt(`${_e.col0}${_e.clearLine}${s()}`),r=!0},i=()=>{r&&nt(`${_e.col0}${_e.clearLine}`),r=!1};nt(_e.hideCursor);let a=setInterval(()=>{e+=1,o()},80);return{log(l){i(),nt(`${l}
|
|
1259
|
+
`),o()},status(l){n=l,o()},done(l){clearInterval(a),i(),nt(_e.showCursor);let p=l.stage!=="failed",u=`${t} ${h.dim("\u25B8")} ${pb(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;nt(`${p?ve.success(u):ve.error(u)}
|
|
1260
|
+
`)},stop(){clearInterval(a),i(),nt(_e.showCursor)}}}function pb(t){return t==="completed"?h.green(t):t==="failed"?h.red(t):h.cyan(t)}function qe(t,e,n={}){return new Promise((r,s)=>{let o=e.findIndex(R=>!R.disabled);if(o===-1){s(new Error("no selectable options"));return}let i=n.defaultIndex!==void 0&&!e[n.defaultIndex]?.disabled?n.defaultIndex:o,a=R=>{process.stderr.write(R)},l=process.stdin,p=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${h.bold(h.cyan("?"))} ${h.bold(t)}
|
|
1261
|
+
`),a(`${h.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
1262
|
+
`),a(_e.hideCursor);let u=0,m=()=>{let R=process.stderr.columns??process.stdout.columns??80;u>0&&(a(_e.cursorUp(u)),a(_e.clearToEnd));let E=0;for(let P=0;P<e.length;P+=1){let I=e[P],U=P===i,se=U?h.cyan("\u25B6"):" ",V=I.disabled?h.grey(I.label):U?h.bold(h.cyan(I.label)):I.label,De=I.description?` ${h.dim(I.description)}`:"",He=` ${se} ${V}${De}`;a(`\r${He}
|
|
1263
|
+
`),E+=Li(He,R)}u=E},x=()=>{l.removeListener("data",k),l.setRawMode?.(p??!1),l.pause(),a(_e.showCursor)},v=R=>{let E=i;for(let P=0;P<e.length;P+=1)if(E=(E+R+e.length)%e.length,!e[E].disabled){i=E;return}},k=R=>{let E=R.toString("utf8");if(E===""||E==="q"){x(),a(`
|
|
1264
|
+
`),s(new Error("aborted"));return}if(E==="\r"||E===`
|
|
1265
|
+
`){let I=e[i];if(I.disabled)return;x(),r(I.value);return}if(E==="\x1B[A"||E==="k"){v(-1),m();return}if(E==="\x1B[B"||E==="j"){v(1),m();return}let P=Number(E);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,m())};l.on("data",k),m()})}function eu(t,e){return`${_n(t)}${" ".repeat(Math.max(0,e-t.length))}`}var fb=t=>new Promise(e=>setTimeout(e,t));function Xd(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,n=t.reason?` reason="${t.reason}"`:"",r=t.fromExternalId?` ext=${t.fromExternalId}`:"",s=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${eu(t.state,9)} ${t.conduitId} \u2192 ${e}${r} hop=${t.hop}${s}${n}`}async function tu(t,e,n={}){let r=n.sink??(u=>{process.stdout.write(`${u}
|
|
1266
|
+
`)}),s=n.sleep??fb,o=n.intervalMs??2e3,i=await t.conduitEvents(e,{limit:n.limit??100});if(i.length===0&&!n.follow)return r(`logs: no conduit_event rows for ${e}.`),0;let a=0,l="";for(let u of[...i].reverse())r(Xd(u)),a+=1,u.updatedAt>l&&(l=u.updatedAt);if(!n.follow)return a;let p=n.maxPolls??Number.POSITIVE_INFINITY;for(let u=0;u<p;u+=1){await s(o);let m=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let x of[...m].reverse())r(Xd(x)),a+=1,x.updatedAt>l&&(l=x.updatedAt)}return a}function hb(t){let e=t.externalId??"\u2014",n=t.createdByConduit?` via=${t.createdByConduit}`:"",r=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${eu(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${n}${r}`}async function nu(t,e={}){let n=e.sink??(s=>{process.stdout.write(`${s}
|
|
1267
|
+
`)});if(e.retry){let s=await t.retryBinding(e.retry);return n(`binding: re-enqueued fan-out for ${s.id} \u2192 ${s.sourceSystem} (master ${s.masterTable}/${s.masterRowId}).`),{mode:"retry",id:s.id,retried:s.retried}}let r=await t.bindings({status:e.status,limit:e.limit});if(r.length===0)return n(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let s of r)n(hb(s));return n(`
|
|
1268
|
+
binding: ${r.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:r.length}}Ps();function su(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var Mi=".github/workflows/turbobase-release-deploy.yml",bb=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1124
1269
|
# Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
1125
1270
|
#
|
|
1126
1271
|
# Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
|
|
@@ -1222,7 +1367,7 @@ jobs:
|
|
|
1222
1367
|
--ref "\${{ github.sha }}" \\
|
|
1223
1368
|
--project . \\
|
|
1224
1369
|
--follow
|
|
1225
|
-
`,
|
|
1370
|
+
`,wb=".github/workflows/turbobase-tables-plan.yml",vb=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1226
1371
|
# Turbobase table check \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
|
|
1227
1372
|
#
|
|
1228
1373
|
# Runs \`turbobase tables plan\` against your instance on every pull request. It
|
|
@@ -1297,14 +1442,14 @@ jobs:
|
|
|
1297
1442
|
# field and at what type. Writes nothing to the instance either way.
|
|
1298
1443
|
- name: Plan the declared tables
|
|
1299
1444
|
run: turbobase tables plan .
|
|
1300
|
-
`;function
|
|
1445
|
+
`;function ou(){return[{path:Mi,content:bb}]}function iu(){return[{path:wb,content:vb}]}Ps();var kb=[".mcp.json"];function lu(t,e=kb){let n=i=>i.replace(/^\//,""),r=new Set(t.split(`
|
|
1301
1446
|
`).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(n)),s=e.filter(i=>!r.has(n(i)));return s.length===0?null:`${t===""||t.endsWith(`
|
|
1302
1447
|
`)?t:`${t}
|
|
1303
1448
|
`}
|
|
1304
1449
|
# Added by the Turbobase scaffold.
|
|
1305
1450
|
${s.join(`
|
|
1306
1451
|
`)}
|
|
1307
|
-
`}var
|
|
1452
|
+
`}var Sb=`# Turbobase Extensions \u2014 extension project
|
|
1308
1453
|
|
|
1309
1454
|
This directory authors **Turbobase extensions** (hooks today; conduits later)
|
|
1310
1455
|
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
@@ -1373,8 +1518,8 @@ order is the signal, and it is the part the product team reads first.
|
|
|
1373
1518
|
|
|
1374
1519
|
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
1375
1520
|
updating a test. It is checked into the repo so the whole team sees it.
|
|
1376
|
-
`,
|
|
1377
|
-
`;function
|
|
1521
|
+
`,_b=JSON.stringify({mcpServers:{"turbobase-authoring":{type:"http",url:"__BASE_URL__/mcp/authoring",headers:{Authorization:"Bearer __PAT__"}},turbobase:{type:"http",url:"__BASE_URL__/mcp"}}},null,2)+`
|
|
1522
|
+
`;function $b(t){return`---
|
|
1378
1523
|
name: generate-types
|
|
1379
1524
|
description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
1380
1525
|
---
|
|
@@ -1385,7 +1530,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
|
|
|
1385
1530
|
|
|
1386
1531
|
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
1387
1532
|
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
1388
|
-
`}var
|
|
1533
|
+
`}var xb=`---
|
|
1389
1534
|
name: mock-test
|
|
1390
1535
|
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
1391
1536
|
---
|
|
@@ -1394,7 +1539,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
|
1394
1539
|
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
1395
1540
|
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
1396
1541
|
fixture for each branch (a passing record and a rejecting record).
|
|
1397
|
-
`,
|
|
1542
|
+
`,Rb=`---
|
|
1398
1543
|
name: deploy
|
|
1399
1544
|
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
1400
1545
|
---
|
|
@@ -1402,7 +1547,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
|
1402
1547
|
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
1403
1548
|
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
1404
1549
|
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
1405
|
-
`;function
|
|
1550
|
+
`;function Tb(t){return`# ${t} \u2014 Turbobase app
|
|
1406
1551
|
|
|
1407
1552
|
This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
|
|
1408
1553
|
same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
|
|
@@ -1481,6 +1626,8 @@ Check them before you trust a result.
|
|
|
1481
1626
|
- \`src/lib/turbobase.ts\` \u2014 the auth-wired client. Don't rewrite it; import from it.
|
|
1482
1627
|
- \`src/types.ts\` \u2014 generated record types (\`turbobase project types -o src/types.ts\`),
|
|
1483
1628
|
refreshed at the start of every Claude Code session.
|
|
1629
|
+
- \`hooks/\` \u2014 validation and business rules, one self-contained file each.
|
|
1630
|
+
- \`samples/\` \u2014 JSON fixtures \`turbobase ext test\` runs the hooks against.
|
|
1484
1631
|
- \`INSTANCE.md\` \u2014 the grounding brief (\`turbobase project grounding\`), refreshed
|
|
1485
1632
|
each session; instance-specific, don't hand-edit.
|
|
1486
1633
|
- \`vite.config.ts\` \u2014 \`base\` is pinned to \`/a/${t}/\` and MUST stay that way, or
|
|
@@ -1492,11 +1639,35 @@ Check them before you trust a result.
|
|
|
1492
1639
|
- **Read** with \`select('<table>?select=...')\` \u2192 PostgREST, row-level-security scoped.
|
|
1493
1640
|
- **Write** with \`write('<recordType>', { parent, lines })\` \u2192 \`POST /v1/data/:recordType\`,
|
|
1494
1641
|
the canonical write boundary. **Never** write a table directly through PostgREST.
|
|
1642
|
+
- **Delete** with \`del('<recordType>', { pgRowId })\` \u2192 \`DELETE /v1/data/:recordType\`.
|
|
1643
|
+
Returns \`{ deleted, enqueued }\`. \`enqueued\` means a source delete was QUEUED \u2014
|
|
1644
|
+
not that the source accepted it: it can still be held for operator approval or
|
|
1645
|
+
refused upstream, and that failure surfaces as a sync failure, not as a throw.
|
|
1495
1646
|
|
|
1496
1647
|
Both are same-origin and carry the session cookie. There are no app-owned keys,
|
|
1497
1648
|
no Bearer tokens to manage, and no sign-in page to build \u2014 the instance handles
|
|
1498
1649
|
auth before your SPA loads.
|
|
1499
1650
|
|
|
1651
|
+
## Business rules go in a hook, not in this app
|
|
1652
|
+
|
|
1653
|
+
The app **cannot** bypass \`POST /v1/data\` \u2014 \`authenticated\` holds no
|
|
1654
|
+
INSERT/UPDATE/DELETE on the mirror, so a PostgREST write is refused however the
|
|
1655
|
+
query is phrased. Don't try to route around it; that boundary is where every
|
|
1656
|
+
write runs the record type's \`before_save\`.
|
|
1657
|
+
|
|
1658
|
+
So validation belongs in a hook, not in a component: a rule enforced in
|
|
1659
|
+
\`App.tsx\` is bypassed by the chat agent, an MCP client, the sync worker and the
|
|
1660
|
+
next app. \`hooks/\` already holds a working example for the record the starter
|
|
1661
|
+
touches. Edit it, then:
|
|
1662
|
+
|
|
1663
|
+
\`\`\`sh
|
|
1664
|
+
turbobase ext test hooks/<file>.ts # against samples/*.json, in the production sandbox
|
|
1665
|
+
turbobase ext deploy hooks/<file>.ts # lands ACTIVE \u2014 it gates writes immediately
|
|
1666
|
+
\`\`\`
|
|
1667
|
+
|
|
1668
|
+
A hook is pure and credentials-free: no secrets, no network, no Node builtins,
|
|
1669
|
+
and nothing factored into a shared module.
|
|
1670
|
+
|
|
1500
1671
|
**Reading data yourself, without a browser.** The PAT in \`.mcp.json\` authenticates
|
|
1501
1672
|
the authoring MCP, but PostgREST rejects it outright (\`PGRST301 \u2026 Expected 3
|
|
1502
1673
|
parts; got 1\`) \u2014 it is an opaque bearer, not a JWT. To read rows from a script or
|
|
@@ -1587,7 +1758,27 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
|
1587
1758
|
review, so what you write reaches the knowledge base and the product team instead
|
|
1588
1759
|
of evaporating at the end of the session. Keep the section headings exactly as
|
|
1589
1760
|
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
1590
|
-
`}var
|
|
1761
|
+
`}var $n="customer",rn="email",Eb="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",Pb=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
|
|
1762
|
+
//
|
|
1763
|
+
// It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
|
|
1764
|
+
// the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
|
|
1765
|
+
// PostgREST write is refused however the query is phrased. That is what makes a
|
|
1766
|
+
// rule here different from the same rule in a React component \u2014 this one also
|
|
1767
|
+
// applies to the chat agent, an MCP client, another app, and the sync worker.
|
|
1768
|
+
//
|
|
1769
|
+
// As written it rejects a malformed address and passes everything else, so the
|
|
1770
|
+
// app's edit box shows you the rejection the moment you try one. Replace the
|
|
1771
|
+
// check with the rule you actually need.
|
|
1772
|
+
//
|
|
1773
|
+
// turbobase ext lint hooks/... static check
|
|
1774
|
+
// turbobase ext test hooks/... run against samples/*.json, in the production sandbox
|
|
1775
|
+
// turbobase ext deploy hooks/... lands ACTIVE \u2014 it starts gating writes immediately
|
|
1776
|
+
//
|
|
1777
|
+
// Pure and credentials-free: no secrets, no network, no Node builtins, one
|
|
1778
|
+
// concern per file, nothing factored into a shared module (the sandbox fences
|
|
1779
|
+
// every import except the SDK).
|
|
1780
|
+
`;function Ab(){let t=Mt("hook",{recordType:$n,event:"before_save",template:"enforce-format",field:rn,regex:Eb,id:`app:${$n}:${rn}-format`,description:`Reject a ${$n} write whose ${rn} is not an address.`}),e=(n,r,s)=>JSON.stringify({name:s,context:{recordType:$n,event:"before_save",payload:n},expect:r},null,2)+`
|
|
1781
|
+
`;return[{path:t.relativePath,content:`${Pb}${t.content}`},{path:`samples/${$n}.${rn}-ok.json`,content:e({company_name:"Acme Supply",[rn]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${$n}.${rn}-malformed.json`,content:e({company_name:"Acme Supply",[rn]:"ada-at-example"},"reject","a malformed address is rejected")}]}var Ib="---\nname: preview-app\ndescription: Run the app locally against the instance and check it in a browser. Use after editing the app, before pushing.\n---\n\nStart the dev server NON-BLOCKING (`npm run dev` detached) \u2014 a foreground dev\nserver hangs the session. It proxies `/rest`, `/realtime`, `/v1`, `/auth`,\n`/login` and `/_app` to the instance, so localhost behaves same-origin and the\nsession cookie applies.\n\n**The app is at `http://localhost:3000/a/<slug>/`, not `/`.** Vite serves under\n`base` in dev too; `/` 302s there. Probing `/` and reading the 302 as \"broken\" is\nthe easy mistake here.\n\nThen actually look at it. A build that compiles and a lint that passes prove the\ncode is well-formed, not that it runs: a guard that throws during render, a\nPostgREST embed that 400s because the FK doesn't exist on this instance, an empty\nstate standing in for a failed query \u2014 none of those move the build signal.\n\n- Unauthenticated `/a/<slug>/` returns 200 with the SPA shell, and so does a deep\n client route like `/a/<slug>/customers/42` (Vite's SPA fallback). A 500 means a\n component threw \u2014 fix it, don't ship it.\n- `/login` returns the INSTANCE's sign-in page through the proxy. The app itself\n has no login route and should never grow one.\n- If a list renders empty, check the network tab before assuming there's no data:\n a 400 from PostgREST and a genuinely empty table look identical on screen.\n- `permission denied for table <x>` (SQLSTATE `42501`) usually means NOT SIGNED\n IN, not a role problem: with no session cookie PostgREST answers as the\n anonymous role and every table denies. Load `/login` through the proxy and\n sign in before reading the error as an RLS grant issue.\n\nVite reads `vite.config.ts` and `.env` only at boot \u2014 restart after changing either.\n",Cb=`---
|
|
1591
1782
|
name: ship-app
|
|
1592
1783
|
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
1593
1784
|
---
|
|
@@ -1630,7 +1821,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
|
|
|
1630
1821
|
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
1631
1822
|
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
1632
1823
|
project root and DO travel \u2014 deploy reads them.
|
|
1633
|
-
`;function
|
|
1824
|
+
`;function Ob(t){return`---
|
|
1634
1825
|
name: record-learning
|
|
1635
1826
|
description: Append to INSTANCE-LEARNINGS.md or TURBOBASE-FEEDBACK.md. Use the MOMENT you establish a fact about how this instance is set up, or the platform costs you time \u2014 in the same change, not at the end of the task and not when asked.
|
|
1636
1827
|
---
|
|
@@ -1675,7 +1866,7 @@ the product team acts on first, so it is maintained with the entries.
|
|
|
1675
1866
|
|
|
1676
1867
|
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
1677
1868
|
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
1678
|
-
`}function
|
|
1869
|
+
`}function Nb(t){return`# What this instance's source system actually does
|
|
1679
1870
|
|
|
1680
1871
|
Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
1681
1872
|
Written for the knowledge base, and **everything here is verified against real
|
|
@@ -1794,7 +1985,7 @@ finding has not been handed to the knowledge base yet.
|
|
|
1794
1985
|
and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
|
|
1795
1986
|
already live, which is worth reading before adding another rule. -->
|
|
1796
1987
|
|
|
1797
|
-
`}function
|
|
1988
|
+
`}function jb(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
|
|
1798
1989
|
|
|
1799
1990
|
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
1800
1991
|
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
@@ -1858,7 +2049,7 @@ Expected / happened / cost / fix.
|
|
|
1858
2049
|
|
|
1859
2050
|
<!-- Rank the findings above by how much time each would have saved. Position is
|
|
1860
2051
|
the signal \u2014 1 is the biggest win. -->
|
|
1861
|
-
`}function
|
|
2052
|
+
`}function Lb(t,e){let n=e?`
|
|
1862
2053
|
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
1863
2054
|
# --records focus a previous run stamped into the file, so a refresh never
|
|
1864
2055
|
# narrows what an agent deliberately widened.
|
|
@@ -1876,52 +2067,53 @@ turbobase project grounding \${records:+--records "$records"} --query ${JSON.str
|
|
|
1876
2067
|
set -euo pipefail
|
|
1877
2068
|
turbobase project types -o ${t} >/dev/null \\
|
|
1878
2069
|
|| echo "turbobase: \\\`turbobase project types\\\` failed (its error is above) \u2014 ${t} was NOT refreshed." >&2
|
|
1879
|
-
${n}`}var
|
|
1880
|
-
`,
|
|
2070
|
+
${n}`}var Db=JSON.stringify({hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}]}},null,2)+`
|
|
2071
|
+
`,au="",Ub=t=>`node_modules/
|
|
1881
2072
|
|
|
1882
2073
|
# Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
|
|
1883
2074
|
.mcp.json
|
|
1884
2075
|
|
|
1885
2076
|
.DS_Store
|
|
1886
|
-
`;function
|
|
1887
|
-
`))n(i)}return r}async function
|
|
1888
|
-
`)}),r=e.sleep??
|
|
1889
|
-
`)},
|
|
1890
|
-
`)};function
|
|
1891
|
-
`)){let s=
|
|
2077
|
+
`;function Bi(t={}){let e=_b.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),n=!!t.appSlug,r=n?"src/types.ts":"types.ts",s=n?{slug:t.appSlug}:void 0,o=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:Ub(n)},{path:"INSTANCE-LEARNINGS.md",content:Nb(s)},{path:"TURBOBASE-FEEDBACK.md",content:jb(s)},{path:".claude/settings.json",content:Db},{path:".claude/skills/generate-types/SKILL.md",content:$b(r)},{path:".claude/skills/record-learning/SKILL.md",content:Ob(s)},{path:".claude/hooks/session-start-refresh-types.sh",content:Lb(r,s),executable:!0}];return n?[{path:"CLAUDE.md",content:Tb(t.appSlug)},...o,{path:".claude/skills/preview-app/SKILL.md",content:Ib},{path:".claude/skills/ship-app/SKILL.md",content:Cb},...Ab(),...iu()]:[{path:"CLAUDE.md",content:Sb},...o,{path:".claude/skills/mock-test/SKILL.md",content:xb},{path:".claude/skills/deploy/SKILL.md",content:Rb},{path:"hooks/.gitkeep",content:au},{path:"samples/.gitkeep",content:au}]}import{promises as Ki}from"node:fs";import{resolve as Hb}from"node:path";var zb="For app developers \u2014 adopt these";function cu(t){let e=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(t.trim());return e?{core:[Number(e[1]),Number(e[2]??0),Number(e[3]??0)],prerelease:e[4]??""}:null}function du(t,e){let n=cu(t),r=cu(e);if(!n&&!r)return 0;if(!n)return-1;if(!r)return 1;for(let s=0;s<3;s++){let o=(n.core[s]??0)-(r.core[s]??0);if(o!==0)return o}return n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease<r.prerelease?-1:1:-1:1}function qb(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var gP=qb(zb);cr();Tt();var Mb=t=>new Promise(e=>setTimeout(e,t));function uu(t){return t.stage==="completed"||t.stage==="failed"}function Bb(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function Fb(t,e,n){let r=t.outputTail??"";if(r&&r!==e){let o=(r.startsWith(e)?r.slice(e.length):r).replace(/\n+$/,"");if(o)for(let i of o.split(`
|
|
2078
|
+
`))n(i)}return r}async function Fi(t,e={}){let n=e.sink??(x=>{process.stdout.write(`${x}
|
|
2079
|
+
`)}),r=e.sleep??Mb,s=e.intervalMs??2e3,o=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(x=>n(Bb(x))),a=e.onPoll,l="",p="",u=x=>{a?.(x),x.stage!==p&&i(x),l=Fb(x,l,n),p=x.stage},m=await t();if(u(m),uu(m))return m;for(let x=0;x<o;x+=1)if(await r(s),m=await t(),u(m),uu(m))return m;return m}var w=t=>{process.stdout.write(`${t}
|
|
2080
|
+
`)},D=t=>{process.stderr.write(`${t}
|
|
2081
|
+
`)};function b(t){D(h.red(`turbobase: ${t}`)),process.exit(1)}var mr=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function pu(t,e){let n=e.json===!0||typeof e.reporter=="string";(t.color===!1||n)&&Ui(!1)}async function H(t){let e=await ut(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let n=await Rt();if(t){let r=n.length?` Stored instances: ${n.map(s=>s.baseUrl).join(", ")}.`:"";b(`not signed in to ${Xe(t)}.${r} Run \`turbobase auth login --base-url ${Xe(t)} --token tb_pat_\u2026\`.`)}if(n.length===0&&b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ze())try{let r=await qe("Multiple instances stored \u2014 pick the active one:",n.map(o=>({value:o.baseUrl,label:o.baseUrl,description:`updated ${o.updatedAt}`})));await Ss(r);let s=await ut();if(s)return{baseUrl:s.baseUrl,token:s.token}}catch{}b(`multiple instances stored (${n.map(r=>r.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function G(t,e,n){if(!(t instanceof X)||t.status!==403)return;t.body?.error==="approval_required"&&b(`${n} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),b(`${n} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Hi(t,e,n){let r=n?Number(n):void 0;if(Es()){let o=qi(e),i;try{i=await Fi(t,{intervalMs:r,sink:a=>o.log(a),onStage:()=>{},onPoll:a=>o.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){o.stop(),b(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}o.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let s;try{s=await Fi(t,{sink:w,intervalMs:r})}catch(o){b(`${e} --follow failed: ${o instanceof Error?o.message:String(o)}`)}s.stage==="failed"&&b(`${e} failed${s.runStatus?` (${s.runStatus})`:""}.`),w(`${e} ${s.stage}.`)}var Kb=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function Vb(t){try{let e=await Ki.readFile(t,"utf8");return Kb.exec(e)?.[1]??null}catch{return null}}var Gb=/GENERATED by `turbobase project adopt`/,hu=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,Wb=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function fu(t){let e=[],n=null;for(let r of t.split(`
|
|
2082
|
+
`)){let s=hu.exec(r);if(s){n={version:s[1],items:[]},e.push(n);continue}if(/^#{1,6}[ \t]/.test(r)){n=null;continue}if(!n)continue;let o=Wb.exec(r);if(o){let a=o[2].trim();n.items.push({key:a.replace(/\s+/g," "),done:o[1]!==" ",text:a,extra:[]});continue}let i=n.items[n.items.length-1];i&&r.trim()!==""&&i.extra.push(r)}return e}function Jb(t){let e=t.items.map(n=>[`- [${n.done?"x":" "}] ${n.text}`,...n.extra].join(`
|
|
1892
2083
|
`)).join(`
|
|
1893
2084
|
`);return`## v${t.version}
|
|
1894
2085
|
|
|
1895
|
-
${e}`}function
|
|
1896
|
-
`),a=i.findIndex(
|
|
2086
|
+
${e}`}function Zb(t,e){let n=fu(t);if(n.length===0&&!Gb.test(t))return null;let r=new Map(n.map(u=>[u.version,u])),s=[],o=0;for(let u of fu(e)){let m=r.get(u.version);r.delete(u.version);let x=new Set(u.items.map(k=>k.key)),v=u.items.map(k=>{let R=m?.items.find(E=>E.key===k.key);return R?{...k,done:R.done,extra:R.extra}:k});for(let k of m?.items??[])x.has(k.key)||k.done||(v.push(k),o+=1);s.push({version:u.version,items:v})}for(let u of r.values()){let m=u.items.filter(x=>!x.done);m.length!==0&&(o+=m.length,s.push({version:u.version,items:m}))}s.sort((u,m)=>du(m.version,u.version));let i=e.split(`
|
|
2087
|
+
`),a=i.findIndex(u=>hu.test(u)),l=(a===-1?i:i.slice(0,a)).join(`
|
|
1897
2088
|
`).replace(/\s+$/,"");return{markdown:s.length===0?`${l}
|
|
1898
2089
|
`:`${l}
|
|
1899
2090
|
|
|
1900
|
-
${s.map(
|
|
2091
|
+
${s.map(Jb).join(`
|
|
1901
2092
|
|
|
1902
2093
|
`)}
|
|
1903
|
-
`,carried:o}}function
|
|
1904
|
-
|
|
1905
|
-
`,
|
|
1906
|
-
`);for(let r of n.slice(0,
|
|
1907
|
-
`))
|
|
1908
|
-
`))}catch(
|
|
1909
|
-
`))}async function
|
|
1910
|
-
`))n.push(` ${
|
|
1911
|
-
`))
|
|
1912
|
-
|
|
2094
|
+
`,carried:o}}function mu(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:n,token:r}=await H(e.baseUrl),s=Hb(process.cwd(),e.out),o=e.since?.trim()||await Vb(s),i=new URLSearchParams;o&&i.set("since",o);let a=i.toString(),l=await fetch(`${n}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});l.ok||b(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let p=await l.json();if(!p.available){w(`${n} ships no release notes to adopt from (nothing written).`);return}let u=p.releases.reduce((E,P)=>E+P.items.length,0);if(u===0){w(`up to date${o?` since v${o.replace(/^v/,"")}`:""}${p.currentVersion?` (instance is on v${p.currentVersion})`:""} \u2014 ${s} left untouched.`);return}let m=p.currentVersion??p.releases[0]?.version??"",x=`<!-- GENERATED by \`turbobase project adopt\` against ${n} \u2014 adopted-through=${m}. Re-run to refresh; delete this file once every line is done. -->
|
|
2095
|
+
|
|
2096
|
+
`,v=await Ki.readFile(s,"utf8").catch(()=>null),k=p.markdown,R=0;if(v!==null&&v.trim()!==""){let E=Zb(v,p.markdown);E||b(`${s} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),k=E.markdown,R=E.carried}await Ki.writeFile(s,x+k,"utf8"),w(`wrote ${s} \u2014 ${u} item(s) across ${p.releases.length} release(s)${o?` since v${o.replace(/^v/,"")}`:""}${R>0?`, keeping ${R} unticked item(s) already in the file`:""}.`)})}Tt();var gr=["suggested_kb_edit","kb_correction"];var Yb=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function Qb(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var PP=new Map(Yb.map(t=>[Qb(t.heading),t]));var AP=new RegExp(["^the (situation|context|background|problem|ask|point|gist|upshot|part\\b)","^the (one|two|three|four|five|six|seven|eight|nine|ten|\\d{1,2}) \\w+s?\\b","^(on|about) \\w+ing\\b","^(concrete|specific|possible|suggested) \\w+","^what (we|i|you)(\\b|'d| would| could| should)","^(background|summary|context|recommendations?|next steps|takeaways?|conclusion|in short|tl;?dr)\\b","^why (this|that|it) matters\\b"].join("|"),"i");function Xb(t){return t.diff??!!t.dryRun}var ew={update_page:"append to the existing page",new_page:"create a NEW page"},Pt=(t,e)=>` ${h.dim(t.padEnd(11))}${e}`,yu=t=>t.ownerEmail??t.ownerId;function xn(t){return!t.needsPageRef&&!t.blockedBy}var As=t=>h.green(t?` + ${t}`:" +"),tw=t=>h.red(t?` - ${t}`:" -"),sn=t=>h.dim(` ${t}`),nw=` ${h.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Vi=80;function rw(t){let e=[nw];t.target?(e.push(sn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(tw(`visibility: ${t.target.visibility}`)),e.push(As("visibility: admin"))):e.push(sn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(sn("title, slug, evidence: untouched")),e.push(sn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(sn("turbobase.document \xB7 new")),e.push(As(`title: ${t.pageTitle}`)),e.push(As("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(sn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(sn('appended under "## From app developers":'));let n=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
2097
|
+
`);for(let r of n.slice(0,Vi))e.push(As(r?` ${r}`:""));return n.length>Vi&&e.push(h.yellow(` \u2026 ${n.length-Vi} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function sw(t,e={}){let n=[];return t.forEach((r,s)=>{let{target:o,entries:i}=r;if(n.push(`${String(s+1).padStart(2)}. ${h.bold(r.pageTitle)}`),n.push(Pt("page",o?`${o.title} (${o.slug}) [${o.visibility}]`:h.dim("new \u2014 no existing page matches"))),n.push(Pt("action",xn(r)?ew[r.action]:h.red("SKIP \u2014 nothing is written"))),r.needsPageRef){let a=[...new Set(i.map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];n.push(Pt("unresolved",h.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(n.push(Pt("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let l=a.verdict?` ${h.dim(`\xB7 ${a.verdict}`)}`:"",p=a.kb_page_ref?` ${h.dim(`(${a.kb_page_ref})`)}`:"";n.push(` ${h.dim("\xB7")} ${a.title.trim()}${p}${l}`)}),n.push(Pt("confidence",r.withdraws?h.red("WITHDRAWN from readers (text untouched)"):h.dim("untouched"))),r.supersedes&&n.push(Pt("supersedes",h.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),r.blockedBy&&n.push(Pt("blocked",h.red(`unpublished work on this page belongs to ${yu(r.blockedBy)} \u2014 this page will be SKIPPED`))),r.alsoMatched.length>0&&n.push(Pt("ambiguous",h.yellow(`${r.alsoMatched.length} other page(s) match this ref: ${r.alsoMatched.map(a=>a.slug).join(", ")}`))),(r.similarTo?.length??0)>0){let a=(r.similarTo??[]).map(l=>{let p=t.findIndex(m=>m.key===l),u=p>=0?t[p]:void 0;return u?`#${p+1} "${u.pageTitle}"`:l});n.push(Pt("similar",h.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&xn(r)&&n.push(...rw(r)),n.push("")}),n}function ow(t){let e=p=>t.filter(p).length,n=t.reduce((p,u)=>p+u.entries.length,0),r=e(p=>p.withdraws),s=e(p=>p.blockedBy!=null),o=e(p=>p.needsPageRef),i=[`${n} finding${n===1?"":"s"}`,`${e(xn)} page(s)`,`${e(p=>p.action==="update_page"&&xn(p))} appended`,`${e(p=>p.action==="new_page"&&xn(p))} created (unpublished)`,...o>0?[h.red(`${o} SKIPPED \u2014 correction with no page to correct`)]:[]],a=r>0?h.red(`${r} page(s) WITHDRAWN from readers`):h.dim("no page withdrawn"),l=s>0?` \xB7 ${h.red(`${s} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function iw(t,e){let n=new Map(e.map(s=>[s.key,s])),r=[];for(let s of t){let o=n.get(s.key),i=s.pageTitle||o?.pageTitle||s.key;if(s.skipped==="blocked_by_draft_owner"){r.push(`${h.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${s.blockedBy?yu(s.blockedBy):"another editor"}; its findings stay pending`);continue}if(s.skipped==="unresolved_page_ref"){let l=[...new Set((o?.entries??[]).map(p=>p.kb_page_ref?.trim()).filter(p=>!!p))];r.push(`${h.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(p=>`"${p}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(s.skipped){r.push(`${h.yellow("skipped")} ${i} \u2014 ${s.skipped.replace(/_/g," ")}`);continue}let a=s.created?h.green("created "):h.green("appended");r.push(`${a} ${i} \u2014 ${s.appliedEntryIds.length} finding(s) \u2192 page ${h.bold(s.documentId??"?")}`+(s.created?h.dim(" (unpublished)"):"")),s.confidence==="downgraded"?r.push(` ${h.red("withdrawn from readers:")} ${i}`):s.confidence==="already_withdrawn"?r.push(` ${h.dim("page was already unpublished \u2014 left as is")}`):s.confidence==="missing"&&r.push(` ${h.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return r}function gu(t){if(t instanceof X){let e=t.body;t.status===403&&e?.reason==="admin_required"&&b("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&b("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}G(t,"extensions:deploy","learnings push-kb")}async function yr(t,e){let n;try{n=await J("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(s){return s instanceof X&&s.status===404?D(h.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):D(h.yellow(`could not re-read the pushed markdown: ${aw(s)} \u2014 planning anyway.`)),null}if(n.filesScanned===0)return D(h.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),n;let r=[`${n.filesScanned} file(s) scanned`];return n.docsIngested>0&&r.push(`${n.docsIngested} changed`),n.docsUnchanged>0&&r.push(`${n.docsUnchanged} unchanged`),r.push(`${n.entriesAdded} new finding(s)`),n.entriesDuplicate>0&&r.push(`${n.entriesDuplicate} already known`),n.parseSkipped>0&&r.push(h.yellow(`${n.parseSkipped} unparseable`)),D(h.dim(r.join(" \xB7 "))),n}function aw(t){return t instanceof Error?t.message:String(t)}async function bu(t,e=n=>new B(n)){t.section&&!gr.includes(t.section.trim())&&b(`unknown --section "${t.section}" \u2014 expected one of ${gr.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&b("--limit must be a positive integer.");let n=await H(t.baseUrl),r=e(n),s={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},o=await yr(r,t.app),i;try{i=await J("reading the pending queue",()=>r.learningsPending(s))}catch(p){gu(p),b(`could not read the pending queue: ${p instanceof Error?p.message:String(p)}`)}if(i.items.length===0){if(i.pendingTotal===0&&o&&o.entriesDuplicate>0){D(`nothing pending \u2014 all ${o.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}D(i.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${i.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(w(sw(i.items,{diff:Xb(t)}).join(`
|
|
2098
|
+
`)),w(ow(i.items)),t.dryRun){D(h.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(xn);if(a.length===0){D(h.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let l=a.reduce((p,u)=>p+u.entries.length,0);if(!t.yes){if(!ze()){D(h.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await qe(`Push ${l} finding(s) into the knowledge base as ${a.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){D("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let p=await J("writing pages",()=>r.learningsPushKb(i.planToken,s));w(iw(p.applied,i.items).join(`
|
|
2099
|
+
`))}catch(p){if(p instanceof X&&p.status===409){D(h.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),D(`re-run \`${mr} kb push\` to review the current plan.`),process.exitCode=2;return}gu(p),D(h.red(`turbobase: ${p instanceof Error?p.message:String(p)}`)),process.exitCode=2}}Tt();var Rn=t=>new B(t);async function Tn(t,e){let n=await H(t.baseUrl);return e(n)}async function Is(t,e,n,r){return r.yes?!0:ze()?await qe(t,[{value:"yes",label:e,description:n},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(D("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(D(h.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function lw(t){return t.visibility!=="published"?h.dim("draft"):t.in_current_release?h.green("live"):h.yellow("unreleased")}function wu(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function cw(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(o=>o.slug.length)),n=[];for(let o of t.items)n.push(`${wu(h.bold(o.slug),e)} ${wu(lw(o),10)} ${h.dim(o.path)}`);n.push("");let r=t.items.filter(o=>o.visibility==="published"&&o.in_current_release).length,s=t.items.filter(o=>o.visibility!=="published").length;return n.push(`${t.items.length} page(s) \xB7 ${r} readable \xB7 ${s} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),n}async function vu(t,e=Rn){let n={};t.status&&(t.status!=="draft"&&t.status!=="published"&&b(`--status must be 'draft' or 'published' (got '${t.status}').`),n.status=t.status);let r=await Tn(t,e),s;try{s=await J("reading the knowledge base",()=>r.docsList(n))}catch(o){G(o,"docs:publish","read the knowledge base"),b(`could not read the knowledge base: ${o instanceof Error?o.message:String(o)}`)}w(cw(s).join(`
|
|
2100
|
+
`))}async function ku(t,e,n=Rn){let r=[...new Set(t.map(l=>l.trim()).filter(Boolean))];r.length===0&&b("name at least one page slug. `turbobase kb list` shows them.");let s=await Tn(e,n);if(!await Is(`Publish ${r.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",e))return;let i;try{i=await J("publishing",()=>s.docsPublish(r))}catch(l){G(l,"docs:publish","publish a page"),b(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);w(h.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(D(h.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),D(h.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Su(t,e,n=Rn){let r=[...new Set(t.map(l=>l.trim()).filter(Boolean))];r.length===0&&b("name at least one page slug. `turbobase kb list` shows them.");let s=await Tn(e,n);if(!await Is(`Hide ${r.length} page(s) from readers?`,"Yes \u2014 unpublish them","they drop out of the reader snapshot immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>s.docsUnpublish(r))}catch(l){G(l,"docs:publish","unpublish a page"),b(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);w(h.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),D(h.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(D(h.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function _u(t,e=Rn){let n=await Tn(t,e),r;try{r=await J("reading the releases",()=>n.docsVersions())}catch(s){G(s,"docs:publish","read the knowledge-base releases"),b(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){w("no releases yet \u2014 nothing has been published.");return}for(let s of r.items){let o=s.is_current?h.green("current"):h.dim(" ");w(`v${String(s.version_no).padEnd(4)} ${o} ${s.published_at} ${s.node_count} page(s)${s.published_by?` ${h.dim(s.published_by)}`:""}`),s.release_note&&w(` ${h.dim(s.release_note)}`)}}async function $u(t,e,n=Rn){let r=Number(t);(!Number.isInteger(r)||r<1)&&b(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let s=await Tn(e,n);if(await Is(`Roll the knowledge base back to release v${r}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await J("rolling back",()=>s.docsRollback(r));w(h.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){G(i,"docs:publish","roll the knowledge base back"),b(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function xu(t,e,n=Rn){let r=(t??"").trim();r||b("name the page slug to delete. `turbobase kb list` shows them.");let s=await Tn(e,n);if(await Is(`Delete "${r}"?`,"Yes \u2014 delete it","it drops out of the tree and every reader release; its subtree goes with it, and it stays restorable from the editor\u2019s trash",e))try{let i=await J("deleting",()=>s.docsDelete(r));w(h.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){G(i,"docs:publish","delete a page"),b(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}Tt();function dw(t){return t.diff??!!t.dryRun}function uw(t,e){let n=[];return t.forEach((r,s)=>{let o=r.action==="new_rule"?h.green("new rule"):h.yellow("amend rule"),i=r.targetPublished?` ${h.yellow("[currently live]")}`:"";n.push(`${s+1}. ${o} ${h.bold(r.slug)}${i}`),n.push(` ${r.name}`),r.description&&n.push(` ${h.dim(r.description)}`);for(let a of r.entries)n.push(` ${h.dim("\xB7")} ${h.dim(a.app_slug)} ${a.title}`);if(e.diff){n.push("");for(let a of r.bodyMarkdown.split(`
|
|
2101
|
+
`))n.push(` ${h.dim("|")} ${a}`)}n.push("")}),n}function pw(t){let e=t.reduce((s,o)=>s+o.entries.length,0),n=t.filter(s=>s.targetPublished).length,r=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return n>0&&r.push(h.yellow(`${n} amend a rule that is currently live`)),r.join(" \xB7 ")}async function Ru(t,e=n=>new B(n)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&b("--limit must be a positive integer.");let n=await H(t.baseUrl),r=e(n),s={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},o=await yr(r,t.app),i;try{i=await J("reading the pending rules",()=>r.rulesPending(s))}catch(l){G(l,"extensions:deploy","read the pending rules"),b(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&o&&o.entriesDuplicate>0){D(`nothing pending \u2014 all ${o.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}D(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(w(uw(i.items,{diff:dw(t)}).join(`
|
|
2102
|
+
`)),w(pw(i.items)),t.dryRun){D(h.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,p)=>l+p.entries.length,0);if(!t.yes){if(!ze()){D(h.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await qe(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){D("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await J("writing the rules",()=>r.rulesPush(i.planToken,s))}catch(l){l instanceof X&&l.status===409&&b("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),b(`push failed: ${l instanceof Error?l.message:String(l)}`)}w(h.green(`wrote ${i.items.length} draft rule(s).`)),D(h.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}Tt();var fw=["proposed","active","rejected"],hw=["mechanic","operator","learning","code-baseline"],Cs=t=>new B(t);async function Os(t,e){let n=await H(t.baseUrl);return e(n)}function Tu(t,e,n){if(!t)return;let r=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);if(r.length!==0){for(let s of r)e.includes(s)||b(`${n}: unknown value '${s}' \u2014 expected one of ${e.join(", ")}.`);return r}}function mw(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&b("--limit must be a positive number."),Math.floor(e)}function Au(t){let e=Tu(t.status,fw,"--status"),n=Tu(t.provenance,hw,"--provenance"),r=mw(t.limit);return{...e?{status:e}:{},...n?{provenance:n}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...r?{limit:r}:{}}}function Eu(t){return!!(t.provenance?.length||t.recordType||t.source)}var Iu=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function gw(t){return t.status==="active"?h.green("active"):t.status==="rejected"?h.dim("rejected"):h.yellow("proposed")}function yw(t){return t.message?t.message:t.kind&&t.field?h.dim(`${t.kind} ${t.field}`):t.kind?h.dim(t.kind):h.dim("(no description)")}function Cu(t){return[t.hookId,gw(t),t.provenance==="learning"?h.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),yw(t)]}async function Ou(t={},e=Cs){let n=await Os(t,e),r=Au(t),s;try{s=await n.proposals(r)}catch(i){G(i,"extensions:deploy","list hook proposals"),b(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return w(JSON.stringify(s,null,2));if(s.length===0){let i=r.status?.length?r.status.join("/"):"proposed";return w(`no ${i} hook proposals.
|
|
2103
|
+
`+h.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}w(pt(s.map(Cu),{head:Iu})),w(h.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let o=s.filter(i=>i.provenance==="learning"&&i.status==="proposed");o.length>0&&w(h.dim(` ${o.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function bw(t,e,n){return n.yes?!0:ze()?await qe(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(D("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(D(h.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function ww(t){return!(t instanceof X)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Gi(t,e){ww(t)&&G(t,"extensions:deploy",e)}function Wi(t,e){let n=e instanceof X?e.body:void 0,r=n?.error==="forbidden"?n.reason??n.error:n?.error,o=r?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[r]??r:e instanceof Error?e.message:String(e);D(ve.error(`${h.bold(t)} \u2014 ${o}`))}async function Pu(t,e){try{let n=await t.proposalPromote(e);return w(ve.success(`${h.bold(e)} ${h.dim(`${n.previousStatus} \u2192`)} ${h.green(n.status)}`)),!0}catch(n){return Gi(n,"promote a hook proposal"),Wi(e,n),!1}}async function Nu(t,e={},n=Cs){!e.auto&&t.length===0&&b("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&b("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&b("promote: --apply / --all only mean something with --auto.");let r=await Os(e,n);if(!e.auto){let u=0;for(let m of t)await Pu(r,m)&&(u+=1);u>0&&w(h.dim(` ${u} hook(s) armed \u2014 the loader compiles them on its next reload.`)),u<t.length&&(process.exitCode=1);return}let s=Au({...e,status:e.status??"proposed"});s.provenance?.includes("learning")&&b("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),s.status?.some(u=>u!=="proposed")&&b("promote --auto: only `--status proposed` rows can be armed in bulk.");let o;try{o=await r.proposals(s)}catch(u){G(u,"extensions:deploy","list hook proposals"),b(`list hook proposals failed: ${u instanceof Error?u.message:String(u)}`)}let i=o.filter(u=>u.provenance==="learning"),a=o.filter(u=>u.provenance!=="learning");if(e.json&&(w(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(w(`nothing to promote${Eu(s)?" for that filter":""}.`),i.length>0&&w(h.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(w(e.apply?`promoting ${h.bold(String(a.length))} hook proposal(s):`:`${h.bold("dry run")} \u2014 would promote ${h.bold(String(a.length))} hook proposal(s):`),w(pt(a.map(Cu),{head:Iu})),i.length>0&&w(h.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){w(""),w(ve.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Eu(s)&&!e.all&&b(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await bw(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let p=0;for(let u of a)await Pu(r,u.hookId)&&(p+=1);w(h.dim(` ${p}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),p<a.length&&(process.exitCode=1)}async function ju(t,e={},n=Cs){t.length===0&&b("retract: name at least one proposal id.");let r=await Os(e,n),s=0;for(let o of t)try{let i=await r.proposalRetract(o);w(ve.success(`${h.bold(o)} ${h.dim(`${i.previousStatus} \u2192`)} ${h.yellow(i.status)}`)),s+=1}catch(i){Gi(i,"retract a hook proposal"),Wi(o,i)}s>0&&w(h.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),s<t.length&&(process.exitCode=1)}async function Lu(t,e={},n=Cs){t.length===0&&b("reject: name at least one proposal id.");let r=await Os(e,n),s=0;for(let o of t)try{let i=await r.proposalReject(o,e.reason);w(ve.success(`${h.bold(o)} ${h.dim(`${i.previousStatus} \u2192`)} ${h.dim(i.status)}`)),s+=1}catch(i){Gi(i,"reject a hook proposal"),Wi(o,i)}s<t.length&&(process.exitCode=1)}Tt();var En=t=>new B(t);async function Pn(t,e){let n=await H(t.baseUrl);return e(n)}async function Ns(t,e,n,r){return r.yes?!0:ze()?await qe(t,[{value:"yes",label:e,description:n},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(D("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(D(h.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function vw(t){return t.visibility!=="published"?h.dim("draft"):t.in_current_release?h.green("live"):h.yellow("unreleased")}function Du(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function kw(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(o=>o.slug.length)),n=[];for(let o of t.items)n.push(`${Du(h.bold(o.slug),e)} ${Du(vw(o),10)} ${o.surfaces.join(",")||h.dim("none")}`),o.description&&n.push(` ${h.dim(o.description)}`);n.push("");let r=t.items.filter(o=>o.visibility==="published"&&o.in_current_release).length,s=t.items.filter(o=>o.visibility!=="published").length;return n.push(`${t.items.length} skill(s) \xB7 ${r} injected \xB7 ${s} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),n}async function Uu(t,e=En){let n={};t.status&&(t.status!=="draft"&&t.status!=="published"&&b(`--status must be 'draft' or 'published' (got '${t.status}').`),n.status=t.status);let r=await Pn(t,e),s;try{s=await J("reading the skills",()=>r.skillsList(n))}catch(o){G(o,"skills:publish","read the instance skills"),b(`could not read the skills: ${o instanceof Error?o.message:String(o)}`)}w(kw(s).join(`
|
|
2104
|
+
`))}async function zu(t,e,n=En){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&b("name at least one skill slug. `turbobase skills list` shows them.");let s=await Pn(e,n);if(!await Ns(`Publish ${r.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await J("publishing",()=>s.skillsPublish(r))}catch(a){G(a,"skills:publish","publish a skill"),b(`publish failed: ${a instanceof Error?a.message:String(a)}`)}w(h.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(D(h.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),D(h.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function qu(t,e,n=En){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&b("name at least one skill slug. `turbobase skills list` shows them.");let s=await Pn(e,n);if(!await Ns(`Move ${r.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>s.skillsUnpublish(r))}catch(a){G(a,"skills:publish","unpublish a skill"),b(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}w(h.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),D(h.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(D(h.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Mu(t,e,n=En){let r=Number(t);(!Number.isInteger(r)||r<1)&&b(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let s=await Pn(e,n);if(await Ns(`Roll the skills back to release v${r}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await J("rolling back",()=>s.skillsRollback(r));w(h.green(`rolled back to v${i.version.version_no}.`))}catch(i){G(i,"skills:publish","roll back a skills release"),b(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Bu(t,e=En){let n=await Pn(t,e),r;try{r=await J("reading the releases",()=>n.skillsReleases())}catch(s){G(s,"skills:publish","read the skills releases"),b(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){D("no releases yet.");return}for(let s of r.items){let o=s.is_current?h.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";w(`${o} v${s.version_no} ${s.skill_count} skill(s) ${h.dim(s.published_at)}${s.published_by?h.dim(` by ${s.published_by}`):""}${h.dim(i)}`)}}async function Fu(t,e,n=En){let r=[...new Set((t??[]).map(p=>p.trim()).filter(Boolean))];r.length===0&&b("name at least one skill to delete. `turbobase skills list` shows the slugs.");let s=await Pn(e,n);if(!await Ns(r.length===1?`Delete the skill '${r[0]}'?`:`Delete ${r.length} skills?
|
|
1913
2105
|
${r.join(`
|
|
1914
|
-
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let
|
|
1915
|
-
`,{mode:384})}async function $w(t){let e=await Wi();e.push(t),await Ld(e)}async function zd(t){let e=await Wi(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await Ld(e),r??null}async function Is(){return Wi()}function Ji(t,e=Date.now()){let n=[],r=[];for(let s of t)pw(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function Dd(t,e){Gi(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new yr(n);let r=fw(e.sample),s=e.now??Date.now(),o=(e.nameGen??(d=>vw(d)))(e.fromTenant),i=Sw(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let d of a){let p=hw(d.rows,r),h=bw(d.table,p,d.classification);h.length>0&&await t.copyRows(i,d.table,h)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:dw(e.ttl,s),sampleFraction:r,url:_w(o,e.baseUrl)};return await $w(l),l}async function Ud(t,e){Gi(t.target());let r=(await Is()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await zd(e),r):null}async function Zi(t,e=Date.now()){Gi(t.target());let n=await Is(),{expired:r}=Ji(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await zd(o.name),s.push(o)}return s}var wr={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},OP=Object.keys(wr).filter(t=>wr[t].mintable);var LP=wr.pat.prefix,xw=Object.entries(wr).map(([t,e])=>[e.prefix,t]),Tw=/^[A-Za-z0-9_-]{20,}$/;function Rw(t){if(typeof t!="string")return null;for(let[e,n]of xw)if(t.startsWith(e)&&Tw.test(t.slice(e.length)))return n;return null}function qd(t){return Rw(t)==="pat"}var vr="bundle.json",Cs="turbobase";function Bd(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let n=e,r=typeof n.version=="number"?n.version:0;if(r!==1)throw new Error(`bundle.json version ${r} is unsupported (expected 1)`);let s=l=>Array.isArray(l)?l:[],o=n.sync??{},i=n.guardrails??{},a={version:1,...typeof n.tenant=="string"?{tenant:n.tenant}:{},hooks:s(n.hooks),conduits:s(n.conduits),sync:{fields:s(o.fields),tables:s(o.tables)},guardrails:{validationHooks:s(i.validationHooks),fieldRules:s(i.fieldRules),conduits:s(i.conduits)},schedules:s(n.schedules)};return Ew(a)}function Ew(t){let e=n=>(r,s)=>n(r)<n(s)?-1:n(r)>n(s)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(n=>n.id)),conduits:[...t.conduits].sort(e(n=>n.id)),sync:{fields:[...t.sync.fields].sort(e(Md)),tables:[...t.sync.tables].sort(e(n=>n.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Md)),conduits:[...t.guardrails.conduits].sort(e(n=>n.conduitId))},schedules:[...t.schedules].sort(e(n=>n.name))}}function Md(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Fd(t,e){let n=(e??"").trim();if(!n)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let r=(t??"").trim();return r?r!==n?{ok:!1,reason:`--confirm "${r}" does not match the target instance "${n}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${n}")`}}lr();var Pw=8e3,Aw={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function Iw(t){return Aw[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Cw(t,e,n=fetch){let r;try{r=await n(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(Pw)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(r.status===200||r.status===403)return{state:"accepted"};if(r.status===401){let o=await r.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(r.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${r.status} \u2014 this host does not serve the /v1 API`}}function Kd(t){return t.state==="accepted"?Te()?g.green("accepted"):"accepted":t.state==="rejected"?Te()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Te()?g.yellow("unreachable"):"unreachable"}async function Hd(t={},e=fetch){let n=await xt(),{file:r}=ws();if(n.length===0){$("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),z(g.dim(`no sign-ins stored in ${r}.`));return}let s=await ut(),o=await Promise.all(n.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await Cw(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)$(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Te())$(Dt(o.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),Kd(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)$(`${i.active?"* ":" "}${i.baseUrl} ${Kd(i.check)} (updated ${i.updatedAt})`);z(g.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(z(g.red(`${i.baseUrl}: ${Iw(i.check.reason)}.`)),z(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&z(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||z("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function ZR(t,e){try{let n=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!n.ok)return null;let r=await n.json();return typeof r.token=="string"&&r.token.length>0?r.token:null}catch{return null}}async function YR(t){let e=await xt();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),We()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Je(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{v("cancelled.")}}async function QR(t,e){let n;try{n=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}function XR(t){z(""),z("Sharing is ON. Two things reach the Turbobase product team from this instance:"),z(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),z(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),z(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),z(" about OUR platform, with instance name, user names and ids masked before they leave."),z(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),z("")}async function e0(t,e,n){let r=await ku({baseUrl:t,token:e}),s=(await xt()).length-1;if($(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),XR(r.baseUrl),!n)return;let o=await QR(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(z(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),z(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),z(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?z(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):z(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function t0(t){let e=await pr(t),n=l=>{let d=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return d?d[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(e),s=n("id");if(r){let l=n("on"),d=n("recordType"),p=n("source");return(!s||!d||!l||!p)&&v(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:s,recordType:d,event:l,source:p,sourceCode:e,extensionKind:"conduit"}}let o=n("recordType"),i=n("event"),a=n("source")??"standalone";return(!s||!o||!i)&&v(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:s,recordType:o,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function tr(t,e,n,r){try{return await re.access(t),"skipped"}catch{}return await re.mkdir(er(t),{recursive:!0}),await re.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await re.chmod(t,r),"wrote"}async function Ug(t,e){if(qg(t)!==".gitignore")return tr(t,e.content,e.executable,e.mode);let n=await re.readFile(t,"utf8").catch(()=>null);if(n===null)return tr(t,e.content,e.executable,e.mode);let r=ed(n);return r===null?"skipped":(await re.writeFile(t,r,"utf8"),"merged")}function Gc(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function n0(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function r0(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function s0(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function Xc({includeInternal:t=!0}={}){let e=new JR;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.19").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",u=>u.command.parent?"":`${Ci()}
|
|
1916
|
-
`),e.hook("preAction",(
|
|
1917
|
-
${
|
|
1918
|
-
`).length} lines).`);return}catch{}
|
|
1919
|
-
`).length} lines).`)}),
|
|
1920
|
-
|
|
1921
|
-
`;await re.writeFile(A,N+(
|
|
2106
|
+
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let p of r)try{i.push(await J(`deleting ${p}`,()=>s.skillsDelete(p)))}catch(u){if(u instanceof X&&u.status===404){a.push(p);continue}i.length>0&&D(h.dim(`deleted before the error: ${i.map(m=>m.slug).join(", ")}`)),G(u,"skills:publish","delete a skill"),b(`delete failed on '${p}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&w(h.green(`deleted ${i.length} skill(s).`));let l=i.filter(p=>p.wasPublished).map(p=>p.slug);l.length>0&&D(h.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(D(h.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Hu}from"node:fs";import{join as Sw,relative as _w,resolve as $w,sep as xw}from"node:path";var Rw=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),Tw=new Set([".mcp.json",".env"]);function Ew(t){return Tw.has(t)||t.startsWith(".env.")&&t!==".env.example"}function Pw(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function Aw(t){return t.includes(0)}async function Ku(t){let e=$w(t),n={},r=[],s=[],o=[];async function i(a){let l=await Hu.readdir(a,{withFileTypes:!0});for(let p of l){let u=Sw(a,p.name);if(p.isDirectory()){if(Rw.has(p.name))continue;await i(u);continue}if(!p.isFile())continue;let m=_w(e,u).split(xw).join("/");if(Ew(p.name)){s.push(m);continue}let x=await Hu.readFile(u);if(!Pw(x)){r.push(m);continue}Aw(x)&&o.push(m),n[m]=x.toString("utf8")}}return await i(e),{files:n,skipped:r,secrets:s,unstorable:o}}import{randomBytes as Iw}from"node:crypto";var Cw="/_tb/app-assets",Ow=16,Nw=/^[0-9a-f]{32}$/;function Vu(){return Iw(Ow).toString("hex")}function jw(t){return Nw.test(t)}function Gu(t){if(!jw(t))throw new Error(`not a build id: ${t}`);return`${Cw}/${t}/`}var Wu=7;import js from"node:fs/promises";import br from"node:path";var Ji={esbuild:"0.28.1","isolated-vm":"6.1.2"},Zi="@turbobase/isolated-vm-prebuilds";function Yi(t,e){return`${t}-${e}`}function Qi(t=process.versions){return`abi${t.modules}`}var Ju=["darwin-x64","win32-arm64"];async function Zu(t){let e=t.platform??process.platform,n=t.arch??process.arch,r=Yi(e,n),s=br.join(t.home,"node_modules"),o=br.join(s,...Zi.split("/"),"prebuilds",r),i=br.join(s,"isolated-vm","prebuilds",r),a;try{a=await js.readdir(o)}catch{return[]}let l=[];await js.mkdir(i,{recursive:!0});for(let p of a){if(!p.endsWith(".node"))continue;let u=br.join(i,p);try{await js.copyFile(br.join(o,p),u,js.constants?.COPYFILE_EXCL??1),l.push(p)}catch{}}return l}import{homedir as Lw}from"node:os";import{join as Yu}from"node:path";import{promises as Xi}from"node:fs";function Xu(){let t=process.env.TURBOBASE_HOME??Yu(Lw(),".turbobase");return{dir:t,file:Yu(t,"sandboxes.json")}}var Dw={s:1e3,m:6e4,h:36e5,d:864e5};function Uw(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let n=Number(e[1]);if(!Number.isFinite(n)||n<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return n*Dw[e[2]]}function zw(t,e=Date.now()){return new Date(e+Uw(t)).toISOString()}function qw(t,e=Date.now()){let n=Date.parse(t);return Number.isNaN(n)?!0:n<=e}function Mw(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let n=Number(e[1]);if(!Number.isFinite(n)||n<0||n>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return n/100}function Bw(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let n=Math.max(1,Math.round(1/e)),r=[];for(let s=0;s<t.length;s+=n)r.push(t[s]);return r}var Fw="[REDACTED]",wr=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},ea=class extends Error{table;column;constructor(e,n,r){super(`Refusing to copy ${e}.${n} into a sandbox: ${r}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=n}};function Hw(t,e,n){let r={};for(let[s,o]of Object.entries(e)){let i=n[s];if(i===void 0)throw new ea(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?r[s]=o==null?o:Fw:r[s]=o}return r}function Kw(t,e,n){return e.map(r=>Hw(t,r,n))}var Qu=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Vw=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function Gw(t){let e=t.trim();try{let s=new URL(e);if(s.hostname)return s.hostname.toLowerCase()}catch{}let n=e.replace(/^[a-z]+:\/\//i,""),r=(n.split("/")[0]??n).split("@").pop()??n;return(r.split(":")[0]??r).toLowerCase()}function ta(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let r of Vw)if(e.includes(r))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${r}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let n=Gw(t);if(!Qu.has(n))throw new Error(`local-only guard: target host '${n}' is not a recognised local Postgres (${[...Qu].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function Ww(t,e=Jw){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Jw(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function Zw(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Yw(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function na(){let{file:t}=Xu();try{let e=await Xi.readFile(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function ep(t){let{dir:e,file:n}=Xu();await Xi.mkdir(e,{recursive:!0}),await Xi.writeFile(n,`${JSON.stringify(t,null,2)}
|
|
2107
|
+
`,{mode:384})}async function Qw(t){let e=await na();e.push(t),await ep(e)}async function tp(t){let e=await na(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await ep(e),r??null}async function Ls(){return na()}function ra(t,e=Date.now()){let n=[],r=[];for(let s of t)qw(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function np(t,e){ta(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new wr(n);let r=Mw(e.sample),s=e.now??Date.now(),o=(e.nameGen??(p=>Ww(p)))(e.fromTenant),i=Zw(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let p of a){let u=Bw(p.rows,r),m=Kw(p.table,u,p.classification);m.length>0&&await t.copyRows(i,p.table,m)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:zw(e.ttl,s),sampleFraction:r,url:Yw(o,e.baseUrl)};return await Qw(l),l}async function rp(t,e){ta(t.target());let r=(await Ls()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await tp(e),r):null}async function sa(t,e=Date.now()){ta(t.target());let n=await Ls(),{expired:r}=ra(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await tp(o.name),s.push(o)}return s}var vr={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},pA=Object.keys(vr).filter(t=>vr[t].mintable);var mA=vr.pat.prefix,Xw=Object.entries(vr).map(([t,e])=>[e.prefix,t]),ev=/^[A-Za-z0-9_-]{20,}$/;function tv(t){if(typeof t!="string")return null;for(let[e,n]of Xw)if(t.startsWith(e)&&ev.test(t.slice(e.length)))return n;return null}function sp(t){return tv(t)==="pat"}var kr="bundle.json",Ds="turbobase";function ip(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let n=e,r=typeof n.version=="number"?n.version:0;if(r!==1)throw new Error(`bundle.json version ${r} is unsupported (expected 1)`);let s=l=>Array.isArray(l)?l:[],o=n.sync??{},i=n.guardrails??{},a={version:1,...typeof n.tenant=="string"?{tenant:n.tenant}:{},hooks:s(n.hooks),conduits:s(n.conduits),sync:{fields:s(o.fields),tables:s(o.tables)},guardrails:{validationHooks:s(i.validationHooks),fieldRules:s(i.fieldRules),conduits:s(i.conduits)},schedules:s(n.schedules)};return nv(a)}function nv(t){let e=n=>(r,s)=>n(r)<n(s)?-1:n(r)>n(s)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(n=>n.id)),conduits:[...t.conduits].sort(e(n=>n.id)),sync:{fields:[...t.sync.fields].sort(e(op)),tables:[...t.sync.tables].sort(e(n=>n.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(op)),conduits:[...t.guardrails.conduits].sort(e(n=>n.conduitId))},schedules:[...t.schedules].sort(e(n=>n.name))}}function op(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function ap(t,e){let n=(e??"").trim();if(!n)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let r=(t??"").trim();return r?r!==n?{ok:!1,reason:`--confirm "${r}" does not match the target instance "${n}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${n}")`}}cr();var rv=8e3,sv={revoked:"the instance REVOKED this token \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",expired:"this token has EXPIRED \u2014 mint a new PAT (Settings \u203A Access tokens) and run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`",unknown:"this instance has never seen this token \u2014 it was deleted, or it belongs to a DIFFERENT instance; check the base-url before minting a new PAT",suspended:"the user this token belongs to is SUSPENDED \u2014 an instance administrator has to restore the account; a new token will not help",malformed:"the stored credential is not shaped like a Turbobase PAT (tb_pat_\u2026) \u2014 sign in again",missing:"no token reached the instance \u2014 sign in again",transient:"the instance could not verify the token right now (a storage error, not a decision about the token) \u2014 retry"};function ov(t){return sv[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function iv(t,e,n=fetch){let r;try{r=await n(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(rv)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(r.status===200||r.status===403)return{state:"accepted"};if(r.status===401){let o=await r.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(r.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${r.status} \u2014 this host does not serve the /v1 API`}}function lp(t){return t.state==="accepted"?Te()?h.green("accepted"):"accepted":t.state==="rejected"?Te()?h.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Te()?h.yellow("unreachable"):"unreachable"}async function cp(t={},e=fetch){let n=await Rt(),{file:r}=ks();if(n.length===0){w("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),D(h.dim(`no sign-ins stored in ${r}.`));return}let s=await ut(),o=await Promise.all(n.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await iv(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)w(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Te())w(pt(o.map(i=>[i.active?h.green("*"):" ",h.bold(i.baseUrl),lp(i.check),h.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)w(`${i.active?"* ":" "}${i.baseUrl} ${lp(i.check)} (updated ${i.updatedAt})`);D(h.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(D(h.red(`${i.baseUrl}: ${ov(i.check.reason)}.`)),D(h.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&D(h.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||D("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function $E(t,e){try{let n=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!n.ok)return null;let r=await n.json();return typeof r.token=="string"&&r.token.length>0?r.token:null}catch{return null}}async function xE(t){let e=await Rt();e.length===0&&b("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ze()||b("this command needs an explicit <base-url> in a non-interactive shell.");try{return await qe(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{b("cancelled.")}}async function RE(t,e){let n;try{n=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}function TE(t){D(""),D("Sharing is ON. Two things reach the Turbobase product team from this instance:"),D(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),D(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),D(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),D(" about OUR platform, with instance name, user names and ids masked before they leave."),D(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),D("")}async function EE(t,e,n){let r=await Pd({baseUrl:t,token:e}),s=(await Rt()).length-1;if(w(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),TE(r.baseUrl),!n)return;let o=await RE(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(D(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),D(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),D(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?D(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):D(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function PE(t){let e=await fr(t),n=l=>{let p=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return p?p[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(e),s=n("id");if(r){let l=n("on"),p=n("recordType"),u=n("source");return(!s||!p||!l||!u)&&b(`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`),{id:s,recordType:p,event:l,source:u,sourceCode:e,extensionKind:"conduit"}}let o=n("recordType"),i=n("event"),a=n("source")??"standalone";return(!s||!o||!i)&&b(`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`),{id:s,recordType:o,event:i,source:a,sourceCode:e,extensionKind:"hook"}}async function nr(t,e,n,r){try{return await re.access(t),"skipped"}catch{}return await re.mkdir(tr(t),{recursive:!0}),await re.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await re.chmod(t,r),"wrote"}async function ry(t,e){if(sy(t)!==".gitignore")return nr(t,e.content,e.executable,e.mode);let n=await re.readFile(t,"utf8").catch(()=>null);if(n===null)return nr(t,e.content,e.executable,e.mode);let r=lu(n);return r===null?"skipped":(await re.writeFile(t,r,"utf8"),"merged")}function td(t){if(t!==void 0){if(t==="junit"||t==="json")return t;b(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function li(t){process.exit(t)}function AE(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function IE(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function CE(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function ad({includeInternal:t=!0}={}){let e=new _E;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.1.21").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${zi()}
|
|
2108
|
+
`),e.hook("preAction",(d,f)=>{pu(e.opts(),f.opts())});let n=e.command("auth").description("Sign in to an instance and manage stored credentials."),r=e.command("project").description("Set up the local project and the files an agent session reads."),s=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),o=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");n.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let f=Xe(d.baseUrl);d.token||b(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
2109
|
+
${mr} auth login --base-url ${f} --token tb_pat_\u2026`),sp(d.token)||b("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await EE(f,d.token,d.verify)}),n.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async d=>cp({probe:d.probe})),n.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let f=d??await xE("Pick the active instance:"),y=await Ss(f);if(!y){let _=await Rt();b(`no stored sign-in for ${Xe(f)}.`+(_.length?` Stored: ${_.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Xe(f)} --token tb_pat_\u2026\`.`)}w(`active instance \u2192 ${y.baseUrl}.`)}),n.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let _=await Rt();for(let S of _)await Ei(S.baseUrl);w(`removed ${_.length} stored sign-in${_.length===1?"":"s"}.`);return}let f=await Ei(d.baseUrl);f||b(d.baseUrl?`no stored sign-in for ${Xe(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let y=await ut();w(`signed out of ${f}.`+(y?` Active instance \u2192 ${y.baseUrl}.`:""))}),r.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:f,token:y}=await H(d.baseUrl),_;try{_=await Dt({baseUrl:f,token:y,recordsOnly:d.recordsOnly})}catch(g){let $=g instanceof Error?g.message:String(g);if(!d.recordsOnly&&/openapi\.json failed \(401/.test($)){let T=await $E(f,y);if(T)try{_=await Dt({baseUrl:f,token:T,recordsOnly:!1});let A=de(process.cwd(),d.out);await re.writeFile(A,_,"utf8"),w(`wrote ${A} (${_.split(`
|
|
2110
|
+
`).length} lines).`);return}catch{}D("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{_=await Dt({baseUrl:f,token:y,recordsOnly:!0})}catch(A){b(`types generation failed: ${A instanceof Error?A.message:String(A)}`)}}else b(`types generation failed: ${$}`)}let S=de(process.cwd(),d.out);await re.writeFile(S,_,"utf8"),w(`wrote ${S} (${_.split(`
|
|
2111
|
+
`).length} lines).`)}),mu(r),r.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:f,token:y}=await H(d.baseUrl),_=new URLSearchParams;d.records&&_.set("records",d.records),d.query&&_.set("query",d.query);let S=_.toString(),g=await fetch(`${f}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${y}`,Accept:"application/json"}});g.ok||b(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let T=((await g.json()).markdown??"").trim(),A=de(process.cwd(),d.out),C=d.records?` records=${d.records}`:"",N=`<!-- GENERATED by \`turbobase project grounding\` against ${f}${C} \u2014 do not edit; re-run to refresh. -->
|
|
2112
|
+
|
|
2113
|
+
`;await re.writeFile(A,N+(T?`${T}
|
|
1922
2114
|
`:`(no grounding available yet)
|
|
1923
|
-
`),"utf8")
|
|
1924
|
-
${E===0?g.green(A):g.yellow(A)}`),E>0&&process.exit(1)}),s.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(u,f)=>{if(f.to){let x=await Wc(),{baseUrl:E,token:A}=await V(f.baseUrl),C=new F({baseUrl:E,token:A});try{let N=await W(`applying bundle to ${f.to}`,()=>C.configApply(x));$(`applied bundle to ${f.to}: +${N.applied.add} ~${N.applied.change} -${N.applied.destroy}`+(N.backfillsQueued.length?` (${N.backfillsQueued.length} backfill(s) queued)`:""))}catch(N){N instanceof ne&&N.status===403&&v("apply forbidden (403) \u2014 the stored PAT is not for an admin."),v(`bundle apply failed: ${N instanceof Error?N.message:String(N)}`)}return}u||v("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:b,token:S}=await V(f.baseUrl),k=await t0(ue(process.cwd(),u)),m=new F({baseUrl:b,token:S});try{let x=await W(`deploying ${qg(u)}`,()=>m.deploy(k));Te()?$(zt("Deployed",[`${g.bold(x.id)} ${Sn(x.status)} ${g.dim(x.outcome)}`])):$(`deployed ${x.id} \u2192 status=${x.status} (${x.outcome}).`)}catch(x){x instanceof ne&&x.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),v(`deploy failed: ${x instanceof Error?x.message:String(x)}`)}});let l=e.command("apps").description("Manage hosted apps served in your Turbobase app.");l.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").action(async(u,f,b)=>{let S=!!(b.preview||b.replace),k=ue(process.cwd(),f??".");await re.mkdir(k,{recursive:!0});let m=b.proposal??await T(k),{baseUrl:x,token:E}=await V(b.baseUrl),A=new F({baseUrl:x,token:E}),C=!1;try{C=(await A.appsList()).some(fe=>fe.slug===u||fe.id===u)}catch(fe){Z(fe,"extensions:deploy","deploy"),v(`could not reach ${x}: ${fe instanceof Error?fe.message:String(fe)}`)}if(!C){b.create||v(`no app "${u}" on ${x} \u2014 create it with \`turbobase apps create ${u}\`, or pass --create.`);let fe=await W(`creating app ${u}`,()=>p(x,E,{slug:u},{tolerateExisting:!0}));fe.existed||$(`created ${fe.slug??u}.`)}let N;if(b.replace)if(typeof b.replace=="string")N=b.replace;else{let{previews:fe}=await se(x,E,u);if(fe.length===0&&v(`no open preview on ${u} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),fe.length>1){for(let Ce of fe)$(` ${Ce.previewId} v${Ce.version}${Ce.label?` ${Ce.label}`:""} ${Ce.url}`);v(`${u} has ${fe.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${fe[0].previewId}\`.`)}N=fe[0].previewId}let G=fe=>re.stat(Ye(k,fe)).then(()=>!0).catch(()=>!1),O=u,Q=k,pe=b.build!==!1;if(pe&&!await G("package.json"))if(await G("index.html"))$("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),pe=!1;else if(b.pull===!1)v(`${k} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let fe=await W(`pulling ${u}`,()=>h(x,E,u));O=fe.slug??u,await _(k,fe.files,!0),$(`pulled generated source (rev ${fe.rev}).`)}let he;if(pe){let fe=Ed();if(he={buildId:fe,assetBase:Pd(fe)},b.install!==!1&&!await G("node_modules")){$("installing dependencies\u2026");try{await P(["install"],k)}catch(Ce){v(`npm install failed: ${Ce instanceof Error?Ce.message:String(Ce)}`)}}$("building\u2026");try{await P(["run","build"],k,{TURBOBASE_ASSET_BASE:he.assetBase})}catch(Ce){v(`build failed: ${Ce instanceof Error?Ce.message:String(Ce)}`)}await G("dist")||v(`no dist/ after build in ${k} \u2014 check the app's build script.`),Q=Ye(k,"dist")}S&&!he&&v(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${O}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let Ie=await H(x,E,O,Q,b.entry,m,he,S?{label:b.label,replacePreviewId:N}:void 0);if(S){let fe=Ie.previewUrl??"(no url returned)",Ce=Ie.expiresAt?new Date(Ie.expiresAt).toLocaleDateString():`${Ad} days`,or=Ie.replacedVersion==null?null:`replaced v${Ie.replacedVersion} \u2014 same URL`;if(Te())$(zt(or?"Preview replaced":"Preview deployed",[`${g.bold(O)} ${g.green(`v${Ie.version??"?"}`)} ${g.dim("not live")}`,`${g.bold(fe)}`,...or?[g.dim(or)]:[],g.dim(`expires ${Ce}`)]));else{let Fg=or?`; ${or}`:"";$(`preview ${O} v${Ie.version??"?"} \u2192 ${fe} (expires ${Ce}; /a/${O} unchanged${Fg}).`)}$(`next: turbobase apps promote ${O} ${Ie.previewId??"<preview-id>"} # make it live`),$(` turbobase apps preview discard ${Ie.previewId??"<preview-id>"}`);return}Te()?$(zt("Deployed",[`${g.bold(O)} ${g.green(`v${Ie.version??"?"}`)} ${g.dim(Ie.url??`/a/${O}`)}`])):$(`deployed ${O} \u2192 v${Ie.version??"?"} (${Ie.url??`/a/${O}`}).`),await Le(Ie,k)}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,f,b)=>{let{baseUrl:S,token:k}=await V(b.baseUrl),m=await W(`promoting ${f}`,()=>D(S,k,u,"promote",{previewId:f}));Te()?$(zt("Promoted",[`${g.bold(u)} ${g.green(`v${m.version??"?"}`)} ${g.dim(m.url??`/a/${u}`)}`])):$(`promoted ${u} \u2192 v${m.version??"?"} is now live at ${m.url??`/a/${u}`}.`),await Le(m)});let d=l.command("preview").description("Inspect and manage an app's open previews.");d.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,f)=>{let{baseUrl:b,token:S}=await V(f.baseUrl),k=await se(b,S,u);if(k.previews.length===0){$(`no open previews for ${u}.`);return}for(let m of k.previews){let x=m.label?` ${m.label}`:"",E=m.expiresAt?new Date(m.expiresAt).toLocaleDateString():"?";$(`v${m.version} ${m.previewId}${x} ${m.url} (expires ${E})`)}}),d.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,f,b)=>{let{baseUrl:S,token:k}=await V(b.baseUrl);await W(`discarding ${f}`,()=>D(S,k,u,"discard",{previewId:f})),$(`discarded ${f}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,f)=>{let{baseUrl:b,token:S}=await V(f.baseUrl),k=await W(`creating ${u}`,()=>p(b,S,{slug:u,name:f.name,description:f.description})),m=k.slug??u;Te()?$(zt("Created",[`${g.bold(m)} ${g.dim(k.url??`/a/${m}`)}`])):$(`created ${m} (${k.url??`/a/${m}`}).`),$(`next: turbobase apps push ${m} . # store the source`),$(` turbobase apps deploy ${m} # build + go live`)});async function p(u,f,b,S={}){let k=`${u.replace(/\/+$/,"")}/v1/apps`,m;try{m=await fetch(k,{method:"POST",headers:{Authorization:`Bearer ${f}`,"content-type":"application/json"},body:JSON.stringify({slug:b.slug,name:b.name??b.slug,description:b.description})})}catch(x){v(`create request failed: ${x instanceof Error?x.message:String(x)}`)}if(m.status===401&&v("create unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&v("create forbidden (403) \u2014 the PAT is not for an admin."),m.status===409){if(S.tolerateExisting)return{slug:b.slug,existed:!0};v(`an app with slug "${b.slug}" already exists.`)}return m.ok||v(`create failed: HTTP ${m.status} ${(await m.text().catch(()=>"")).slice(0,200)}`),await m.json().catch(()=>({}))}async function h(u,f,b){let S=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/pull`,k;try{k=await fetch(S,{headers:{Authorization:`Bearer ${f}`}})}catch(m){v(`pull request failed: ${m instanceof Error?m.message:String(m)}`)}return k.status===401&&v("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),k.status===403&&v("pull forbidden (403) \u2014 the PAT is not for an admin."),k.status===404&&v(`no generated source for "${b}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),k.ok||v(`pull failed: HTTP ${k.status} ${(await k.text().catch(()=>"")).slice(0,200)}`),await k.json()}async function _(u,f,b){let S=ue(u),k=0;for(let[m,x]of Object.entries(f)){let E=ue(S,m);E!==S&&!E.startsWith(S+Yc)&&v(`refusing to write outside ${S}: ${m}`),b||await re.stat(E).then(()=>!0).catch(()=>!1)&&v(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(er(E),{recursive:!0}),await re.writeFile(E,x,"utf8"),k+=1}return k}function y(u){let f=u.indexOf(","),b=u.startsWith("data:")?f>=0?u.slice(f+1):"":u;if(!b)return null;try{let S=Buffer.from(b,"base64");return S.length>0?new Uint8Array(S):null}catch{return null}}async function w(u,f,b){let S=ue(u),k=async(x,E)=>{let A=ue(S,x);A!==S&&!A.startsWith(S+Yc)&&v(`refusing to write outside ${S}: ${x}`),b||await re.stat(A).then(()=>!0).catch(()=>!1)&&v(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(er(A),{recursive:!0}),await re.writeFile(A,E)},m=`# ${f.title||"App change request"}
|
|
2115
|
+
`),"utf8"),w(`wrote ${A}${T?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),o.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${gr.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each page\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Plan every finding on its own instead of merging the ones that look related \u2014 N findings for one page become N sequential appends.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>bu(d)),o.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>vu(d)),o.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>ku(d,f)),o.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Su(d,f)),o.command("versions").description("List knowledge-base releases, newest first, marking the current one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>_u(d)),o.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>$u(d,f)),o.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>xu(d,f)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>Ru(d)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>Uu(d)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>zu(d,f)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>qu(d,f)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Bu(d)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Mu(d,f)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Fu(d,f));let a=s.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async d=>{let f;try{f=Mt("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(S){b(S instanceof Error?S.message:String(S))}let y=de(process.cwd(),f.relativePath);await nr(y,f.content)==="skipped"&&b(`refusing to overwrite existing file: ${y}`),w(`wrote ${y}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let f;try{f=Mt("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(S){b(S instanceof Error?S.message:String(S))}let y=de(process.cwd(),f.relativePath);await nr(y,f.content)==="skipped"&&b(`refusing to overwrite existing file: ${y}`),w(`wrote ${y}`)}),s.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(d,f)=>{let y=td(f.reporter),_=await fr(de(process.cwd(),d)),S=de(process.cwd(),f.samples),g=await pr(S);g.length===0&&!y&&w(`no samples found under ${S} \u2014 add JSON fixtures to dry-run against.`);let $;try{$=await xs(_,g.map(C=>C.fixture))}catch(C){b(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(y){let C=AE($);w(Ts(C,y)),li(C.cases.some(N=>N.status==="failed")?1:0)}let T=0;for(let C of $){let N=C.pass?h.green("PASS"):h.red("FAIL");C.pass||(T+=1);let W=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";w(` ${N} ${C.name}${W}`)}let A=`${$.length-T}/${$.length} sample(s) passed.`;w(`
|
|
2116
|
+
${T===0?h.green(A):h.yellow(A)}`),li(T>0?1:0)}),s.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE bundle (turbobase/bundle.json) to this env (sandbox|prod).").action(async(d,f)=>{if(f.to){let $=await nd(),{baseUrl:T,token:A}=await H(f.baseUrl),C=new B({baseUrl:T,token:A});try{let N=await J(`applying bundle to ${f.to}`,()=>C.configApply($));w(`applied bundle to ${f.to}: +${N.applied.add} ~${N.applied.change} -${N.applied.destroy}`+(N.backfillsQueued.length?` (${N.backfillsQueued.length} backfill(s) queued)`:""))}catch(N){N instanceof X&&N.status===403&&b("apply forbidden (403) \u2014 the stored PAT is not for an admin."),b(`bundle apply failed: ${N instanceof Error?N.message:String(N)}`)}return}d||b("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:y,token:_}=await H(f.baseUrl),S=await PE(de(process.cwd(),d)),g=new B({baseUrl:y,token:_});try{let $=await J(`deploying ${sy(d)}`,()=>g.deploy(S));Te()?w(zt("Deployed",[`${h.bold($.id)} ${_n($.status)} ${h.dim($.outcome)}`])):w(`deployed ${$.id} \u2192 status=${$.status} (${$.outcome}).`)}catch($){$ instanceof X&&$.status===403&&b("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),b(`deploy failed: ${$ instanceof Error?$.message:String($)}`)}});let l=e.command("apps").description("Manage hosted apps served in your Turbobase app.");l.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").action(async(d,f,y)=>{let _=!!(y.preview||y.replace),S=de(process.cwd(),f??".");await re.mkdir(S,{recursive:!0});let g=y.proposal??await R(S),{baseUrl:$,token:T}=await H(y.baseUrl),A=new B({baseUrl:$,token:T}),C=!1;try{C=(await A.appsList()).some(fe=>fe.slug===d||fe.id===d)}catch(fe){G(fe,"extensions:deploy","deploy"),b(`could not reach ${$}: ${fe instanceof Error?fe.message:String(fe)}`)}if(!C){y.create||b(`no app "${d}" on ${$} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let fe=await J(`creating app ${d}`,()=>u($,T,{slug:d},{tolerateExisting:!0}));fe.existed||w(`created ${fe.slug??d}.`)}let N;if(y.replace)if(typeof y.replace=="string")N=y.replace;else{let{previews:fe}=await se($,T,d);if(fe.length===0&&b(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),fe.length>1){for(let Oe of fe)w(` ${Oe.previewId} v${Oe.version}${Oe.label?` ${Oe.label}`:""} ${Oe.url}`);b(`${d} has ${fe.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${fe[0].previewId}\`.`)}N=fe[0].previewId}let W=fe=>re.stat(Qe(S,fe)).then(()=>!0).catch(()=>!1),O=d,Q=S,pe=y.build!==!1;if(pe&&!await W("package.json"))if(await W("index.html"))w("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),pe=!1;else if(y.pull===!1)b(`${S} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let fe=await J(`pulling ${d}`,()=>m($,T,d));O=fe.slug??d,await x(S,fe.files,!0),w(`pulled generated source (rev ${fe.rev}).`)}let he;if(pe){let fe=Vu();if(he={buildId:fe,assetBase:Gu(fe)},y.install!==!1&&!await W("node_modules")){w("installing dependencies\u2026");try{await P(["install"],S)}catch(Oe){b(`npm install failed: ${Oe instanceof Error?Oe.message:String(Oe)}`)}}w("building\u2026");try{await P(["run","build"],S,{TURBOBASE_ASSET_BASE:he.assetBase})}catch(Oe){b(`build failed: ${Oe instanceof Error?Oe.message:String(Oe)}`)}await W("dist")||b(`no dist/ after build in ${S} \u2014 check the app's build script.`),Q=Qe(S,"dist")}_&&!he&&b(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${O}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let Ce=await V($,T,O,Q,y.entry,g,he,_?{label:y.label,replacePreviewId:N}:void 0);if(_){let fe=Ce.previewUrl??"(no url returned)",Oe=Ce.expiresAt?new Date(Ce.expiresAt).toLocaleDateString():`${Wu} days`,ir=Ce.replacedVersion==null?null:`replaced v${Ce.replacedVersion} \u2014 same URL`;if(Te())w(zt(ir?"Preview replaced":"Preview deployed",[`${h.bold(O)} ${h.green(`v${Ce.version??"?"}`)} ${h.dim("not live")}`,`${h.bold(fe)}`,...ir?[h.dim(ir)]:[],h.dim(`expires ${Oe}`)]));else{let ay=ir?`; ${ir}`:"";w(`preview ${O} v${Ce.version??"?"} \u2192 ${fe} (expires ${Oe}; /a/${O} unchanged${ay}).`)}w(`next: turbobase apps promote ${O} ${Ce.previewId??"<preview-id>"} # make it live`),w(` turbobase apps preview discard ${Ce.previewId??"<preview-id>"}`);return}Te()?w(zt("Deployed",[`${h.bold(O)} ${h.green(`v${Ce.version??"?"}`)} ${h.dim(Ce.url??`/a/${O}`)}`])):w(`deployed ${O} \u2192 v${Ce.version??"?"} (${Ce.url??`/a/${O}`}).`),await De(Ce,S)}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f,y)=>{let{baseUrl:_,token:S}=await H(y.baseUrl),g=await J(`promoting ${f}`,()=>U(_,S,d,"promote",{previewId:f}));Te()?w(zt("Promoted",[`${h.bold(d)} ${h.green(`v${g.version??"?"}`)} ${h.dim(g.url??`/a/${d}`)}`])):w(`promoted ${d} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${d}`}.`),await De(g)});let p=l.command("preview").description("Inspect and manage an app's open previews.");p.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=await se(y,_,d);if(S.previews.length===0){w(`no open previews for ${d}.`);return}for(let g of S.previews){let $=g.label?` ${g.label}`:"",T=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";w(`v${g.version} ${g.previewId}${$} ${g.url} (expires ${T})`)}}),p.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f,y)=>{let{baseUrl:_,token:S}=await H(y.baseUrl);await J(`discarding ${f}`,()=>U(_,S,d,"discard",{previewId:f})),w(`discarded ${f}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=await J(`creating ${d}`,()=>u(y,_,{slug:d,name:f.name,description:f.description})),g=S.slug??d;Te()?w(zt("Created",[`${h.bold(g)} ${h.dim(S.url??`/a/${g}`)}`])):w(`created ${g} (${S.url??`/a/${g}`}).`),w(`next: turbobase apps push ${g} . # store the source`),w(` turbobase apps deploy ${g} # build + go live`)});async function u(d,f,y,_={}){let S=`${d.replace(/\/+$/,"")}/v1/apps`,g;try{g=await fetch(S,{method:"POST",headers:{Authorization:`Bearer ${f}`,"content-type":"application/json"},body:JSON.stringify({slug:y.slug,name:y.name??y.slug,description:y.description})})}catch($){b(`create request failed: ${$ instanceof Error?$.message:String($)}`)}if(g.status===401&&b("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&b("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if(_.tolerateExisting)return{slug:y.slug,existed:!0};b(`an app with slug "${y.slug}" already exists.`)}return g.ok||b(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function m(d,f,y){let _=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/pull`,S;try{S=await fetch(_,{headers:{Authorization:`Bearer ${f}`}})}catch(g){b(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return S.status===401&&b("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&b("pull forbidden (403) \u2014 the PAT is not for an admin."),S.status===404&&b(`no generated source for "${y}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),S.ok||b(`pull failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json()}async function x(d,f,y){let _=de(d),S=0;for(let[g,$]of Object.entries(f)){let T=de(_,g);T!==_&&!T.startsWith(_+od)&&b(`refusing to write outside ${_}: ${g}`),y||await re.stat(T).then(()=>!0).catch(()=>!1)&&b(`${T} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(tr(T),{recursive:!0}),await re.writeFile(T,$,"utf8"),S+=1}return S}function v(d){let f=d.indexOf(","),y=d.startsWith("data:")?f>=0?d.slice(f+1):"":d;if(!y)return null;try{let _=Buffer.from(y,"base64");return _.length>0?new Uint8Array(_):null}catch{return null}}async function k(d,f,y){let _=de(d),S=async($,T)=>{let A=de(_,$);A!==_&&!A.startsWith(_+od)&&b(`refusing to write outside ${_}: ${$}`),y||await re.stat(A).then(()=>!0).catch(()=>!1)&&b(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(tr(A),{recursive:!0}),await re.writeFile(A,T)},g=`# ${f.title||"App change request"}
|
|
1925
2117
|
|
|
1926
2118
|
> Widget proposal \`${f.proposalId}\` \u2014 build this change, then ship it with
|
|
1927
2119
|
> \`turbobase apps deploy ${f.appSlug}\`. The deploy stamps this proposal complete.
|
|
@@ -1931,34 +2123,34 @@ ${f.bodyMarkdown||"_No description provided._"}
|
|
|
1931
2123
|
## Screen context
|
|
1932
2124
|
|
|
1933
2125
|
`+(f.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
|
|
1934
|
-
`);if(await
|
|
1935
|
-
`)}async function T(u){try{let f=await re.readFile(Ye(u,".turbobase","proposal.json"),"utf8"),b=JSON.parse(f);return typeof b.proposalId=="string"&&b.proposalId?b.proposalId:void 0}catch{return}}async function R(u,f,b,S,k,m){let x=new F({baseUrl:u,token:f});try{return await x.appsPush(b,S,{note:k,proposalId:m})}catch(E){if(E instanceof ne){let A=E.body;if(E.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&Z(E,"extensions:deploy","push app source"),E.status===404&&v(`no app "${b}" on this instance \u2014 create it with \`turbobase apps create ${b}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let C=A?.path?` in ${A.path}`:"",N=A?.reason?` (${A.reason})`:"";v(`push rejected: ${A?.error??"bad request"}${N}${C}.`)}}v(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function P(u,f,b){return new Promise((S,k)=>{let m=Qc("npm",u,{cwd:f,stdio:"inherit",...b?{env:{...process.env,...b}}:{}});m.on("error",k),m.on("exit",x=>x===0?S():k(new Error(`npm ${u.join(" ")} exited ${x??"?"}`)))})}async function I(u,f,b,S){let k=`${u.replace(/\/+$/,"")}${b}`,m;try{m=await fetch(k,{method:S.method,headers:{Authorization:`Bearer ${f}`,...S.body?{"content-type":"application/json"}:{}},...S.body?{body:JSON.stringify(S.body)}:{}})}catch(x){v(`request failed: ${x instanceof Error?x.message:String(x)}`)}if(m.status===401&&v("unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&v("forbidden (403) \u2014 the PAT is not for an admin."),!m.ok){let x=await m.text().catch(()=>""),E=x.slice(0,300);try{let A=JSON.parse(x);E=A.message??A.error??E}catch{}v(`failed: HTTP ${m.status} ${E}`)}return await m.json().catch(()=>({}))}async function D(u,f,b,S,k){return await I(u,f,`/v1/apps/${encodeURIComponent(b)}/preview/${S}`,{method:"POST",body:k})}async function se(u,f,b){return{previews:(await I(u,f,`/v1/apps/${encodeURIComponent(b)}/previews`,{method:"GET"})).previews??[]}}async function H(u,f,b,S,k,m,x,E){let A;try{A=await W(`zipping ${S}`,()=>Du(S))}catch(O){v(`could not zip ${S}: ${O instanceof Error?O.message:String(O)}`)}A.fileCount===0&&v(`${S} is empty \u2014 the build produced nothing.`);let C={Authorization:`Bearer ${f}`,"Content-Type":"application/zip"};k&&(C["x-app-entry"]=k),m&&(C["x-proposal-id"]=m),x&&(C["x-app-build-id"]=x.buildId,C["x-app-asset-base"]=x.assetBase),E&&(C["x-app-channel"]="preview",E.label&&(C["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(C["x-app-preview-replace"]=E.replacePreviewId));let N=`${u.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/deploy`,G;try{G=await W(`deploying ${b} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(N,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(O){v(`deploy request failed: ${O instanceof Error?O.message:String(O)}`)}if(G.status===401&&v("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),G.status===403&&v("deploy forbidden (403) \u2014 the PAT is not for an admin."),G.status===404){let O=await G.text().catch(()=>""),Q={};try{Q=JSON.parse(O)}catch{}Q.error==="no_preview"&&v(`${Q.message??`no open preview to replace on ${b}`} \u2014 list them with \`turbobase apps preview list ${b}\`.`),v(`no app "${b}" on ${u} \u2014 create it with \`turbobase apps create ${b}\`.`)}if(!G.ok){let O=await G.text().catch(()=>""),Q=O.slice(0,300);try{let pe=JSON.parse(O);Q=pe.message??pe.error??Q}catch{}v(`deploy failed: HTTP ${G.status} ${Q}`)}return await G.json().catch(()=>({}))}async function Le(u,f){let b=Zu(u,{localDocsModifiedAt:await Be(f)});b&&$(b.level==="warn"?g.yellow(b.message):g.dim(b.message))}async function Be(u){if(!u)return null;let f=null;for(let b of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let S=await re.stat(Ye(u,b));(f===null||S.mtimeMs>f)&&(f=S.mtimeMs)}catch{}return f===null?null:new Date(f)}l.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(u,f,b)=>{let{baseUrl:S,token:k}=await V(b.baseUrl);if(b.proposal){let A=new F({baseUrl:S,token:k}),C;try{C=await W(`fetching proposal ${b.proposal}`,()=>A.appPullContext(b.proposal))}catch(pe){Z(pe,"extensions:deploy","pull proposal"),pe instanceof ne&&pe.status===404&&v(`no widget proposal "${b.proposal}" on ${S}.`),v(`could not fetch proposal ${b.proposal}: ${pe instanceof Error?pe.message:String(pe)}`)}let N=await W(`pulling ${C.appSlug}`,()=>h(S,k,C.appSlug)),G=f??u,O=ue(process.cwd(),G??C.appSlug);await re.mkdir(O,{recursive:!0});let Q=await _(O,N.files,!!b.force);await w(O,C,!!b.force),$(`pulled ${Q} file${Q===1?"":"s"} \u2192 ${O} (rev ${N.rev}), linked to proposal ${C.proposalId}.`),$(`next: cd ${ri(process.cwd(),O)||"."} && turbobase apps deploy ${C.appSlug}`);return}u||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let m=await W(`pulling ${u}`,()=>h(S,k,u)),x=ue(process.cwd(),f??m.slug??u);await re.mkdir(x,{recursive:!0});let E=await _(x,m.files,!!b.force);$(`pulled ${E} file${E===1?"":"s"} \u2192 ${x} (rev ${m.rev}).`),$(`next: cd ${ri(process.cwd(),x)||"."} && turbobase apps deploy ${m.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(u,f,b)=>{let S=ue(process.cwd(),f??u),k=await ut(b.baseUrl).catch(()=>null),{scaffoldAppFiles:m,starterApp:x}=await Promise.resolve().then(()=>(ip(),op)),E=b.title??u,A=m({slug:u,title:E,appTsx:x(E),instanceOrigin:k?.baseUrl});await re.mkdir(S,{recursive:!0});let C=await _(S,A,!!b.force);if($(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${S}`),b.claude!==!1){let G=Li({baseUrl:k?.baseUrl,token:k?.token,appSlug:u}),O=0;for(let Q of G){let pe=await Ug(Ye(S,Q.path),Q);(pe==="wrote"||pe==="merged")&&(O+=1)}$(`wired Claude Code: ${O} file${O===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),k||z("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let N=ri(process.cwd(),S)||".";$(`next: cd ${N} && npm install && npm run dev`),$(` turbobase apps create ${u}`),$(` turbobase apps push ${u} .`),$(` turbobase apps deploy ${u} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:f,token:b}=await V(u.baseUrl),S=new F({baseUrl:f,token:b}),k;try{k=await S.appsList()}catch(m){Z(m,"extensions:deploy","list apps"),v(`list apps failed: ${m instanceof Error?m.message:String(m)}`)}if(u.json)return $(JSON.stringify(k,null,2));if(k.length===0)return $("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");$(Dt(k.map(m=>[m.slug,m.name,m.deployed?"yes":"no",m.sourceRev===null?"\u2014":`rev ${m.sourceRev}`,m.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(u,f,b)=>{let S=ue(process.cwd(),f??".");await re.stat(S).then(he=>he.isDirectory()).catch(()=>!1)||v(`${S} is not a directory.`);let{baseUrl:m,token:x}=await V(b.baseUrl),E=b.proposal??await T(S),{files:A,skipped:C,secrets:N,unstorable:G}=await Rd(S),O=Object.keys(A).length;if(O===0&&v(`no source files found under ${S} (build output and node_modules are skipped).`),G.length>0){for(let he of G)z(`${he} contains a NUL byte (U+0000), which cannot be stored.`);v(`push aborted: ${G.length} ${G.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let he of C)z(g.dim(`skipped binary file ${he}`));for(let he of N)z(g.dim(`skipped ${he} (holds credentials \u2014 never pushed)`));let Q=await W(`pushing ${O} file${O===1?"":"s"}`,()=>R(m,x,u,A,b.note,E));$(`pushed ${Q.files} file${Q.files===1?"":"s"} \u2192 ${Q.slug} rev ${Q.rev} (source only, nothing deployed).`);let pe=await gr(new F({baseUrl:m,token:x}),Q.slug);pe&&pe.entriesAdded>0&&$(`${pe.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),$(`next: turbobase apps deploy ${Q.slug}`)}),s.command("plan").description("Diff the local bundle (turbobase/bundle.json) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async u=>{let f=await Wc(),{baseUrl:b,token:S}=await V(u.baseUrl),k=new F({baseUrl:b,token:S}),m;try{m=await W(`planning against ${u.to??b}`,()=>k.configPlan(f))}catch(x){v(`plan failed: ${x instanceof Error?x.message:String(x)}`)}i0(m,u.to??b)}),s.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").action(async u=>{let f=await Wc(),{baseUrl:b,token:S}=await V(u.baseUrl),k=f.tenant??a0(b),m=Fd(u.confirm,k);m.ok||v(`promote refused (fail-closed): ${m.reason}`);let x=new F({baseUrl:b,token:S});try{let E=await W(`promoting ${u.from} \u2192 ${u.to} (${k})`,()=>x.configApply(f));if(Te()){let A=[`${g.bold(`${u.from} \u2192 ${u.to}`)} ${g.dim(k??"")}`,`${Lt.add(String(E.applied.add))} ${Lt.change(String(E.applied.change))} ${Lt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&A.push(g.dim(`${E.backfillsQueued.length} backfill(s) queued`)),$(zt("Promoted",A))}else $(`promoted ${u.from} \u2192 ${u.to} (${k}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""))}catch(E){E instanceof ne&&E.status===403&&v("promote forbidden (403) \u2014 the stored PAT is not for an admin."),v(`promote failed: ${E instanceof Error?E.message:String(E)}`)}});let nr=async(u,f)=>{let{baseUrl:b,token:S}=await V(f.baseUrl),k=new F({baseUrl:b,token:S}),m=f.limit?Number(f.limit):void 0;if(f.follow){try{await Gu(k,u,{follow:!0,limit:m,intervalMs:f.intervalMs?Number(f.intervalMs):void 0,sink:$})}catch(x){v(`logs --follow failed: ${x instanceof Error?x.message:String(x)}`)}return}try{let x=await k.logs(u,m);x.length===0&&$(`no logs for ${u}.`);for(let E of x)$(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(x){v(`logs failed: ${x instanceof Error?x.message:String(x)}`)}};s.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(nr),s.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(u,f)=>{let b=Gc(f.reporter),S=ue(process.cwd(),u),k=await pr(S),m=qu(k);b?$(xs(r0(u,m),b)):$(Mu(u,m,{warn:g.yellow,ok:g.green,dim:g.dim})),f.ci&&m.warnings.length>0&&process.exit(1)}),s.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(u,f)=>{let b=Gc(f.reporter),S=await Cu(ue(process.cwd(),u));if(f.against){f.against!=="sandbox"&&v(`unknown --against target '${f.against}' (only 'sandbox' is supported).`);try{await Au(Ei(S))}catch(x){v(x instanceof Error?x.message:String(x))}return}f.fixture||v("replay needs a --fixture <file> (offline) or --against sandbox (online).");let k;try{k=await Iu(ue(process.cwd(),f.fixture))}catch(x){v(`could not read fixture ${f.fixture}: ${x instanceof Error?x.message:String(x)}`)}let m=await Pu(S,k,f.fixture);if(b){let x=s0(m);$(xs(x,b)),x.cases.some(E=>E.status==="failed")&&process.exit(1);return}$(Ou(m,!!f.trace)),m.error&&process.exit(1)}),s.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async u=>{let{baseUrl:f,token:b}=await V(u.baseUrl),S=new F({baseUrl:f,token:b});try{await Wu(S,{status:u.status,retry:u.retry,limit:u.limit?Number(u.limit):void 0,sink:$})}catch(k){k instanceof ne&&k.status===403&&v("forbidden (403) \u2014 binding --retry requires an admin PAT."),k instanceof ne&&k.status===409&&v("binding is not retryable (only divergent/blocked bindings can be retried)."),v(`ext binding failed: ${k instanceof Error?k.message:String(k)}`)}}),s.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(u,f)=>{let b=u.lastIndexOf("@"),S=b>0?u.slice(0,b):u,k=b>0?u.slice(b+1):void 0,m=Si();m||v(`marketplace not configured \u2014 set ${wn} and ${ks}.
|
|
1936
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
1937
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
1938
|
-
project init: ${
|
|
1939
|
-
project ci: ${f} written, ${
|
|
1940
|
-
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`)
|
|
1941
|
-
`;
|
|
1942
|
-
samples init: ${
|
|
1943
|
-
`+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));$(Dt(k.map(en),{head:rr})),$(g.dim(" first match wins; lower PRIO is evaluated first."))}),yt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",u=>Number(u)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,f)=>{let{baseUrl:b,token:S}=await V(f.baseUrl),k=new F({baseUrl:b,token:S}),m;try{m=await k.guardrailCreate({name:u,source:f.source,record:f.record,decision:f.decision,...f.op?{op:f.op}:{},...f.target?{target:f.target}:{},...f.actor?{actor:f.actor}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when?{when:f.when}:{},...f.reason?{reason:f.reason}:{},...f.disabled?{enabled:!1}:{},...f.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(x){Z(x,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${x instanceof Error?x.message:String(x)}`)}$(`${g.green("\u2713")} guardrail ${g.bold(m.name??m.id)} created${m.status==="active"?"":g.dim(` (${m.status} \u2014 activate it to take effect)`)}`),$(g.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.actor?` actor=${m.actor}`:""}${m.when?` where ${m.when}`:""} @prio ${m.priority}`)),$(g.dim(` verify with: turbobase guardrails test --source ${m.source==="*"?"<source>":m.source} --record <record>`))}),yt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",u=>Number(u)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,f)=>{f.decision===void 0&&f.priority===void 0&&f.when===void 0&&f.reason===void 0&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:b,token:S}=await V(f.baseUrl),k=new F({baseUrl:b,token:S}),m;try{m=await k.guardrailUpdate(u,{...f.decision!==void 0?{decision:f.decision}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when!==void 0?{when:f.when}:{},...f.reason!==void 0?{reason:f.reason}:{}})}catch(x){Z(x,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${x instanceof Error?x.message:String(x)}`)}$(`${g.green("\u2713")} guardrail ${g.bold(m.name??m.id)} updated`),$(g.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.when?` where ${m.when}`:""} @prio ${m.priority}`))});for(let[u,f,b]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])yt.command(`${u} <name>`).description(f==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(S,k)=>{let{baseUrl:m,token:x}=await V(k.baseUrl),E=new F({baseUrl:m,token:x});try{await E.guardrailUpdate(S,{status:f})}catch(A){Z(A,"extensions:deploy",`${u} a guardrail`),v(`${u} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}$(`${g.green("\u2713")} guardrail ${g.bold(S)} ${b}`),f==="inactive"&&$(g.dim(" writes it was gating now fall through to the other rules."))});yt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,f)=>{let{baseUrl:b,token:S}=await V(f.baseUrl),k=new F({baseUrl:b,token:S});try{await k.guardrailDelete(u)}catch(m){Z(m,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}$(`${g.green("\u2713")} guardrail ${g.bold(u)} deleted`)}),yt.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async u=>{let f;if(u.fields)try{f=JSON.parse(u.fields)}catch(E){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:b,token:S}=await V(u.baseUrl),k=new F({baseUrl:b,token:S}),m;try{m=await k.guardrailTest({source:u.source,record:u.record,...u.actor?{actor:u.actor}:{},...u.externalId?{externalId:u.externalId}:{},...f?{fields:f}:{},...u.phase?{phase:u.phase}:{}})}catch(E){Z(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(u.json)return $(JSON.stringify(m,null,2));let x=`${u.source}/${u.record}`;m.degraded?($(`${g.red("\u2717")} ${x} \u2014 guardrail policy is UNREADABLE; writes fail closed`),$(g.dim(` ${m.reason}`))):m.allowed?$(`${g.green("\u2713")} ${x} \u2014 ${m.decision}`+(m.blockedBy?g.dim(` (rule ${m.blockedBy})`):g.dim(" (no rule matched)"))):($(`${g.red("\u2717")} ${x} \u2014 ${m.decision} by ${g.bold(m.blockedBy??"?")} at the ${m.phase} gate`),m.message&&$(g.dim(` ${m.message}`))),m.decision==="require_confirm"&&$(g.yellow(" this write is HELD for operator approval, not refused.")),m.allowed||(process.exitCode=1)});let Ct=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),bn=(u,f={})=>{let b=`${g.bold(u.table)} ${g.dim(u.displayName)}`;$(u.exists===!1?`${b} ${g.dim("(new)")}`:b);for(let S of u.fields){let k=[S.required?"required":null].filter(Boolean).join(", "),m=f.showClaimants&&S.claimedBy?.length?` ${g.dim(`\u2190 ${S.claimedBy.join(", ")}`)}`:"";$(` ${S.column.padEnd(28)} ${S.type}${k?` (${k})`:""}${m}`)}f.showClaimants&&u.claimants.length>1&&$(g.dim(` claimed by ${u.claimants.join(", ")}`))};function sr(u){if(u instanceof ne&&u.status===409){let f=u.body;f?.error==="table_conflict"&&f.message&&(z(f.message),process.exit(1))}v(`tables: ${u instanceof Error?u.message:String(u)}`)}let eu=async u=>{let f=Ye(ue(process.cwd(),u),"public","turbobase.json"),b=await re.readFile(f,"utf8").catch(()=>null);if(b===null)return null;let S;try{S=JSON.parse(b)}catch(m){v(`${f} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let k=S.tables;return k===void 0?{tables:[],manifestPath:f}:(Array.isArray(k)||v(`${f}: "tables" must be an array.`),{tables:k,manifestPath:f})};Ct.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async u=>{let{baseUrl:f,token:b}=await V(u.baseUrl),S=new F({baseUrl:f,token:b}),k;try{k=await S.tablesList()}catch(m){Z(m,"extensions:deploy","list tables"),v(`list tables failed: ${m instanceof Error?m.message:String(m)}`)}if(u.json)return $(JSON.stringify(k,null,2));if(k.length===0)return $("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");$(Dt(k.map(m=>[m.table,m.displayName,String(m.fields.length),m.status,m.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Ct.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(u,f)=>{let b=await eu(u??".");if(b||v(`no public/turbobase.json under ${ue(process.cwd(),u??".")}.`),b.tables.length===0)return $(`${b.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:S,token:k}=await V(f.baseUrl),m=new F({baseUrl:S,token:k}),x;try{x=await W("planning tables",()=>m.tablesPlan({claimedBy:f.as,tables:b.tables}))}catch(E){Z(E,"extensions:deploy","plan tables"),sr(E)}$(`claiming as ${g.bold(x.claimedBy)}`);for(let E of x.tables)bn(E,{showClaimants:!0});$(""),$(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Ct.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(u,f)=>{let b=await eu(u??".");if(b||v(`no public/turbobase.json under ${ue(process.cwd(),u??".")}.`),b.tables.length===0)return $(`${b.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:S,token:k}=await V(f.baseUrl),m=new F({baseUrl:S,token:k}),x;try{x=await W("applying tables",()=>m.tablesApply({claimedBy:f.as,tables:b.tables}))}catch(E){Z(E,"extensions:deploy","apply tables"),sr(E)}for(let E of x.tables)bn(E,{showClaimants:!0});$(`applied ${x.tables.length} table${x.tables.length===1?"":"s"} as ${x.claimedBy}.`)}),Ct.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(u,f)=>[...f??[],u],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,f)=>{let b=f.field.map(E=>{let[A,C,N]=E.split(":");return(!A||!C)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),N!==void 0&&N!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...N==="required"?{required:!0}:{}}}),{baseUrl:S,token:k}=await V(f.baseUrl),m=new F({baseUrl:S,token:k}),x;try{x=await W(`creating cr_${u}`,()=>m.tablesApply({tables:[{slug:u,displayName:f.name??u,fields:b,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){Z(E,"extensions:deploy","create a table"),sr(E)}for(let E of x.tables)bn(E);$(""),$(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Ct.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(u,f)=>{f.confirm!==u&&v(`drop refused: --confirm "${f.confirm}" does not match "${u}".`);let{baseUrl:b,token:S}=await V(f.baseUrl),k=new F({baseUrl:b,token:S}),m;try{m=await W(`dropping cr_${u}`,()=>k.tablesDrop(u,f.confirm))}catch(x){Z(x,"extensions:deploy","drop a table"),v(`drop failed: ${x instanceof Error?x.message:String(x)}`)}if(!m.removed)return $(`no table named "${u}" on this instance \u2014 nothing dropped.`);$(`dropped ${m.table} and every row in it.`)});let si=e.command("sandbox").description("Ephemeral local authoring sandboxes.");si.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async u=>{process.env.TURBOBASE_SANDBOX="1";let f=Jc(),b;try{b=await Dd(f,{fromTenant:u.from,ttl:u.ttl,sample:u.sample,baseUrl:u.baseUrl})}catch(S){S instanceof yr&&v(S.message),v(`sandbox create failed: ${S instanceof Error?S.message:String(S)}`)}$(`sandbox ${b.name} ready.`),$(` source: ${b.fromTenant} (sampled ${Math.round(b.sampleFraction*100)}%, redacted)`),$(` url: ${b.url}`),$(` expires: ${b.expiresAt}`)}),si.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async u=>{let f=Jc();await Zi(f).catch(()=>[]);let b;try{b=await Ud(f,u)}catch(S){v(`sandbox destroy failed: ${S instanceof Error?S.message:String(S)}`)}b||v(`no sandbox named '${u}'.`),$(`destroyed sandbox ${b.name} (dropped ${b.database}).`)}),si.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let u=Jc(),f=await Zi(u).catch(()=>[]),b=await Is(),{active:S}=Ji(b);if(S.length===0)$("no active sandboxes.");else{for(let k of S)$(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);$(`
|
|
1944
|
-
${
|
|
1945
|
-
|
|
1946
|
-
`).length} lines).`)});let
|
|
1947
|
-
run \`${
|
|
1948
|
-
${
|
|
1949
|
-
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},
|
|
1950
|
-
${Object.keys(
|
|
1951
|
-
`+(
|
|
2126
|
+
`);if(await S("PROPOSAL.md",g),f.screenshot){let $=v(f.screenshot);$&&await S("proposal-screenshot.png",$)}await S(Qe(".turbobase","proposal.json"),`${JSON.stringify({proposalId:f.proposalId},null,2)}
|
|
2127
|
+
`)}async function R(d){try{let f=await re.readFile(Qe(d,".turbobase","proposal.json"),"utf8"),y=JSON.parse(f);return typeof y.proposalId=="string"&&y.proposalId?y.proposalId:void 0}catch{return}}async function E(d,f,y,_,S,g){let $=new B({baseUrl:d,token:f});try{return await $.appsPush(y,_,{note:S,proposalId:g})}catch(T){if(T instanceof X){let A=T.body;if(T.status===401&&b("push unauthorized (401) \u2014 re-run `turbobase auth login`."),T.status===403&&A?.error==="admin_required"&&b("push forbidden (403) \u2014 the PAT is not for an admin."),T.status===403&&G(T,"extensions:deploy","push app source"),T.status===404&&b(`no app "${y}" on this instance \u2014 create it with \`turbobase apps create ${y}\`.`),T.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&b("push rejected: the request body exceeded the instance limit."),b(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),T.status===400){let C=A?.path?` in ${A.path}`:"",N=A?.reason?` (${A.reason})`:"";b(`push rejected: ${A?.error??"bad request"}${N}${C}.`)}}b(`push failed: ${T instanceof Error?T.message:String(T)}`)}}function P(d,f,y){return new Promise((_,S)=>{let g=id("npm",d,{cwd:f,stdio:"inherit",...y?{env:{...process.env,...y}}:{}});g.on("error",S),g.on("exit",$=>$===0?_():S(new Error(`npm ${d.join(" ")} exited ${$??"?"}`)))})}async function I(d,f,y,_){let S=`${d.replace(/\/+$/,"")}${y}`,g;try{g=await fetch(S,{method:_.method,headers:{Authorization:`Bearer ${f}`,..._.body?{"content-type":"application/json"}:{}},..._.body?{body:JSON.stringify(_.body)}:{}})}catch($){b(`request failed: ${$ instanceof Error?$.message:String($)}`)}if(g.status===401&&b("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&b("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let $=await g.text().catch(()=>""),T=$.slice(0,300);try{let A=JSON.parse($);T=A.message??A.error??T}catch{}b(`failed: HTTP ${g.status} ${T}`)}return await g.json().catch(()=>({}))}async function U(d,f,y,_,S){return await I(d,f,`/v1/apps/${encodeURIComponent(y)}/preview/${_}`,{method:"POST",body:S})}async function se(d,f,y){return{previews:(await I(d,f,`/v1/apps/${encodeURIComponent(y)}/previews`,{method:"GET"})).previews??[]}}async function V(d,f,y,_,S,g,$,T){let A;try{A=await J(`zipping ${_}`,()=>Vd(_))}catch(O){b(`could not zip ${_}: ${O instanceof Error?O.message:String(O)}`)}A.fileCount===0&&b(`${_} is empty \u2014 the build produced nothing.`);let C={Authorization:`Bearer ${f}`,"Content-Type":"application/zip"};S&&(C["x-app-entry"]=S),g&&(C["x-proposal-id"]=g),$&&(C["x-app-build-id"]=$.buildId,C["x-app-asset-base"]=$.assetBase),T&&(C["x-app-channel"]="preview",T.label&&(C["x-app-preview-label"]=encodeURIComponent(T.label)),T.replacePreviewId&&(C["x-app-preview-replace"]=T.replacePreviewId));let N=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/deploy`,W;try{W=await J(`deploying ${y} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(N,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(O){b(`deploy request failed: ${O instanceof Error?O.message:String(O)}`)}if(W.status===401&&b("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),W.status===403&&b("deploy forbidden (403) \u2014 the PAT is not for an admin."),W.status===404){let O=await W.text().catch(()=>""),Q={};try{Q=JSON.parse(O)}catch{}Q.error==="no_preview"&&b(`${Q.message??`no open preview to replace on ${y}`} \u2014 list them with \`turbobase apps preview list ${y}\`.`),b(`no app "${y}" on ${d} \u2014 create it with \`turbobase apps create ${y}\`.`)}if(!W.ok){let O=await W.text().catch(()=>""),Q=O.slice(0,300);try{let pe=JSON.parse(O);Q=pe.message??pe.error??Q}catch{}b(`deploy failed: HTTP ${W.status} ${Q}`)}return await W.json().catch(()=>({}))}async function De(d,f){let y=su(d,{localDocsModifiedAt:await He(f)});y&&w(y.level==="warn"?h.yellow(y.message):h.dim(y.message))}async function He(d){if(!d)return null;let f=null;for(let y of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let _=await re.stat(Qe(d,y));(f===null||_.mtimeMs>f)&&(f=_.mtimeMs)}catch{}return f===null?null:new Date(f)}l.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(d,f,y)=>{let{baseUrl:_,token:S}=await H(y.baseUrl);if(y.proposal){let A=new B({baseUrl:_,token:S}),C;try{C=await J(`fetching proposal ${y.proposal}`,()=>A.appPullContext(y.proposal))}catch(pe){G(pe,"extensions:deploy","pull proposal"),pe instanceof X&&pe.status===404&&b(`no widget proposal "${y.proposal}" on ${_}.`),b(`could not fetch proposal ${y.proposal}: ${pe instanceof Error?pe.message:String(pe)}`)}let N=await J(`pulling ${C.appSlug}`,()=>m(_,S,C.appSlug)),W=f??d,O=de(process.cwd(),W??C.appSlug);await re.mkdir(O,{recursive:!0});let Q=await x(O,N.files,!!y.force);await k(O,C,!!y.force),w(`pulled ${Q} file${Q===1?"":"s"} \u2192 ${O} (rev ${N.rev}), linked to proposal ${C.proposalId}.`),w(`next: cd ${ci(process.cwd(),O)||"."} && turbobase apps deploy ${C.appSlug}`);return}d||b("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await J(`pulling ${d}`,()=>m(_,S,d)),$=de(process.cwd(),f??g.slug??d);await re.mkdir($,{recursive:!0});let T=await x($,g.files,!!y.force);w(`pulled ${T} file${T===1?"":"s"} \u2192 ${$} (rev ${g.rev}).`),w(`next: cd ${ci(process.cwd(),$)||"."} && turbobase apps deploy ${g.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(d,f,y)=>{let _=de(process.cwd(),f??d),S=await ut(y.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:$}=await Promise.resolve().then(()=>($p(),_p)),T=y.title??d,A=g({slug:d,title:T,appTsx:$(T),instanceOrigin:S?.baseUrl});await re.mkdir(_,{recursive:!0});let C=await x(_,A,!!y.force);if(w(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${_}`),y.claude!==!1){let W=Bi({baseUrl:S?.baseUrl,token:S?.token,appSlug:d}),O=0;for(let Q of W){let pe=await ry(Qe(_,Q.path),Q);(pe==="wrote"||pe==="merged")&&(O+=1)}w(`wired Claude Code: ${O} file${O===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),S||D("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let N=ci(process.cwd(),_)||".";w(`next: cd ${N} && npm install && npm run dev`),w(` turbobase apps create ${d}`),w(` turbobase apps push ${d} .`),w(` turbobase apps deploy ${d} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:y}=await H(d.baseUrl),_=new B({baseUrl:f,token:y}),S;try{S=await _.appsList()}catch(g){G(g,"extensions:deploy","list apps"),b(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return w(JSON.stringify(S,null,2));if(S.length===0)return w("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");w(pt(S.map(g=>[g.slug,g.name,g.deployed?"yes":"no",g.sourceRev===null?"\u2014":`rev ${g.sourceRev}`,g.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(d,f,y)=>{let _=de(process.cwd(),f??".");await re.stat(_).then(he=>he.isDirectory()).catch(()=>!1)||b(`${_} is not a directory.`);let{baseUrl:g,token:$}=await H(y.baseUrl),T=y.proposal??await R(_),{files:A,skipped:C,secrets:N,unstorable:W}=await Ku(_),O=Object.keys(A).length;if(O===0&&b(`no source files found under ${_} (build output and node_modules are skipped).`),W.length>0){for(let he of W)D(`${he} contains a NUL byte (U+0000), which cannot be stored.`);b(`push aborted: ${W.length} ${W.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let he of C)D(h.dim(`skipped binary file ${he}`));for(let he of N)D(h.dim(`skipped ${he} (holds credentials \u2014 never pushed)`));let Q=await J(`pushing ${O} file${O===1?"":"s"}`,()=>E(g,$,d,A,y.note,T));w(`pushed ${Q.files} file${Q.files===1?"":"s"} \u2192 ${Q.slug} rev ${Q.rev} (source only, nothing deployed).`);let pe=await yr(new B({baseUrl:g,token:$}),Q.slug);pe&&pe.entriesAdded>0&&w(`${pe.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),w(`next: turbobase apps deploy ${Q.slug}`)}),s.command("plan").description("Diff the local bundle (turbobase/bundle.json) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let f=await nd(),{baseUrl:y,token:_}=await H(d.baseUrl),S=new B({baseUrl:y,token:_}),g;try{g=await J(`planning against ${d.to??y}`,()=>S.configPlan(f))}catch($){b(`plan failed: ${$ instanceof Error?$.message:String($)}`)}NE(g,d.to??y)}),s.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").action(async d=>{let f=await nd(),{baseUrl:y,token:_}=await H(d.baseUrl),S=f.tenant??jE(y),g=ap(d.confirm,S);g.ok||b(`promote refused (fail-closed): ${g.reason}`);let $=new B({baseUrl:y,token:_});try{let T=await J(`promoting ${d.from} \u2192 ${d.to} (${S})`,()=>$.configApply(f));if(Te()){let A=[`${h.bold(`${d.from} \u2192 ${d.to}`)} ${h.dim(S??"")}`,`${Ut.add(String(T.applied.add))} ${Ut.change(String(T.applied.change))} ${Ut.destroy(String(T.applied.destroy))}`];T.backfillsQueued.length&&A.push(h.dim(`${T.backfillsQueued.length} backfill(s) queued`)),w(zt("Promoted",A))}else w(`promoted ${d.from} \u2192 ${d.to} (${S}): +${T.applied.add} ~${T.applied.change} -${T.applied.destroy}`+(T.backfillsQueued.length?` (${T.backfillsQueued.length} backfill(s) queued)`:""))}catch(T){T instanceof X&&T.status===403&&b("promote forbidden (403) \u2014 the stored PAT is not for an admin."),b(`promote failed: ${T instanceof Error?T.message:String(T)}`)}});let rr=async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_}),g=f.limit?Number(f.limit):void 0;if(f.follow){try{await tu(S,d,{follow:!0,limit:g,intervalMs:f.intervalMs?Number(f.intervalMs):void 0,sink:w})}catch($){b(`logs --follow failed: ${$ instanceof Error?$.message:String($)}`)}return}try{let $=await S.logs(d,g);$.length===0&&w(`no logs for ${d}.`);for(let T of $)w(` [${T.level}] ${T.ts??""} ${T.message}`)}catch($){b(`logs failed: ${$ instanceof Error?$.message:String($)}`)}};s.command("logs").argument("<id>","Extension id (default) or conduit id (with --follow)").description("Read an extension's logs; with --follow, stream a conduit's run ledger.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--limit <n>","Max log lines").option("--follow","Stream the conduit_event run ledger for the given conduit id.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(rr),s.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(d,f)=>{let y=td(f.reporter),_=de(process.cwd(),d),S=await fr(_),g=Wd(S);y?w(Ts(IE(d,g),y)):w(Jd(d,g,{warn:h.yellow,ok:h.green,dim:h.dim})),f.ci&&g.warnings.length>0&&process.exit(1)}),s.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(d,f)=>{let y=td(f.reporter),_=await qd(de(process.cwd(),d));if(f.against){f.against!=="sandbox"&&b(`unknown --against target '${f.against}' (only 'sandbox' is supported).`);try{await Ud(ji(_))}catch($){b($ instanceof Error?$.message:String($))}return}f.fixture||b("replay needs a --fixture <file> (offline) or --against sandbox (online).");let S;try{S=await zd(de(process.cwd(),f.fixture))}catch($){b(`could not read fixture ${f.fixture}: ${$ instanceof Error?$.message:String($)}`)}let g=await Dd(_,S,f.fixture);if(y){let $=CE(g);w(Ts($,y)),li($.cases.some(T=>T.status==="failed")?1:0)}w(Md(g,!!f.trace)),li(g.error?1:0)}),s.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async d=>{let{baseUrl:f,token:y}=await H(d.baseUrl),_=new B({baseUrl:f,token:y});try{await nu(_,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:w})}catch(S){S instanceof X&&S.status===403&&b("forbidden (403) \u2014 binding --retry requires an admin PAT."),S instanceof X&&S.status===409&&b("binding is not retryable (only divergent/blocked bindings can be retried)."),b(`ext binding failed: ${S instanceof Error?S.message:String(S)}`)}});let Nt=s.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");Nt.command("list").description("List hook proposals and the evidence behind each (defaults to the pending queue).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <list>","proposed | active | rejected (comma-joined). Default: proposed.").option("--provenance <list>","mechanic | operator | learning | code-baseline (comma-joined).").option("--record-type <type>","Only proposals for this record type.").option("--source <system>","Only proposals for this adapter id.").option("--limit <n>","Max rows listed (default 200).").option("--json","Emit raw JSON instead of a table.").action(async d=>{await Ou(d)}),Nt.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,f)=>{await Nu(d??[],f)}),Nt.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{await ju(d,f)}),Nt.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,f)=>{await Lu(d,f)}),s.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(d,f)=>{let y=d.lastIndexOf("@"),_=y>0?d.slice(0,y):d,S=y>0?d.slice(y+1):void 0,g=Pi();g||b(`marketplace not configured \u2014 set ${vn} and ${_s}.
|
|
2128
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let $=Ai(g.registryUrl);$&&b($);let{baseUrl:T,token:A}=await H(f.baseUrl),C=new dr(g),N;try{N=await J(`fetching ${d}`,()=>C.fetchBundle(_,S))}catch(he){b(`marketplace fetch failed for ${d}: ${he instanceof Error?he.message:String(he)}`)}let W=gs(N.manifest),O=null;if(W.length>0){if(!f.connection){let he=W.map(Ce=>Ce.source_system).join(", ");b(`${N.name}@${N.version} declares a connection input (source: ${he}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}O=f.connection}let Q=OE(N.bundle,N.name,N.kind),pe=new B({baseUrl:T,token:A});try{let he=await J(`installing ${N.name}@${N.version}`,()=>pe.deploy({...Q,provenance:"marketplace",...O?{connectionId:O}:{}}));w(`installed ${N.name}@${N.version} \u2192 ${he.id} (status=${he.status}, ${he.outcome})`+(O?` bound to connection ${O}.`:"."))}catch(he){he instanceof X&&he.status===403&&b("install forbidden (403) \u2014 the stored PAT is not for an admin."),b(`install failed: ${he instanceof Error?he.message:String(he)}`)}}),s.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(d,f)=>{let y=Pi();y||b(`marketplace not configured \u2014 set ${vn} and ${_s}.
|
|
2129
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let _=Ai(y.registryUrl);_&&b(_);let S=de(process.cwd(),d),g=await fr(S),$=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",T={};if(f.manifest){let N=de(process.cwd(),f.manifest),W;try{W=await re.readFile(N,"utf8")}catch{b(`manifest not found at ${f.manifest}.`)}let O;try{O=JSON.parse(W)}catch{b(`manifest is not valid JSON: ${f.manifest}.`)}(typeof O!="object"||O===null||Array.isArray(O))&&b("manifest must be a JSON object."),T=O}try{hi(T,g)}catch(N){N instanceof Lt&&b(N.message),b(`manifest validation failed: ${N instanceof Error?N.message:String(N)}`)}let A=new dr(y);try{await J(`publishing ${f.name}@${f.pkgVersion}`,()=>A.publish({name:f.name,version:f.pkgVersion,kind:$,bundle:g,manifest:T}))}catch(N){N instanceof X&&N.status===403&&b("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),N instanceof X&&N.status===409&&b(`version already published \u2014 ${f.name}@${f.pkgVersion} exists. Bump the version.`),b(`publish failed: ${N instanceof Error?N.message:String(N)}`)}let C=gs(T);w(`published ${f.name}@${f.pkgVersion} (kind=${$}) to the marketplace.`),C.length>0&&w(` declares ${C.length} connection input(s): ${C.map(N=>N.source_system).join(", ")} \u2014 bound at install.`)}),r.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async d=>{let f=await ut(d.baseUrl).catch(()=>null),y=Bi({baseUrl:f?.baseUrl,token:f?.token}),_=0,S=0,g=0;for(let $ of y){let T=de(process.cwd(),$.path),A=await ry(T,$);A==="wrote"?(_+=1,w(` wrote ${$.path}`)):A==="merged"?(g+=1,w(` merged ${$.path} (added the .mcp.json rule)`)):(S+=1,w(` skipped ${$.path} (exists)`))}w(`
|
|
2130
|
+
project init: ${_} written, ${g} merged, ${S} skipped.`)}),r.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Mi} (non-destructive).`).action(async()=>{let d=ou(),f=0,y=0;for(let _ of d){let S=de(process.cwd(),_.path);await nr(S,_.content,_.executable)==="wrote"?(f+=1,w(` wrote ${_.path}`)):(y+=1,w(` skipped ${_.path} (exists)`))}w(`
|
|
2131
|
+
project ci: ${f} written, ${y} skipped.`),f>0&&(w(`
|
|
2132
|
+
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),w("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),w("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),r.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async d=>{let{baseUrl:f,token:y}=await H(d.baseUrl),_=new B({baseUrl:f,token:y}),S;try{S=await _.catalogRecords()}catch(C){C instanceof X&&(C.status===401||C.status===403)&&b("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),b(`catalog fetch failed: ${C instanceof Error?C.message:String(C)}`)}if(S.length===0){w("no records in the instance catalog \u2014 nothing to generate.");return}let g=de(process.cwd(),d.out),$=Fd(S,{event:d.event}),T=0,A=0;for(let{recordType:C,fixture:N}of $){let W=Qe(g,`${C}.json`),O=`${JSON.stringify(N,null,2)}
|
|
2133
|
+
`;d.force?(await re.mkdir(tr(W),{recursive:!0}),await re.writeFile(W,O,{mode:420}),T+=1,w(` wrote ${d.out}/${C}.json`)):await nr(W,O)==="wrote"?(T+=1,w(` wrote ${d.out}/${C}.json`)):(A+=1,w(` skipped ${d.out}/${C}.json (exists \u2014 use --force to overwrite)`))}w(`
|
|
2134
|
+
samples init: ${T} written, ${A} skipped.`)});let Ze=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),sr=d=>[d.name??h.dim(d.id.slice(0,8)),d.status==="active"?h.green("active"):d.status==="proposed"?h.yellow("proposed"):h.dim("inactive"),d.decision==="deny"?h.red(d.decision):d.decision==="require_confirm"?h.yellow(d.decision):h.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??h.dim("any"),d.when||h.dim("(always)"),d.reason??""],fs=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Ze.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:y}=await H(d.baseUrl),_=new B({baseUrl:f,token:y}),S;try{S=await _.guardrailsList()}catch(g){G(g,"extensions:deploy","list guardrails"),b(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return w(JSON.stringify(S,null,2));if(S.length===0)return w(`no write guardrails \u2014 every record the admin entitlement allows is writable.
|
|
2135
|
+
`+h.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));w(pt(S.map(sr),{head:fs})),w(h.dim(" first match wins; lower PRIO is evaluated first."))}),Ze.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_}),g;try{g=await S.guardrailCreate({name:d,source:f.source,record:f.record,decision:f.decision,...f.op?{op:f.op}:{},...f.target?{target:f.target}:{},...f.actor?{actor:f.actor}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when?{when:f.when}:{},...f.reason?{reason:f.reason}:{},...f.disabled?{enabled:!1}:{},...f.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch($){G($,"extensions:deploy","create a guardrail"),b(`create guardrail failed: ${$ instanceof Error?$.message:String($)}`)}w(`${h.green("\u2713")} guardrail ${h.bold(g.name??g.id)} created${g.status==="active"?"":h.dim(` (${g.status} \u2014 activate it to take effect)`)}`),w(h.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),w(h.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),Ze.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.decision===void 0&&f.priority===void 0&&f.when===void 0&&f.reason===void 0&&b("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_}),g;try{g=await S.guardrailUpdate(d,{...f.decision!==void 0?{decision:f.decision}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when!==void 0?{when:f.when}:{},...f.reason!==void 0?{reason:f.reason}:{}})}catch($){G($,"extensions:deploy","edit a guardrail"),b(`edit guardrail failed: ${$ instanceof Error?$.message:String($)}`)}w(`${h.green("\u2713")} guardrail ${h.bold(g.name??g.id)} updated`),w(h.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[d,f,y]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Ze.command(`${d} <name>`).description(f==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(_,S)=>{let{baseUrl:g,token:$}=await H(S.baseUrl),T=new B({baseUrl:g,token:$});try{await T.guardrailUpdate(_,{status:f})}catch(A){G(A,"extensions:deploy",`${d} a guardrail`),b(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}w(`${h.green("\u2713")} guardrail ${h.bold(_)} ${y}`),f==="inactive"&&w(h.dim(" writes it was gating now fall through to the other rules."))});Ze.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_});try{await S.guardrailDelete(d)}catch(g){G(g,"extensions:deploy","delete a guardrail"),b(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}w(`${h.green("\u2713")} guardrail ${h.bold(d)} deleted`)}),Ze.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await S.guardrailPostureGet()}catch(C){G(C,"extensions:deploy","read the guardrail posture"),b(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}w(`guardrail posture: ${h.bold(g(A.mode))}`),w(h.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let $=d.trim().toLowerCase();$!=="allow"&&$!=="deny"&&b("posture must be 'allow' or 'deny'.");let T;try{T=await S.guardrailPostureSet($)}catch(A){G(A,"extensions:deploy","set the guardrail posture"),b(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}w(`${h.green("\u2713")} guardrail posture set to ${h.bold(g(T.mode))}`),T.mode==="deny"&&w(h.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Ze.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let f;if(d.fields)try{f=JSON.parse(d.fields)}catch(T){b(`--fields must be valid JSON: ${T instanceof Error?T.message:String(T)}`)}let{baseUrl:y,token:_}=await H(d.baseUrl),S=new B({baseUrl:y,token:_}),g;try{g=await S.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...f?{fields:f}:{},...d.phase?{phase:d.phase}:{}})}catch(T){G(T,"extensions:deploy","test guardrails"),b(`guardrails test failed: ${T instanceof Error?T.message:String(T)}`)}if(d.json)return w(JSON.stringify(g,null,2));let $=`${d.source}/${d.record}`;g.degraded?(w(`${h.red("\u2717")} ${$} \u2014 guardrail policy is UNREADABLE; writes fail closed`),w(h.dim(` ${g.reason}`))):g.allowed?w(`${h.green("\u2713")} ${$} \u2014 ${g.decision}`+(g.blockedBy?h.dim(` (rule ${g.blockedBy})`):h.dim(" (no rule matched)"))):(w(`${h.red("\u2717")} ${$} \u2014 ${g.decision} by ${h.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&w(h.dim(` ${g.message}`))),g.decision==="require_confirm"&&w(h.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let jt=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),or=(d,f={})=>{let y=`${h.bold(d.table)} ${h.dim(d.displayName)}`;w(d.exists===!1?`${y} ${h.dim("(new)")}`:y);for(let _ of d.fields){let S=[_.required?"required":null].filter(Boolean).join(", "),g=f.showClaimants&&_.claimedBy?.length?` ${h.dim(`\u2190 ${_.claimedBy.join(", ")}`)}`:"";w(` ${_.column.padEnd(28)} ${_.type}${S?` (${S})`:""}${g}`)}f.showClaimants&&d.claimants.length>1&&w(h.dim(` claimed by ${d.claimants.join(", ")}`))};function di(d){if(d instanceof X&&d.status===409){let f=d.body;f?.error==="table_conflict"&&f.message&&(D(f.message),process.exit(1))}b(`tables: ${d instanceof Error?d.message:String(d)}`)}let ld=async d=>{let f=Qe(de(process.cwd(),d),"public","turbobase.json"),y=await re.readFile(f,"utf8").catch(()=>null);if(y===null)return null;let _;try{_=JSON.parse(y)}catch(g){b(`${f} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let S=_.tables;return S===void 0?{tables:[],manifestPath:f}:(Array.isArray(S)||b(`${f}: "tables" must be an array.`),{tables:S,manifestPath:f})};jt.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:y}=await H(d.baseUrl),_=new B({baseUrl:f,token:y}),S;try{S=await _.tablesList()}catch(g){G(g,"extensions:deploy","list tables"),b(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return w(JSON.stringify(S,null,2));if(S.length===0)return w("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");w(pt(S.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),jt.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,f)=>{let y=await ld(d??".");if(y||b(`no public/turbobase.json under ${de(process.cwd(),d??".")}.`),y.tables.length===0)return w(`${y.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:_,token:S}=await H(f.baseUrl),g=new B({baseUrl:_,token:S}),$;try{$=await J("planning tables",()=>g.tablesPlan({claimedBy:f.as,tables:y.tables}))}catch(T){G(T,"extensions:deploy","plan tables"),di(T)}w(`claiming as ${h.bold($.claimedBy)}`);for(let T of $.tables)or(T,{showClaimants:!0});w(""),w(h.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),jt.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,f)=>{let y=await ld(d??".");if(y||b(`no public/turbobase.json under ${de(process.cwd(),d??".")}.`),y.tables.length===0)return w(`${y.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:_,token:S}=await H(f.baseUrl),g=new B({baseUrl:_,token:S}),$;try{$=await J("applying tables",()=>g.tablesApply({claimedBy:f.as,tables:y.tables}))}catch(T){G(T,"extensions:deploy","apply tables"),di(T)}for(let T of $.tables)or(T,{showClaimants:!0});w(`applied ${$.tables.length} table${$.tables.length===1?"":"s"} as ${$.claimedBy}.`)}),jt.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,f)=>[...f??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let y=f.field.map(T=>{let[A,C,N]=T.split(":");return(!A||!C)&&b(`--field "${T}" must be name:type[:required] (e.g. title:text:required).`),N!==void 0&&N!=="required"&&b(`--field "${T}": the third part may only be "required".`),{name:A,type:C,...N==="required"?{required:!0}:{}}}),{baseUrl:_,token:S}=await H(f.baseUrl),g=new B({baseUrl:_,token:S}),$;try{$=await J(`creating cr_${d}`,()=>g.tablesApply({tables:[{slug:d,displayName:f.name??d,fields:y,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(T){G(T,"extensions:deploy","create a table"),di(T)}for(let T of $.tables)or(T);w(""),w(h.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),jt.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.confirm!==d&&b(`drop refused: --confirm "${f.confirm}" does not match "${d}".`);let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_}),g;try{g=await J(`dropping cr_${d}`,()=>S.tablesDrop(d,f.confirm))}catch($){G($,"extensions:deploy","drop a table"),b(`drop failed: ${$ instanceof Error?$.message:String($)}`)}if(!g.removed)return w(`no table named "${d}" on this instance \u2014 nothing dropped.`);w(`dropped ${g.table} and every row in it.`)});let ui=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ui.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let f=rd(),y;try{y=await np(f,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(_){_ instanceof wr&&b(_.message),b(`sandbox create failed: ${_ instanceof Error?_.message:String(_)}`)}w(`sandbox ${y.name} ready.`),w(` source: ${y.fromTenant} (sampled ${Math.round(y.sampleFraction*100)}%, redacted)`),w(` url: ${y.url}`),w(` expires: ${y.expiresAt}`)}),ui.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let f=rd();await sa(f).catch(()=>[]);let y;try{y=await rp(f,d)}catch(_){b(`sandbox destroy failed: ${_ instanceof Error?_.message:String(_)}`)}y||b(`no sandbox named '${d}'.`),w(`destroyed sandbox ${y.name} (dropped ${y.database}).`)}),ui.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=rd(),f=await sa(d).catch(()=>[]),y=await Ls(),{active:_}=ra(y);if(_.length===0)w("no active sandboxes.");else{for(let S of _)w(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);w(`
|
|
2136
|
+
${_.length} active sandbox(es).`)}f.length>0&&w(`(reaped ${f.length} expired sandbox(es).)`)}),s.command("export").description("Snapshot the live instance into turbobase/bundle.json.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Ds).action(async d=>{let{baseUrl:f,token:y}=await H(d.baseUrl),_=new B({baseUrl:f,token:y}),S;try{S=await J("exporting instance config",()=>_.configExport())}catch(T){T instanceof X&&(T.status===401||T.status===403)&&b("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),b(`ext export failed: ${T instanceof Error?T.message:String(T)}`)}let g=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
|
|
2137
|
+
`,$=de(process.cwd(),d.out,kr);await re.mkdir(tr($),{recursive:!0}),await re.writeFile($,g,"utf8"),w(`wrote ${d.out}/${kr} (${g.split(`
|
|
2138
|
+
`).length} lines).`)});let cd=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),oy=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],dd=()=>process.env.TURBOBASE_HOME?.trim()||Qe(SE(),".turbobase"),iy=()=>"1.1.21",hs=async()=>Promise.all(oy.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));cd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await hs();for(let f of d)w(`${f.present?ve.success("installed"):ve.warn("missing")} ${h.bold(f.name)} \u2014 ${f.needs}`);d.some(f=>!f.present)&&w(`
|
|
2139
|
+
run \`${mr} ext extras install\` to fetch them into ${dd()}.`)}),cd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await hs();if(d.every(A=>A.present)){w(ve.success("extras already installed \u2014 nothing to do."));return}let f=dd();await re.mkdir(f,{recursive:!0});let y=d.filter(A=>!A.present).map(A=>A.name),_=Yi(process.platform,process.arch),S=async(A,C)=>{let{code:N,stderr:W}=await ps("npm",["install","--prefix",f,"--no-audit","--no-fund",...A]);N!==0&&b(`extras install failed while installing ${C} (npm exited ${N}).
|
|
2140
|
+
${W.trim()}
|
|
2141
|
+
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=y.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(C=>`${C}@${Ji[C]??"latest"}`);w(`installing ${A.join(", ")} \u2192 ${f}/node_modules \u2026`),await S(A,g.join(", "))}if(y.includes("isolated-vm")){let A=`isolated-vm@${Ji["isolated-vm"]}`;if(w(`installing ${A} \u2192 ${f}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),Ju.includes(_)){let N=`${Zi}@${iy()}`;w(`fetching ${N} (no upstream binary for ${_}) \u2026`);let{code:W}=await ps("npm",["install","--prefix",f,"--no-audit","--no-fund","--ignore-scripts",N]);W!==0&&w(ve.warn(`could not fetch ${N} \u2014 falling back to a source build.`))}let C=await Zu({home:f});C.length>0&&w(` ${ve.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${_}`)}let $=await hs(),T=$.filter(A=>!A.present).map(A=>A.name);if(T.includes("isolated-vm")){w(ve.warn(`no prebuilt isolated-vm for ${_} / Node ${process.versions.node} (${Qi()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await ps("npm",["rebuild","--prefix",f,"isolated-vm"]);A===0&&($=await hs(),T=$.filter(C=>!C.present).map(C=>C.name))}T.length>0&&b(`npm succeeded but ${T.join(", ")} still will not load \u2014 no prebuilt binary for ${_} / Node ${process.versions.node} (${Qi()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),w(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let wn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return wn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let f=d.target==="approved"?"approved":d.target==="auto"?"auto":null;f||b(`--target must be 'auto' or 'approved' (got '${d.target}').`);let y=await LE(de(process.cwd(),d.project??".")),_=Object.keys(y).length;!d.solution&&_===0&&b("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(d.ref?await sd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await sd(["rev-parse","HEAD"]),$=d.gitRepo??process.env.GITHUB_REPOSITORY??await sd(["remote","get-url","origin"]),T=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:N}=await H(d.baseUrl),W=new B({baseUrl:C,token:N}),O;try{O=await W.releaseDeploy({solutionId:d.solution??null,target:f,approvedBy:d.approvedBy??null,files:_>0?y:null,gitRepo:$,gitRef:T,gitSha:g,prUrl:A})}catch(Q){G(Q,"releases:write","release deploy"),Q instanceof X&&Q.status===404&&b("solution_not_found \u2014 no solution with that id."),b(`release deploy failed: ${Q instanceof Error?Q.message:String(Q)}`)}w(`release ${O.releaseId} enqueued \u2192 taskId=${O.taskId} (target=${f}`+(_>0?`, uploaded ${_} bundle file(s)`:", live-fetch")+")."),d.follow&&await Hi(()=>W.releaseStatus(O.releaseId),`release ${O.releaseId}`,d.intervalMs)}),wn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_}),g;try{g=await S.releaseFiles(d)}catch(A){A instanceof X&&A.status===404&&b(`release ${d} not found.`),A instanceof X&&A.status===409&&b(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),G(A,"releases:write","pull a release"),b(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let $=de(process.cwd(),f.dir),T=0;for(let[A,C]of[["owned",g.owned],["context",g.context]])for(let[N,W]of Object.entries(C)){let O=Qe($,A,N);await re.mkdir(tr(O),{recursive:!0}),await re.writeFile(O,W,"utf8"),T++}await re.writeFile(Qe($,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),w(`pulled release ${g.releaseId} (${g.status}) \u2192 ${$}
|
|
2142
|
+
${Object.keys(g.owned).length} owned file(s), ${Object.keys(g.context).length} context file(s), ${T} total
|
|
2143
|
+
`+(g.logTail?`
|
|
1952
2144
|
the failure these bytes produced:
|
|
1953
|
-
${
|
|
2145
|
+
${g.logTail.trim()}
|
|
1954
2146
|
`:"")+`
|
|
1955
2147
|
edit the files under owned/, then:
|
|
1956
|
-
turbobase release push ${
|
|
2148
|
+
turbobase release push ${g.releaseId} --dir ${f.dir}`)}),wn.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_}),g=de(process.cwd(),f.dir),$;try{$=await S.releaseFiles(d)}catch(O){O instanceof X&&O.status===404&&b(`release ${d} not found.`),G(O,"releases:write","push a release"),b(`release push failed: ${O instanceof Error?O.message:String(O)}`)}let T=async(O,Q)=>{try{return await re.readFile(Qe(g,O,Q),"utf8")}catch{return null}},A=[];for(let[O,Q]of Object.entries($.context)){let pe=await T("context",O);pe!==null&&pe!==Q&&A.push(O)}A.length>0&&b(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
|
|
1957
2149
|
`+A.map(O=>` context/${O}`).join(`
|
|
1958
|
-
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={
|
|
2150
|
+
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...$.context},N=0;for(let[O,Q]of Object.entries($.owned)){let pe=await T("owned",O);C[O]=pe??Q,pe!==null&&pe!==Q&&N++}N===0&&w("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let W=f.target==="approved"?"approved":"auto";try{let O=await S.releasePush(d,{files:C,target:W,...f.approvedBy?{approvedBy:f.approvedBy}:{}});w(`pushed ${Object.keys(C).length} file(s) (${N} edited) \u2192 release ${O.releaseId} (task ${O.taskId}).
|
|
1959
2151
|
follow it with:
|
|
1960
|
-
turbobase release status ${O.releaseId} --follow`)}catch(O){O instanceof
|
|
1961
|
-
${
|
|
1962
|
-
`)),t&&void 0,e}function
|
|
1963
|
-
${t.add.length} to add, ${t.change.length} to change, ${t.destroy.length} to destroy.`+(t.add.length+t.change.length+t.destroy.length===0?" (no changes \u2014 up to date.)":""))}function
|
|
2152
|
+
turbobase release status ${O.releaseId} --follow`)}catch(O){O instanceof X&&O.status===403&&b("an approved target needs --approved-by (the deploy gate fails closed)."),O instanceof X&&O.status===409&&b("that solution already has an active release \u2014 roll it back or wait for it."),G(O,"releases:write","push a release"),b(`release push failed: ${O instanceof Error?O.message:String(O)}`)}}),wn.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_});if(f.follow){await Hi(()=>S.releaseStatus(d),`release ${d}`,f.intervalMs);return}let g;try{g=await S.releaseStatus(d)}catch($){G($,"releases:write","release status"),$ instanceof X&&$.status===404&&b(`release ${d} not found.`),b(`release status failed: ${$ instanceof Error?$.message:String($)}`)}w(`release ${d}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&w(g.outputTail.replace(/\n+$/,""))}),wn.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:y,token:_}=await H(f.baseUrl),S=new B({baseUrl:y,token:_}),g;try{g=await S.releaseRollback(d)}catch($){G($,"releases:write","release rollback"),$ instanceof X&&$.status===404&&b(`release ${d} not found.`),$ instanceof X&&$.status===409&&b(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),b(`release rollback failed: ${$ instanceof Error?$.message:String($)}`)}w(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),wn.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:f,token:y}=await H(d.baseUrl),_=new B({baseUrl:f,token:y}),S;try{S=await _.releaseList()}catch(g){G(g,"releases:write","release list"),b(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if(S.length===0){w("no releases.");return}if(Te())w(pt(S.map(g=>[g.id,_n(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map($=>`"${$}"`).join(", "):h.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of S){let $=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";w(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${$}`)}w(`
|
|
2153
|
+
${S.length} release(s).`)}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{runAuthoringMcpServer:f}=await Promise.resolve().then(()=>(ny(),ty));await f({baseUrl:d.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
|
|
2154
|
+
`)),t&&void 0,e}function OE(t,e,n){let r=s=>{let o=new RegExp(`${s}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return o?o[2]:void 0};return{id:r("id")??`marketplace:${e}`,recordType:r("recordType")??"*",event:r("event")??"before_save",source:r("source")??"standalone",sourceCode:t,extensionKind:n||"hook"}}async function nd(){let t=de(process.cwd(),Ds,kr),e;try{e=await re.readFile(t,"utf8")}catch{b(`no bundle found at ${Ds}/${kr} \u2014 run \`turbobase ext export\` first.`)}try{return ip(e)}catch(n){b(`bundle is invalid: ${n instanceof Error?n.message:String(n)}`)}}function NE(t,e){w(`plan against ${e}:`);for(let n of t.add)w(` ${Ut.add(`${n.kind} ${n.id}`)}`);for(let n of t.change)w(` ${Ut.change(`${n.kind} ${n.id}`)}`);for(let n of t.destroy)w(` ${Ut.destroy(`${n.kind} ${n.id}`)}`);w(`
|
|
2155
|
+
${t.add.length} to add, ${t.change.length} to change, ${t.destroy.length} to destroy.`+(t.add.length+t.change.length+t.destroy.length===0?" (no changes \u2014 up to date.)":""))}function jE(t){try{let n=new URL(t).hostname.split(".")[0];return n&&n!=="localhost"?n:void 0}catch{return}}function ps(t,e,n){return new Promise(r=>{let s=id(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...n}}),o="";s.stderr?.on("data",i=>{let a=i.toString();o+=a,process.stderr.write(a)}),s.on("error",i=>r({code:-1,stderr:i.message})),s.on("exit",i=>r({code:i??-1,stderr:o}))})}function rd(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(n,r)=>{let s=r?t.replace(/\/[^/]*$/,`/${r}`):t,o=await ps("psql",[s,"-v","ON_ERROR_STOP=1","-c",n]);if(o.code!==0)throw new Error(`psql failed (exit ${o.code}): ${o.stderr.trim()}`)};return{target:()=>t,createDatabase:async n=>{await e(`CREATE DATABASE ${n};`)},replayMigrations:async n=>{let r=t.replace(/\/[^/]*$/,`/${n}`),s=await ps("supabase",["migration","up","--db-url",r]);if(s.code!==0)throw new Error(`supabase migration up failed (exit ${s.code}): ${s.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async n=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(n,r,s)=>{let o=Object.keys(s[0]??{});if(o.length===0)return;let i=s.map(a=>`(${o.map(l=>a[l]===null||a[l]===void 0?"NULL":`'${String(a[l]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${r} (${o.join(", ")}) VALUES ${i};`,n)},dropDatabase:async n=>{await e(`DROP DATABASE IF EXISTS ${n} WITH (FORCE);`)}}}async function LE(t){let e=de(t,"src"),n={},r=async s=>{let o;try{o=await re.readdir(s,{withFileTypes:!0})}catch{return}for(let i of o){let a=Qe(s,i.name);if(i.isDirectory())await r(a);else if(i.isFile()){let l=ci(e,a).split(od).join("/");n[l]=await re.readFile(a,"utf8")}}};return await r(e),n}function sd(t){return new Promise(e=>{let n=id("git",t,{stdio:["ignore","pipe","ignore"]}),r="";n.stdout?.on("data",s=>{r+=s.toString()}),n.on("error",()=>e(null)),n.on("exit",s=>e(s===0&&r.trim()?r.trim():null))})}var DE=!1;DE&&ad().parseAsync(process.argv).catch(t=>b(t instanceof Error?t.message:String(t)));ad().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
|
|
1964
2156
|
`),process.exit(1)});
|