@turbobase/cli 1.15.0 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/turbobase-standalone.mjs +277 -184
- package/dist/turbobase.js +248 -155
- package/package.json +1 -1
package/dist/turbobase.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
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 dy=Object.create;var Ci=Object.defineProperty;var uy=Object.getOwnPropertyDescriptor;var py=Object.getOwnPropertyNames;var hy=Object.getPrototypeOf,fy=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),qd=(t,e)=>{for(var n in e)Ci(t,n,{get:e[n],enumerable:!0})},my=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of py(e))!fy.call(t,s)&&s!==n&&Ci(t,s,{get:()=>e[s],enumerable:!(r=uy(e,s))||r.enumerable});return t};var zd=(t,e,n)=>(n=t!=null?dy(hy(t)):{},my(e||!t||!t.__esModule?Ci(n,"default",{value:t,enumerable:!0}):n,t));function dn(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var hr=j(()=>{});import{z as un}from"zod";function $s(t){let e=Oi.safeParse(t);return e.success?(e.data.inputs??[]).filter(n=>n.type==="connection"):[]}function Ni(t,e){let n=Oi.safeParse(t);if(!n.success)throw new Ft(`invalid manifest: ${n.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);if(Bd.test(e))throw new Ft('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(Bd.test(r))throw new Ft("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Fd,Hd,Oi,Ft,Bd,Kd=j(()=>{Fd=un.object({type:un.literal("connection"),source_system:un.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:un.string().min(1).max(200).optional()}),Hd=un.discriminatedUnion("type",[Fd]),Oi=un.object({inputs:un.array(Hd).optional()}).passthrough(),Ft=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Bd=/\bconnection[_-]?id\b["']?\s*[:=]/i});var xs,Li=j(()=>{xs=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as qe}from"zod";var ji,Vd,Gd=j(()=>{hr();Li();ji=qe.object({id:qe.string().min(1,"hook id must be non-empty"),recordType:qe.union([qe.string().min(1),qe.array(qe.string().min(1)).min(1),qe.literal("*")]),event:qe.enum(xs),source:qe.string().min(1).optional(),when:qe.unknown().optional(),run:qe.unknown(),failClosed:qe.boolean().optional(),timeoutMs:qe.number().int().positive().optional(),description:qe.string().optional(),systemReserved:qe.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"})}),Vd=dn({kind:"hook",schema:ji,factoryName:"defineHook"})});var Wd=j(()=>{Gd();Li()});var Ts,Di=j(()=>{Ts=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as ke}from"zod";var Jd,Ui,Yd,Zd=j(()=>{hr();Di();Jd=ke.object({source:ke.string().min(1,"to.source must be non-empty"),recordType:ke.string().min(1,"to.recordType must be non-empty")}),Ui=ke.object({id:ke.string().min(1,"conduit id must be non-empty"),on:ke.enum(Ts),from:ke.object({source:ke.string().min(1,"from.source must be non-empty"),recordType:ke.string().min(1,"from.recordType must be non-empty"),when:ke.unknown().optional()}),to:Jd.optional(),mode:ke.enum(["dual-bind","one-shot"]).optional(),transform:ke.unknown().optional(),sequence:ke.array(ke.object({to:Jd,transform:ke.unknown(),awaitSource:ke.boolean().optional()})).optional(),idempotencyKey:ke.unknown().optional(),cycleBudget:ke.number().int().positive().optional(),conflictStrategy:ke.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:ke.number().int().positive().optional(),description:ke.string().optional(),systemReserved:ke.boolean().optional()}).superRefine((t,e)=>{let n=t,r=n.to!==void 0||n.transform!==void 0,s=n.sequence!==void 0;r&&s?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!r&&!s?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):s?(n.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),n.sequence.forEach((u,p)=>{typeof u.transform!="function"&&e.addIssue({code:"custom",path:["sequence",p,"transform"],message:"transform must be a function"}),n.from?.source&&u.to?.source&&n.from.source===u.to.source&&e.addIssue({code:"custom",path:["sequence",p,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(n.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof n.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let o=t.from?.when;o!==void 0&&typeof o!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=n.from,l=n.to;a?.source&&l?.source&&a.source===l.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"})}),Yd=dn({kind:"conduit",schema:Ui,factoryName:"defineConduit"})});var Xd=j(()=>{Zd();Di()});import{z as Ae}from"zod";var Mi,Qd,eu=j(()=>{hr();Mi=Ae.object({id:Ae.string().min(1,"process id must be non-empty"),input:Ae.object({type:Ae.literal("object"),properties:Ae.record(Ae.unknown()).optional(),required:Ae.array(Ae.string()).optional()}).passthrough(),steps:Ae.array(Ae.object({id:Ae.string().min(1,"step id must be non-empty"),recordType:Ae.string().min(1,"step.recordType must be non-empty"),awaitSource:Ae.boolean().optional(),build:Ae.unknown(),description:Ae.string().optional()})).min(1,"a process needs at least one step"),onFailure:Ae.enum(["stop","rollback"]).optional(),description:Ae.string().optional()}).superRefine((t,e)=>{let n=t.steps;if(!Array.isArray(n))return;let r=new Map;n.forEach((s,o)=>{let i=s;if(typeof i.build!="function"&&e.addIssue({code:"custom",path:["steps",o,"build"],message:"build must be a function"}),typeof i.id=="string"){let a=r.get(i.id);a!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${i.id}' (steps ${a} and ${o}) \u2014 step ids must be unique within a process`}):r.set(i.id,o)}})}),Qd=dn({kind:"process",schema:Mi,factoryName:"defineProcess"})});var tu=j(()=>{});var nu=j(()=>{eu();tu()});async function xy(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 Rs(t,e={}){return(e.transform??xy)(t)}var qi=j(()=>{});function zi(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 ru(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Bi(t){return`${ru(t.source)}${ru(t.recordType)}`}function Ty(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Ry(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function Fi(t){let e=Bi(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=zi(o.pgType),a=o.nullable?"?":"",l=o.nullable?" | null":"";return` /** ${Ry(o)} */
|
|
12
|
+
${Ty(o.name)}${a}: ${i}${l};`});return`${r}
|
|
13
13
|
export interface ${e} {
|
|
14
14
|
${s.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}function
|
|
16
|
+
}`}function Es(t){return[...t.records].sort((r,s)=>`${r.source}:${r.recordType}`.localeCompare(`${s.source}:${s.recordType}`)).map(Fi).join(`
|
|
17
17
|
|
|
18
|
-
`)}function
|
|
19
|
-
`)}var
|
|
18
|
+
`)}function su(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 Ey(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Hi(t){let e=su(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` ${Ey(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 Ki=j(()=>{});function Py(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function ou(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 pn(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let n=Py(t.baseUrl),r=await ou(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=Es(r),o=[Ay,"// ----- Record shapes (from /v1/catalog/records) -----",s,"// ----- Keyset seek keys (derived from column nullability) -----",Hi(r)];if(!t.recordsOnly){let i=await ou(n.openapi,t.token,e),a=await Rs(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
|
|
25
|
-
`)}function
|
|
26
|
-
`)}function Ps(t,e={}){let n=e.budgetMs??6e5,r=e.defaultDelayMs??6e4,s=e.sleep??(u=>new Promise(p=>setTimeout(p,u))),o=e.now??(()=>Date.now()),i=e.onWait??wy,a=e.onGiveUp??vy;return async(u,p)=>{let g=o(),$=0;for(;;){let v=await t(u,p);if(v.status!==503||p&&!yy(p.body))return v;let S=n-(o()-g),{maintenance:T,delayMs:E,error:P}=await by(v,o());if(!T)return v;if(S<=0)return $>0&&a({waitedMs:o()-g,attempts:$,host:eu(u),error:P}),v;let C=E??r;C=Math.min(Math.max(C,1e3),12e4),C=Math.min(C,S),$+=1,i({attempt:$,delayMs:C,remainingMs:S,host:eu(u),error:P}),await s(C)}}}var Vi=j(()=>{});function tu(t){if(typeof t=="string")return t.trim();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():""}function ky(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function nu(t){let e=tu(t);return typeof t=="string"&&ky(e)?Sy:e.slice(0,200)}function ru(t,e){return Ki(t,e)}function su(t){return t instanceof X&&ru(t.status,t.body)}function $y(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function ou(t){return t.replace(/\/+$/,"")}function Gi(t=process.env){let e=(t[Rn]??"").trim(),n=(t[As]??"").trim();return!e||!n?null:{registryUrl:e,token:n}}function Wi(t){let e;try{e=new URL(t)}catch{return`${Rn} 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:`${Rn} 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,Sy,_y,H,Rn,As,fr,Et=j(()=>{Vi();X=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="ApiError"}status;body};Sy="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";_y="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";H=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=ou(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=e.retry===!1?n:Ps(n,e.retry??{})}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){if($y()){let u=tu(a);throw new X(`${e} ${n} \u2192 ${o.status}${u?`: ${u}`:""}`,o.status,a)}if(ru(o.status,a))throw new X(_y,o.status,a);let l=nu(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 platformEvents(e={}){let n=new URLSearchParams;e.subsystem&&n.set("subsystem",e.subsystem),e.severity&&n.set("severity",e.severity),e.code&&n.set("code",e.code),e.since&&n.set("since",e.since),e.after&&n.set("after",e.after),e.correlationId&&n.set("correlationId",e.correlationId),e.extension&&n.set("extension",e.extension),e.conduit&&n.set("conduit",e.conduit),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/events${r}`)).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,n={}){return this.request("POST","/v1/config/apply",{bundle:e,...n.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],roles:e.roles??[],labels:e.labels??[]})}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`)}},Rn="TURBOBASE_REGISTRY_URL",As="TURBOBASE_REGISTRY_TOKEN";fr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=ou(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=nu(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(xy.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Ey(){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:")||Ay(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:Ry,loader:"js"}))}}}function Ay(t){let e=t.startsWith("node:")?t.slice(5):t;return Py.has(e.split("/")[0])}function iu(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function Iy(){try{return(await import("esbuild")).build}catch(t){throw iu("esbuild",t)}}async function Cy(){try{return(await import("isolated-vm")).default}catch(t){throw iu("isolated-vm",t)}}async function Is(t){let e=await Iy(),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:[Ey()]})}catch(r){let o=r.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new Ji(o||`extension bundle failed: ${String(r)}`)}return n.outputFiles?.[0]?.text??""}async function mr(t,e,n={}){let r=n.timeoutMs??200,s=n.memoryLimitMb??16,o=n.member??"run",i={patches:[],logs:[]},a=await Cy(),l=new a.Isolate({memoryLimit:s});try{let u=await l.createContext(),p=u.global,g=new a.Callback(C=>{let D=JSON.parse(String(C));i.rejection||(i.rejection=D)}),$=new a.Callback(C=>{i.patches.push(JSON.parse(String(C)))}),v=new a.Callback(C=>{let D=JSON.parse(String(C));i.logs.push(D)}),S=new a.Callback(C=>{i.result=JSON.parse(String(C))});await p.set("__tb_reject",g),await p.set("__tb_patch",$),await p.set("__tb_log",v),await p.set("__tb_result",S),await p.set("__tb_ctx_json",JSON.stringify(Oy(e)));let T=Ny(t,o),P=await(await l.compileScript(T)).run(u,{timeout:r,promise:!0});return o==="when"?{effects:i,whenResult:!!P}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Oy(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 Ny(t,e){return`
|
|
22
|
+
`}var Ay,iu=j(()=>{qi();Ki();Ki();qi();Ay=["/**"," * 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 Vi=j(()=>{hr();Kd();Wd();Xd();nu();iu()});import{homedir as Iy}from"node:os";import{join as au}from"node:path";import{promises as Gi}from"node:fs";function tt(t){return t.trim().replace(/\/+$/,"")}function Ps(){let t=process.env.TURBOBASE_HOME??au(Iy(),".turbobase");return{dir:t,file:au(t,"credentials")}}function lu(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function fr(){let{file:t}=Ps(),e;try{let o=await Gi.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))lu(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))lu(i)&&(r[o]={token:i.token,updatedAt:i.updatedAt});return{active:Cy(r),tenants:r}}function Cy(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 Wi(t){let{dir:e,file:n}=Ps();await Gi.mkdir(e,{recursive:!0,mode:448}),await Gi.writeFile(n,JSON.stringify(t,null,2)+`
|
|
24
|
+
`,{mode:384})}async function cu(t){let e=tt(t.baseUrl),n=await fr(),r=new Date().toISOString();return n.tenants[e]={token:t.token,updatedAt:r},n.active=e,await Wi(n),{baseUrl:e,token:t.token,updatedAt:r}}async function pt(t){let e=await fr();if(t){let o=tt(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 As(t){let e=tt(t),n=await fr(),r=n.tenants[e];return r?(n.active=e,await Wi(n),{baseUrl:e,token:r.token,updatedAt:r.updatedAt}):null}async function Ji(t){let e=await fr(),n=t?tt(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 Wi(e),n}async function It(){let t=await fr();return Object.entries(t.tenants).map(([e,n])=>({baseUrl:e,token:n.token,updatedAt:n.updatedAt}))}var mr=j(()=>{});function Zi(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function Oy(t){if(t)try{return JSON.parse(t)}catch{return t}}function Ny(t,e){if(!t)return null;let n=t.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:Math.max(0,r-e)}function Ly(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function jy(t,e){let n=Ny(t.headers?.get?.("retry-after"),e),r="";try{r=await t.clone().text()}catch{return{maintenance:!1,delayMs:n}}let s=Oy(r),o=Zi(t.status,s),i=typeof s?.error=="string"?s.error:void 0;return{maintenance:o,delayMs:n??Ly(r),error:i}}function Dy(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function du(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function Yi(t){return`${Math.round(t/1e3)}s`}function Uy(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${Yi(t.delayMs)} before retrying (${Yi(t.remainingMs)} of the retry budget left).
|
|
25
|
+
`)}function My(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${Yi(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
|
|
26
|
+
`)}function Is(t,e={}){let n=e.budgetMs??6e5,r=e.defaultDelayMs??6e4,s=e.sleep??(u=>new Promise(p=>setTimeout(p,u))),o=e.now??(()=>Date.now()),i=e.onWait??Uy,a=e.onGiveUp??My;return async(u,p)=>{let g=o(),x=0;for(;;){let b=await t(u,p);if(b.status!==503||p&&!Dy(p.body))return b;let S=n-(o()-g),{maintenance:T,delayMs:R,error:P}=await jy(b,o());if(!T)return b;if(S<=0)return x>0&&a({waitedMs:o()-g,attempts:x,host:du(u),error:P}),b;let N=R??r;N=Math.min(Math.max(N,1e3),12e4),N=Math.min(N,S),x+=1,i({attempt:x,delayMs:N,remainingMs:S,host:du(u),error:P}),await s(N)}}}var Xi=j(()=>{});function uu(t){if(typeof t=="string")return t.trim();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():""}function qy(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function pu(t){let e=uu(t);return typeof t=="string"&&qy(e)?zy:e.slice(0,200)}function hu(t,e){return Zi(t,e)}function fu(t){return t instanceof Q&&hu(t.status,t.body)}function Fy(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function mu(t){return t.replace(/\/+$/,"")}function Qi(t=process.env){let e=(t[In]??"").trim(),n=(t[Cs]??"").trim();return!e||!n?null:{registryUrl:e,token:n}}function ea(t){let e;try{e=new URL(t)}catch{return`${In} 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:`${In} 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 Q,zy,By,H,In,Cs,gr,Ct=j(()=>{Xi();Q=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="ApiError"}status;body};zy="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";By="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";H=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=mu(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=e.retry===!1?n:Is(n,e.retry??{})}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){if(Fy()){let u=uu(a);throw new Q(`${e} ${n} \u2192 ${o.status}${u?`: ${u}`:""}`,o.status,a)}if(hu(o.status,a))throw new Q(By,o.status,a);let l=pu(a);throw new Q(`${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"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}async proposals(e={}){let 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 platformEvents(e={}){let n=new URLSearchParams;e.subsystem&&n.set("subsystem",e.subsystem),e.severity&&n.set("severity",e.severity),e.code&&n.set("code",e.code),e.since&&n.set("since",e.since),e.after&&n.set("after",e.after),e.correlationId&&n.set("correlationId",e.correlationId),e.extension&&n.set("extension",e.extension),e.conduit&&n.set("conduit",e.conduit),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/events${r}`)).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,n={}){return this.request("POST","/v1/config/apply",{bundle:e,...n.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],roles:e.roles??[],labels:e.labels??[]})}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`)}},In="TURBOBASE_REGISTRY_URL",Cs="TURBOBASE_REGISTRY_TOKEN";gr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=mu(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=pu(a);throw new Q(`${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}:{}})}}});import{existsSync as Hy,statSync as Ky}from"node:fs";import{resolve as Os,sep as gu}from"node:path";function bu(t){if(Gy.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Jy(t,e,n){let r=Os(e,n),s=Os(t);if(r!==s&&!r.startsWith(s+gu))return null;let o=[r];/\.(js|mjs|cjs)$/.test(r)&&o.push(r.replace(/\.js$/,".ts"),r.replace(/\.mjs$/,".mts"),r.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(r)||o.push(`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}/index.ts`,`${r}/index.js`);for(let i of o)if(i.startsWith(s+gu)&&Hy(i)&&Ky(i).isFile())return i;return null}function yu(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},n=>{if(n.kind==="entry-point")return null;if(bu(n.path))return{path:n.path,namespace:"extension-sdk"};let r=n.path.startsWith(".")||n.path.startsWith("/");if(r&&t){let o=Jy(t,n.resolveDir,n.path);if(o)return{path:o}}return{errors:[{text:`extension ${r?`imports a sibling/local file ('${n.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:n.path.startsWith("node:")||Zy(n.path)?`imports a Node builtin ('${n.path}')`:`imports an external module ('${n.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:Wy,loader:"js"}))}}}function Zy(t){let e=t.startsWith("node:")?t.slice(5):t;return Yy.has(e.split("/")[0])}function wu(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 vu(){try{return(await import("esbuild")).build}catch(t){throw wu("esbuild",t)}}async function Xy(){try{return(await import("isolated-vm")).default}catch(t){throw wu("isolated-vm",t)}}async function js(t,e={}){let n=await vu(),r=e.resolveDir?Os(e.resolveDir):void 0,s;try{s=await n({stdin:{contents:t,loader:"ts",resolveDir:r??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[yu(r)]})}catch(o){let a=o.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new Ns(a||`extension bundle failed: ${String(o)}`)}return s.outputFiles?.[0]?.text??""}async function ta(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let n=await vu(),r=Os(e),s=yu(r),o={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:bu(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await n({stdin:{contents:t,loader:"ts",resolveDir:r,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[o,s]})}catch(a){let u=a.errors?.map(p=>p.text).filter(Boolean).join("; ");throw new Ns(u||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function br(t,e,n={}){let r=n.timeoutMs??Ls,s=n.memoryLimitMb??Vy,o=n.member??"run",i={patches:[],logs:[]},a=await Xy(),l=new a.Isolate({memoryLimit:s});try{let u=await l.createContext(),p=u.global,g=new a.Callback(W=>{let K=JSON.parse(String(W));i.rejection||(i.rejection=K)}),x=new a.Callback(W=>{i.patches.push(JSON.parse(String(W)))}),b=new a.Callback(W=>{let K=JSON.parse(String(W));i.logs.push(K)}),S=new a.Callback(W=>{i.result=JSON.parse(String(W))}),T=n.query,R=new a.Reference(async W=>{if(!T)throw new Error("ctx.query is not available in this context");return JSON.stringify(await T(String(W)))});await p.set("__tb_reject",g),await p.set("__tb_patch",x),await p.set("__tb_log",b),await p.set("__tb_result",S),await p.set("__tb_query",R),await p.set("__tb_ctx_json",JSON.stringify(Qy(e)));let P=ew(t,o,n.stepIndex??0),D=await(await l.compileScript(P)).run(u,{timeout:r,promise:!0});return o==="when"?{effects:i,whenResult:!!D}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Qy(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null,materialized:t.materialized??null,process:t.process??null}}function ew(t,e,n){return e==="build"?tw(t,n):`
|
|
27
27
|
"use strict";
|
|
28
28
|
(async () => {
|
|
29
29
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -55,6 +55,7 @@ ${s.join(`
|
|
|
55
55
|
metadata: __tb_ctx.metadata == null ? undefined : __tb_ctx.metadata,
|
|
56
56
|
lines: (__tb_ctx.metadata && __tb_ctx.metadata.lines) || [],
|
|
57
57
|
bindings: __tb_ctx.bindings || [],
|
|
58
|
+
materialized: __tb_ctx.materialized || [],
|
|
58
59
|
atlas: {
|
|
59
60
|
resolve(args) {
|
|
60
61
|
const k = (args.entityType || '') + '|' + (args.targetSource || '') + '|' + (args.sourceExternalId || '');
|
|
@@ -83,8 +84,12 @@ ${s.join(`
|
|
|
83
84
|
// 'when' resolves the kind's gate: a hook's is top-level \`def.when\`; a
|
|
84
85
|
// conduit's is the nested \`def.from.when\` (#572). A conduit has no
|
|
85
86
|
// top-level \`when\` (and a hook has no \`from\`), so the \`??\` picks the
|
|
86
|
-
// right one without a kind discriminator. 'run'/'transform' are the body
|
|
87
|
-
|
|
87
|
+
// right one without a kind discriminator. 'run'/'transform' are the body;
|
|
88
|
+
// a conduit with a \`sequence\` has one transform per target, and
|
|
89
|
+
// \`stepIndex\` picks which (turbobase-dev#1514, AC10).
|
|
90
|
+
const fn = ${e==="when"?"(def.when || (def.from && def.from.when))":e==="transform"?`(Array.isArray(def.sequence) && def.sequence[${Number(n)}]
|
|
91
|
+
? def.sequence[${Number(n)}].transform
|
|
92
|
+
: def.transform)`:`def[${JSON.stringify(e)}]`};
|
|
88
93
|
if (typeof fn !== 'function') {
|
|
89
94
|
${e==="when"?"return true;":e==="transform"?"throw new Error('conduit default export has no transform() function');":"throw new Error('extension default export has no run() function');"}
|
|
90
95
|
}
|
|
@@ -92,36 +97,75 @@ ${s.join(`
|
|
|
92
97
|
${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
|
|
93
98
|
return ${e==="when"?"out":"undefined"};
|
|
94
99
|
})()
|
|
95
|
-
`}
|
|
100
|
+
`}function tw(t,e){return`
|
|
101
|
+
"use strict";
|
|
102
|
+
(async () => {
|
|
103
|
+
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
104
|
+
const __tb_process = __tb_ctx.process || {};
|
|
105
|
+
const ctx = {
|
|
106
|
+
input: __tb_process.input,
|
|
107
|
+
runId: __tb_process.runId,
|
|
108
|
+
steps: __tb_process.steps || {},
|
|
109
|
+
async query(q) {
|
|
110
|
+
const json = await __tb_query.apply(undefined, [String(q)], {
|
|
111
|
+
arguments: { copy: true },
|
|
112
|
+
result: { promise: true, copy: true },
|
|
113
|
+
});
|
|
114
|
+
return JSON.parse(json);
|
|
115
|
+
},
|
|
116
|
+
log(level, message, meta) {
|
|
117
|
+
__tb_log(JSON.stringify({ level, message, meta }));
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
// ---- bundled extension module (IIFE assigns __tb_extension_module) ----
|
|
122
|
+
${t}
|
|
123
|
+
|
|
124
|
+
const def = (typeof __tb_extension_module !== 'undefined' && __tb_extension_module)
|
|
125
|
+
? __tb_extension_module.default
|
|
126
|
+
: undefined;
|
|
127
|
+
if (!def || typeof def !== 'object') {
|
|
128
|
+
throw new Error('extension bundle has no default export (use export default defineProcess({...}))');
|
|
129
|
+
}
|
|
130
|
+
const step = Array.isArray(def.steps) ? def.steps[${Number(e)}] : undefined;
|
|
131
|
+
if (!step || typeof step.build !== 'function') {
|
|
132
|
+
throw new Error('process step ${Number(e)} has no build() function');
|
|
133
|
+
}
|
|
134
|
+
const out = await step.build(ctx);
|
|
135
|
+
__tb_result(JSON.stringify(out == null ? null : out));
|
|
136
|
+
return undefined;
|
|
137
|
+
})()
|
|
138
|
+
`}var Ls,Vy,Gy,Wy,Ns,Yy,Ds=j(()=>{Ls=200,Vy=16,Gy=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@/sync/processes","@/sync/processes/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit","@turbobase/extensions/process"]);Wy=`
|
|
96
139
|
export const defineHook = (def) => def;
|
|
97
140
|
export const defineConduit = (def) => def;
|
|
141
|
+
export const defineProcess = (def) => def;
|
|
98
142
|
export default defineHook;
|
|
99
|
-
|
|
143
|
+
`;Ns=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};Yy=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 na}from"node:fs";import{join as nw}from"node:path";function rw(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 sw(t,e,n){let r=e.name??n,s=e.expect??"pass";try{let{effects:o}=await br(t,rw(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 Us(t,e,n={}){let r=await js(t,{resolveDir:n.resolveDir}),s=[];for(let o=0;o<e.length;o+=1)s.push(await sw(r,e[o],`sample[${o}]`));return s}async function yr(t){let e;try{e=await na.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 na.readFile(nw(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 wr(t){return na.readFile(t,"utf8")}var ra=j(()=>{Ds()});function Ge(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function jw(t){let e=t.recordType;if(!e)throw new We("record type is required (e.g. --record=salesOrder)");let n=t.event??"before_save",r=t.template??"require-field",s=t.source,o=s?`
|
|
100
144
|
source: ${JSON.stringify(s)},`:"",i,a;if(r==="blank")i=`
|
|
101
145
|
run: (ctx) => {
|
|
102
146
|
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
103
147
|
// with ctx.patch({...}); observe with ctx.log('info', '...').
|
|
104
|
-
},`,a="custom";else if(r==="require-field"){let
|
|
148
|
+
},`,a="custom";else if(r==="require-field"){let x=t.field;if(!x)throw new We("require-field template needs --field=<name>");i=`
|
|
105
149
|
run: (ctx) => {
|
|
106
|
-
const v = ctx.payload[${JSON.stringify(
|
|
150
|
+
const v = ctx.payload[${JSON.stringify(x)}];
|
|
107
151
|
if (v === undefined || v === null || v === '') {
|
|
108
152
|
ctx.reject({
|
|
109
153
|
code: 'MANDATORY_FIELD_MISSING',
|
|
110
|
-
field: ${JSON.stringify(
|
|
111
|
-
message: ${JSON.stringify(`${
|
|
154
|
+
field: ${JSON.stringify(x)},
|
|
155
|
+
message: ${JSON.stringify(`${x} is required`)},
|
|
112
156
|
});
|
|
113
157
|
}
|
|
114
|
-
},`,a=`require-field-${
|
|
158
|
+
},`,a=`require-field-${x}`}else if(r==="enforce-format"){let x=t.field;if(!x)throw new We("enforce-format template needs --field=<name>");if(!t.regex)throw new We("enforce-format template needs --regex=<pattern>");i=`
|
|
115
159
|
run: (ctx) => {
|
|
116
|
-
const v = ctx.payload[${JSON.stringify(
|
|
160
|
+
const v = ctx.payload[${JSON.stringify(x)}];
|
|
117
161
|
if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
|
|
118
162
|
ctx.reject({
|
|
119
163
|
code: 'INVALID_FORMAT',
|
|
120
|
-
field: ${JSON.stringify(
|
|
121
|
-
message: ${JSON.stringify(`${
|
|
164
|
+
field: ${JSON.stringify(x)},
|
|
165
|
+
message: ${JSON.stringify(`${x} does not match expected format`)},
|
|
122
166
|
});
|
|
123
167
|
}
|
|
124
|
-
},`,a=`enforce-format-${
|
|
168
|
+
},`,a=`enforce-format-${x}`}else throw new We(`unsupported template: ${r}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${Ge(t.regex).slice(0,24)}`:""}`,p=`/**
|
|
125
169
|
* ${t.description??`${a} on ${e}.${n}`}
|
|
126
170
|
*
|
|
127
171
|
* Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
|
|
@@ -134,7 +178,7 @@ export default defineHook<Record<string, unknown>>({
|
|
|
134
178
|
recordType: ${JSON.stringify(e)},
|
|
135
179
|
event: ${JSON.stringify(n)},${o}${i}
|
|
136
180
|
});
|
|
137
|
-
`;return{relativePath:`hooks/${e}/${n}.${a}.ts`,content:p}}function
|
|
181
|
+
`;return{relativePath:`hooks/${e}/${n}.${a}.ts`,content:p}}function Dw(t){let e=t.recordType;if(!e)throw new We("record type is required (e.g. --record=order)");let n=t.source;if(!n)throw new We("--source is required (the origin source, e.g. --source=shopify)");let r=t.to;if(!r)throw new We("--to is required (the target source, e.g. --to=netsuite)");if(n===r)throw new We(`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??`${Ge(n)}2${Ge(r)}:${Ge(e)}`,l=`/**
|
|
138
182
|
* ${t.description??`Bridge ${n} ${e} \u2192 ${r} ${s} (${o}).`}
|
|
139
183
|
*
|
|
140
184
|
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
@@ -177,7 +221,56 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
177
221
|
},
|
|
178
222
|
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
179
223
|
});
|
|
180
|
-
`;return{relativePath:`conduits/${
|
|
224
|
+
`;return{relativePath:`conduits/${Ge(n)}-${Ge(e)}-to-${Ge(r)}-${Ge(s)}.ts`,content:l}}function Uw(t){let e=t.recordType;if(!e)throw new We("record type is required (e.g. --record=purchaseOrder)");let n=t.then,r=t.onFailure??"stop";if(r!=="stop"&&r!=="rollback")throw new We(`--on-failure must be stop | rollback (got ${r})`);let s=n?`${Ge(e)}-then-${Ge(n)}`:Ge(e),o=t.id??`custom:process:${s}`,i=t.description??(n?`Raise a ${e}, wait for the source, then raise a ${n}.`:`Raise a ${e}.`),a=n?`
|
|
225
|
+
{
|
|
226
|
+
id: ${JSON.stringify(Ge(n))},
|
|
227
|
+
recordType: ${JSON.stringify(n)},
|
|
228
|
+
build: (ctx) => ({
|
|
229
|
+
parent: {
|
|
230
|
+
// The first step declared awaitSource, so its source-minted id is here.
|
|
231
|
+
created_from_id: ctx.steps[${JSON.stringify(Ge(e))}]?.externalId ?? null,
|
|
232
|
+
// ...mapped fields from ctx.input...
|
|
233
|
+
},
|
|
234
|
+
}),
|
|
235
|
+
},`:"",l=`/**
|
|
236
|
+
* ${i}
|
|
237
|
+
*
|
|
238
|
+
* Scaffolded by \`turbobase ext new process\`. A process is INVOKED by an app
|
|
239
|
+
* (POST /v1/processes/${o}) and runs its steps on the server, in order, through
|
|
240
|
+
* the same write boundary the app's own writes use \u2014 hooks, guardrails and RLS
|
|
241
|
+
* all apply, as the invoking user. Every step's \`build\` is PURE: it returns
|
|
242
|
+
* the write payload and never calls a source API. Read with \`ctx.query\`
|
|
243
|
+
* (scoped to the invoking user, exactly like POST /v1/batch).
|
|
244
|
+
*
|
|
245
|
+
* Edit freely, then \`turbobase ext test\` and \`turbobase ext deploy\`.
|
|
246
|
+
*/
|
|
247
|
+
import { defineProcess } from '@turbobase/extensions';
|
|
248
|
+
|
|
249
|
+
export default defineProcess({
|
|
250
|
+
id: ${JSON.stringify(o)},
|
|
251
|
+
description: ${JSON.stringify(i)},
|
|
252
|
+
input: {
|
|
253
|
+
type: 'object',
|
|
254
|
+
properties: {
|
|
255
|
+
// ...the typed input the app sends, as JSON Schema...
|
|
256
|
+
},
|
|
257
|
+
required: [],
|
|
258
|
+
},
|
|
259
|
+
steps: [
|
|
260
|
+
{
|
|
261
|
+
id: ${JSON.stringify(Ge(e))},
|
|
262
|
+
recordType: ${JSON.stringify(e)},${n?`
|
|
263
|
+
awaitSource: true,`:""}
|
|
264
|
+
build: (ctx) => ({
|
|
265
|
+
parent: {
|
|
266
|
+
// ...mapped fields from ctx.input...
|
|
267
|
+
},
|
|
268
|
+
}),
|
|
269
|
+
},${a}
|
|
270
|
+
],
|
|
271
|
+
onFailure: ${JSON.stringify(r)},
|
|
272
|
+
});
|
|
273
|
+
`;return{relativePath:`processes/${s}.ts`,content:l}}function $t(t,e){let n=Mw[t];if(!n)throw new We(`unknown extension kind '${t}'. Scaffoldable kinds: ${Ku.join(", ")}.`);return n(e)}var Ku,We,Mw,Fs=j(()=>{Ku=["hook","conduit","process"];We=class extends Error{};Mw={hook:jw,conduit:Dw,process:Uw}});var ka,Sa=j(()=>{ka=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function Uk(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 Mk(t){return ih[Uk(t)%ih.length]}function qk(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 ah(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function lh(t,e){let[n,r]=Mk(t),s=ah(qk(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${ah(e)}">
|
|
181
274
|
<defs>
|
|
182
275
|
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
183
276
|
<stop offset="0" stop-color="${n}"/>
|
|
@@ -187,9 +280,9 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
187
280
|
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
188
281
|
<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>
|
|
189
282
|
</svg>
|
|
190
|
-
`}var
|
|
191
|
-
`}function
|
|
192
|
-
`}function
|
|
283
|
+
`}var ih,ch=j(()=>{ih=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var xh={};qd(xh,{CN_UTIL:()=>mh,COMPONENTS_JSON:()=>fh,MAIN_TSX:()=>bh,STYLES_CSS:()=>yh,TSCONFIG:()=>hh,TURBOBASE_CLIENT:()=>dh,UI_BADGE:()=>kh,UI_BUTTON:()=>wh,UI_CARD:()=>vh,UI_INPUT:()=>_h,UI_LABEL:()=>$h,UI_TABLE:()=>Sh,indexHtml:()=>gh,instanceOriginFromEnv:()=>Jk,packageJson:()=>uh,scaffoldAppFiles:()=>Zk,starterApp:()=>Xk,viteConfig:()=>ph});function Fk(t,e){let n=t.trim();if(n.length<=e)return n;let r=n.slice(0,e);return r.replace(/[\s\p{P}\p{S}]+$/u,"")||r}function Hk(t){let e={name:Fk(t.title,Bk)},n=(t.description??"").trim().slice(0,zk);return n&&(e.description=n),e.icon="favicon.svg",e.learnings={...ka},JSON.stringify(e,null,2)+`
|
|
284
|
+
`}function uh(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:Kk},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^19.2.0","@types/react-dom":"^19.2.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
|
|
285
|
+
`}function Wk(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 Jk(t=process.env){let e=(t.TENANT_SLUG??"").trim(),n=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!n))return`https://${e}.${n}`}function ph(t,e={}){let n=Wk(e.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
193
286
|
import { fileURLToPath, URL } from 'node:url';
|
|
194
287
|
import react from '@vitejs/plugin-react';
|
|
195
288
|
// Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
|
|
@@ -208,8 +301,8 @@ import tailwindcss from '@tailwindcss/vite';
|
|
|
208
301
|
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
209
302
|
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
210
303
|
// them at boot; restart the dev server after changing one).
|
|
211
|
-
const TENANT = process.env.SUPABASE_URL || '${n??
|
|
212
|
-
const API = process.env.TURBOBASE_API_URL || '${n??
|
|
304
|
+
const TENANT = process.env.SUPABASE_URL || '${n??Vk}'; // /rest + the Realtime WS
|
|
305
|
+
const API = process.env.TURBOBASE_API_URL || '${n??Gk}'; // /v1, /auth, /login, /_app
|
|
213
306
|
|
|
214
307
|
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
215
308
|
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
@@ -247,7 +340,7 @@ export default defineConfig({
|
|
|
247
340
|
},
|
|
248
341
|
build: { outDir: 'dist' },
|
|
249
342
|
});
|
|
250
|
-
`}function
|
|
343
|
+
`}function gh(t){return`<!doctype html>
|
|
251
344
|
<html lang="en">
|
|
252
345
|
<head>
|
|
253
346
|
<meta charset="UTF-8" />
|
|
@@ -260,7 +353,7 @@ export default defineConfig({
|
|
|
260
353
|
<script type="module" src="/src/main.tsx"></script>
|
|
261
354
|
</body>
|
|
262
355
|
</html>
|
|
263
|
-
`}function
|
|
356
|
+
`}function Zk(t){return{"package.json":uh(t.slug),"vite.config.ts":ph(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":Yk,"tsconfig.json":hh,"index.html":gh(t.title),"public/turbobase.json":Hk(t),"public/favicon.svg":lh(t.slug,t.title),"src/main.tsx":bh,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":dh,"src/styles.css":yh,"components.json":fh,"src/lib/utils.ts":mh,"src/components/ui/button.tsx":wh,"src/components/ui/card.tsx":vh,"src/components/ui/badge.tsx":kh,"src/components/ui/table.tsx":Sh,"src/components/ui/input.tsx":_h,"src/components/ui/label.tsx":$h,"README.md":`# ${t.title}
|
|
264
357
|
|
|
265
358
|
\`\`\`sh
|
|
266
359
|
npm install
|
|
@@ -281,7 +374,7 @@ every read comes back "permission denied", which looks like an RLS problem.
|
|
|
281
374
|
|
|
282
375
|
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
283
376
|
live access token and is gitignored \u2014 keep it that way.
|
|
284
|
-
`}}function
|
|
377
|
+
`}}function Xk(t){return`import React from 'react';
|
|
285
378
|
import { Loader2, Trash2 } from 'lucide-react';
|
|
286
379
|
|
|
287
380
|
import { select, write, del } from '@/lib/turbobase';
|
|
@@ -506,7 +599,7 @@ export default function App() {
|
|
|
506
599
|
</main>
|
|
507
600
|
);
|
|
508
601
|
}
|
|
509
|
-
`}var
|
|
602
|
+
`}var zk,Bk,dh,Pr,Kk,Vk,Gk,Yk,hh,fh,mh,bh,yh,wh,vh,kh,Sh,_h,$h,Th=j(()=>{ch();Sa();zk=200,Bk=60;dh=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
|
|
510
603
|
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
511
604
|
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
512
605
|
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
@@ -1523,7 +1616,7 @@ export async function selectPage<T = unknown>(
|
|
|
1523
1616
|
}
|
|
1524
1617
|
return { rows, nextCursor };
|
|
1525
1618
|
}
|
|
1526
|
-
`,
|
|
1619
|
+
`,Pr="src/types.ts",Kk=`turbobase project types -o ${Pr} || node -e "if(require('node:fs').existsSync('${Pr}')){console.error('turbobase: could not refresh ${Pr} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${Pr} 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 ${Pr}');process.exit(1)}"`;Vk="http://localhost:54331",Gk="http://localhost:4100";Yk=`node_modules/
|
|
1527
1620
|
dist/
|
|
1528
1621
|
build/
|
|
1529
1622
|
|
|
@@ -1535,9 +1628,9 @@ build/
|
|
|
1535
1628
|
!.env.example
|
|
1536
1629
|
|
|
1537
1630
|
.DS_Store
|
|
1538
|
-
`,
|
|
1539
|
-
`,
|
|
1540
|
-
`,
|
|
1631
|
+
`,hh=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
|
|
1632
|
+
`,fh=`${JSON.stringify({$schema:"https://ui.shadcn.com/schema.json",style:"new-york",rsc:!1,tsx:!0,tailwind:{config:"",css:"src/styles.css",baseColor:"neutral",cssVariables:!0,prefix:""},aliases:{components:"@/components",utils:"@/lib/utils",ui:"@/components/ui",lib:"@/lib",hooks:"@/hooks"},iconLibrary:"lucide"},null,2)}
|
|
1633
|
+
`,mh=`import { clsx, type ClassValue } from 'clsx';
|
|
1541
1634
|
import { twMerge } from 'tailwind-merge';
|
|
1542
1635
|
|
|
1543
1636
|
/**
|
|
@@ -1551,7 +1644,7 @@ import { twMerge } from 'tailwind-merge';
|
|
|
1551
1644
|
export function cn(...inputs: ClassValue[]) {
|
|
1552
1645
|
return twMerge(clsx(inputs));
|
|
1553
1646
|
}
|
|
1554
|
-
`;
|
|
1647
|
+
`;bh=`import React from 'react';
|
|
1555
1648
|
import { createRoot } from 'react-dom/client';
|
|
1556
1649
|
import App from './App';
|
|
1557
1650
|
import './styles.css';
|
|
@@ -1561,7 +1654,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
1561
1654
|
<App />
|
|
1562
1655
|
</React.StrictMode>,
|
|
1563
1656
|
);
|
|
1564
|
-
`,
|
|
1657
|
+
`,yh=`@import 'tailwindcss';
|
|
1565
1658
|
@import 'tw-animate-css';
|
|
1566
1659
|
|
|
1567
1660
|
/* Inter, self-hosted \u2014 the design system's font.
|
|
@@ -1649,7 +1742,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
1649
1742
|
transition-duration: 0.01ms !important;
|
|
1650
1743
|
}
|
|
1651
1744
|
}
|
|
1652
|
-
`,
|
|
1745
|
+
`,wh=`import * as React from 'react';
|
|
1653
1746
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
1654
1747
|
|
|
1655
1748
|
import { cn } from '@/lib/utils';
|
|
@@ -1689,7 +1782,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|
|
1689
1782
|
Button.displayName = 'Button';
|
|
1690
1783
|
|
|
1691
1784
|
export { Button, buttonVariants };
|
|
1692
|
-
`,
|
|
1785
|
+
`,vh=`import * as React from 'react';
|
|
1693
1786
|
|
|
1694
1787
|
import { cn } from '@/lib/utils';
|
|
1695
1788
|
|
|
@@ -1727,7 +1820,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
|
|
|
1727
1820
|
CardContent.displayName = 'CardContent';
|
|
1728
1821
|
|
|
1729
1822
|
export { Card, CardHeader, CardTitle, CardDescription, CardContent };
|
|
1730
|
-
`,
|
|
1823
|
+
`,kh=`import * as React from 'react';
|
|
1731
1824
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
1732
1825
|
|
|
1733
1826
|
import { cn } from '@/lib/utils';
|
|
@@ -1762,7 +1855,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
|
|
|
1762
1855
|
}
|
|
1763
1856
|
|
|
1764
1857
|
export { Badge, badgeVariants };
|
|
1765
|
-
`,
|
|
1858
|
+
`,Sh=`import * as React from 'react';
|
|
1766
1859
|
|
|
1767
1860
|
import { cn } from '@/lib/utils';
|
|
1768
1861
|
|
|
@@ -1821,7 +1914,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
|
|
|
1821
1914
|
TableCell.displayName = 'TableCell';
|
|
1822
1915
|
|
|
1823
1916
|
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
|
|
1824
|
-
`,
|
|
1917
|
+
`,_h=`import * as React from 'react';
|
|
1825
1918
|
|
|
1826
1919
|
import { cn } from '@/lib/utils';
|
|
1827
1920
|
|
|
@@ -1841,7 +1934,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
|
|
|
1841
1934
|
Input.displayName = 'Input';
|
|
1842
1935
|
|
|
1843
1936
|
export { Input };
|
|
1844
|
-
|
|
1937
|
+
`,$h=`import * as React from 'react';
|
|
1845
1938
|
|
|
1846
1939
|
import { cn } from '@/lib/utils';
|
|
1847
1940
|
|
|
@@ -1858,51 +1951,51 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
|
|
|
1858
1951
|
Label.displayName = 'Label';
|
|
1859
1952
|
|
|
1860
1953
|
export { Label };
|
|
1861
|
-
`});import*as
|
|
1862
|
-
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function fh(t){return t.description}function mh(t){if(kt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Un(t){if(kt(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 Rr=j(()=>{});import*as c from"zod/v4";function Ch(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Oh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Aa,gh,Vt,eo,xe,bh,yh,nC,Ak,Ik,Ia,Ze,Er,wh,Pe,rt,st,Ae,to,vh,Ca,kh,Sh,Oa,Pr,K,Na,_h,$h,rC,no,Ck,ro,Ok,Ar,Mn,xh,Nk,Lk,jk,Dk,Uk,Mk,La,zk,qk,ja,so,Bk,Fk,oo,Hk,Ir,Cr,Kk,Or,zn,Vk,Nr,io,ao,lo,sC,co,uo,po,Th,Rh,Eh,Da,Ph,Lr,qn,Ah,Gk,ho,Wk,fo,Jk,Ua,Yk,mo,Zk,Xk,Qk,eS,tS,nS,rS,sS,oS,iS,go,aS,lS,bo,Ma,za,qa,cS,dS,uS,Ba,pS,hS,fS,mS,gS,Ih,yo,bS,wo,oC,yS,Bn,wS,iC,jr,vS,Fa,kS,SS,_S,$S,xS,TS,RS,Qs,ES,PS,AS,Dr,Ha,IS,CS,OS,NS,LS,jS,DS,US,MS,zS,qS,BS,FS,HS,KS,VS,GS,WS,Fn,JS,YS,ZS,vo,XS,QS,e_,Ka,t_,aC,lC,cC,dC,uC,pC,z,Pa,Hn=j(()=>{Aa="2025-11-25",gh=[Aa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Vt="io.modelcontextprotocol/related-task",eo="2.0",xe=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),bh=c.union([c.string(),c.number().int()]),yh=c.string(),nC=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),Ak=c.object({ttl:c.number().optional()}),Ik=c.object({taskId:c.string()}),Ia=c.looseObject({progressToken:bh.optional(),[Vt]:Ik.optional()}),Ze=c.object({_meta:Ia.optional()}),Er=Ze.extend({task:Ak.optional()}),wh=t=>Er.safeParse(t).success,Pe=c.object({method:c.string(),params:Ze.loose().optional()}),rt=c.object({_meta:Ia.optional()}),st=c.object({method:c.string(),params:rt.loose().optional()}),Ae=c.looseObject({_meta:Ia.optional()}),to=c.union([c.string(),c.number().int()]),vh=c.object({jsonrpc:c.literal(eo),id:to,...Pe.shape}).strict(),Ca=t=>vh.safeParse(t).success,kh=c.object({jsonrpc:c.literal(eo),...st.shape}).strict(),Sh=t=>kh.safeParse(t).success,Oa=c.object({jsonrpc:c.literal(eo),id:to,result:Ae}).strict(),Pr=t=>Oa.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"})(K||(K={}));Na=c.object({jsonrpc:c.literal(eo),id:to.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),_h=t=>Na.safeParse(t).success,$h=c.union([vh,kh,Oa,Na]),rC=c.union([Oa,Na]),no=Ae.strict(),Ck=rt.extend({requestId:to.optional(),reason:c.string().optional()}),ro=st.extend({method:c.literal("notifications/cancelled"),params:Ck}),Ok=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Ar=c.object({icons:c.array(Ok).optional()}),Mn=c.object({name:c.string(),title:c.string().optional()}),xh=Mn.extend({...Mn.shape,...Ar.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),Nk=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),Lk=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:Nk.optional(),url:xe.optional()}),c.record(c.string(),c.unknown()).optional())),jk=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()}),Dk=c.looseObject({list:xe.optional(),cancel:xe.optional(),requests:c.looseObject({tools:c.looseObject({call:xe.optional()}).optional()}).optional()}),Uk=c.object({experimental:c.record(c.string(),xe).optional(),sampling:c.object({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:Lk.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:jk.optional(),extensions:c.record(c.string(),xe).optional()}),Mk=Ze.extend({protocolVersion:c.string(),capabilities:Uk,clientInfo:xh}),La=Pe.extend({method:c.literal("initialize"),params:Mk}),zk=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:Dk.optional(),extensions:c.record(c.string(),xe).optional()}),qk=Ae.extend({protocolVersion:c.string(),capabilities:zk,serverInfo:xh,instructions:c.string().optional()}),ja=st.extend({method:c.literal("notifications/initialized"),params:rt.optional()}),so=Pe.extend({method:c.literal("ping"),params:Ze.optional()}),Bk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),Fk=c.object({...rt.shape,...Bk.shape,progressToken:bh}),oo=st.extend({method:c.literal("notifications/progress"),params:Fk}),Hk=Ze.extend({cursor:yh.optional()}),Ir=Pe.extend({params:Hk.optional()}),Cr=Ae.extend({nextCursor:yh.optional()}),Kk=c.enum(["working","input_required","completed","failed","cancelled"]),Or=c.object({taskId:c.string(),status:Kk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),zn=Ae.extend({task:Or}),Vk=rt.merge(Or),Nr=st.extend({method:c.literal("notifications/tasks/status"),params:Vk}),io=Pe.extend({method:c.literal("tasks/get"),params:Ze.extend({taskId:c.string()})}),ao=Ae.merge(Or),lo=Pe.extend({method:c.literal("tasks/result"),params:Ze.extend({taskId:c.string()})}),sC=Ae.loose(),co=Ir.extend({method:c.literal("tasks/list")}),uo=Cr.extend({tasks:c.array(Or)}),po=Pe.extend({method:c.literal("tasks/cancel"),params:Ze.extend({taskId:c.string()})}),Th=Ae.merge(Or),Rh=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),Eh=Rh.extend({text:c.string()}),Da=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ph=Rh.extend({blob:Da}),Lr=c.enum(["user","assistant"]),qn=c.object({audience:c.array(Lr).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),Ah=c.object({...Mn.shape,...Ar.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:qn.optional(),_meta:c.optional(c.looseObject({}))}),Gk=c.object({...Mn.shape,...Ar.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:qn.optional(),_meta:c.optional(c.looseObject({}))}),ho=Ir.extend({method:c.literal("resources/list")}),Wk=Cr.extend({resources:c.array(Ah)}),fo=Ir.extend({method:c.literal("resources/templates/list")}),Jk=Cr.extend({resourceTemplates:c.array(Gk)}),Ua=Ze.extend({uri:c.string()}),Yk=Ua,mo=Pe.extend({method:c.literal("resources/read"),params:Yk}),Zk=Ae.extend({contents:c.array(c.union([Eh,Ph]))}),Xk=st.extend({method:c.literal("notifications/resources/list_changed"),params:rt.optional()}),Qk=Ua,eS=Pe.extend({method:c.literal("resources/subscribe"),params:Qk}),tS=Ua,nS=Pe.extend({method:c.literal("resources/unsubscribe"),params:tS}),rS=rt.extend({uri:c.string()}),sS=st.extend({method:c.literal("notifications/resources/updated"),params:rS}),oS=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),iS=c.object({...Mn.shape,...Ar.shape,description:c.optional(c.string()),arguments:c.optional(c.array(oS)),_meta:c.optional(c.looseObject({}))}),go=Ir.extend({method:c.literal("prompts/list")}),aS=Cr.extend({prompts:c.array(iS)}),lS=Ze.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),bo=Pe.extend({method:c.literal("prompts/get"),params:lS}),Ma=c.object({type:c.literal("text"),text:c.string(),annotations:qn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),za=c.object({type:c.literal("image"),data:Da,mimeType:c.string(),annotations:qn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),qa=c.object({type:c.literal("audio"),data:Da,mimeType:c.string(),annotations:qn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),cS=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()}),dS=c.object({type:c.literal("resource"),resource:c.union([Eh,Ph]),annotations:qn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),uS=Ah.extend({type:c.literal("resource_link")}),Ba=c.union([Ma,za,qa,uS,dS]),pS=c.object({role:Lr,content:Ba}),hS=Ae.extend({description:c.string().optional(),messages:c.array(pS)}),fS=st.extend({method:c.literal("notifications/prompts/list_changed"),params:rt.optional()}),mS=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),gS=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),Ih=c.object({...Mn.shape,...Ar.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:mS.optional(),execution:gS.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),yo=Ir.extend({method:c.literal("tools/list")}),bS=Cr.extend({tools:c.array(Ih)}),wo=Ae.extend({content:c.array(Ba).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),oC=wo.or(Ae.extend({toolResult:c.unknown()})),yS=Er.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Bn=Pe.extend({method:c.literal("tools/call"),params:yS}),wS=st.extend({method:c.literal("notifications/tools/list_changed"),params:rt.optional()}),iC=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),jr=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),vS=Ze.extend({level:jr}),Fa=Pe.extend({method:c.literal("logging/setLevel"),params:vS}),kS=rt.extend({level:jr,logger:c.string().optional(),data:c.unknown()}),SS=st.extend({method:c.literal("notifications/message"),params:kS}),_S=c.object({name:c.string().optional()}),$S=c.object({hints:c.array(_S).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()}),xS=c.object({mode:c.enum(["auto","required","none"]).optional()}),TS=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()}),RS=c.discriminatedUnion("type",[Ma,za,qa]),Qs=c.discriminatedUnion("type",[Ma,za,qa,cS,TS]),ES=c.object({role:Lr,content:c.union([Qs,c.array(Qs)]),_meta:c.record(c.string(),c.unknown()).optional()}),PS=Er.extend({messages:c.array(ES),modelPreferences:$S.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(Ih).optional(),toolChoice:xS.optional()}),AS=Pe.extend({method:c.literal("sampling/createMessage"),params:PS}),Dr=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Lr,content:RS}),Ha=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Lr,content:c.union([Qs,c.array(Qs)])}),IS=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),CS=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()}),OS=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()}),NS=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),LS=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()}),jS=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()}),DS=c.union([NS,LS]),US=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()}),MS=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()}),zS=c.union([US,MS]),qS=c.union([jS,DS,zS]),BS=c.union([qS,IS,CS,OS]),FS=Er.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),BS),required:c.array(c.string()).optional()})}),HS=Er.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),KS=c.union([FS,HS]),VS=Pe.extend({method:c.literal("elicitation/create"),params:KS}),GS=rt.extend({elicitationId:c.string()}),WS=st.extend({method:c.literal("notifications/elicitation/complete"),params:GS}),Fn=Ae.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())}),JS=c.object({type:c.literal("ref/resource"),uri:c.string()}),YS=c.object({type:c.literal("ref/prompt"),name:c.string()}),ZS=Ze.extend({ref:c.union([YS,JS]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),vo=Pe.extend({method:c.literal("completion/complete"),params:ZS});XS=Ae.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),QS=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),e_=Pe.extend({method:c.literal("roots/list"),params:Ze.optional()}),Ka=Ae.extend({roots:c.array(QS)}),t_=st.extend({method:c.literal("notifications/roots/list_changed"),params:rt.optional()}),aC=c.union([so,La,vo,Fa,bo,go,ho,fo,mo,eS,nS,Bn,yo,io,lo,co,po]),lC=c.union([ro,oo,ja,t_,Nr]),cC=c.union([no,Dr,Ha,Fn,Ka,ao,uo,zn]),dC=c.union([so,AS,VS,e_,io,lo,co,po]),uC=c.union([ro,oo,SS,sS,Xk,wS,fS,Nr,WS]),pC=c.union([no,qk,XS,hS,aS,Wk,Jk,Zk,wo,bS,ao,uo,zn]),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===K.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new Pa(s.elicitations,n)}return new t(e,n,r)}},Pa=class extends z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(K.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Gt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Nh=j(()=>{});var jh,Lh,Dh,ko=j(()=>{jh=Symbol("Let zodToJsonSchema decide on which parser to use"),Lh={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"},Dh=t=>typeof t=="string"?{...Lh,name:t}:{...Lh,...t}});var Uh,Va=j(()=>{ko();Uh=t=>{let e=Dh(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 Ga(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ae(t,e,n,r,s){t[e]=n,Ga(t,e,r,s)}var Wt=j(()=>{});var So,_o=j(()=>{So=(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"?So(e,t.currentPath):e.join("/")}}var ot=j(()=>{_o()});import{ZodFirstPartyTypeKind as n_}from"zod/v3";function Mh(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==n_.ZodAny&&(n.items=J(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(n,"minItems",t.exactLength.value,t.exactLength.message,e),ae(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var Wa=j(()=>{Wt();$e()});function zh(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?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}var Ja=j(()=>{Wt()});function qh(){return{type:"boolean"}}var Ya=j(()=>{});function $o(t,e){return J(t.type._def,e)}var xo=j(()=>{$e()});var Bh,Za=j(()=>{$e();Bh=(t,e)=>J(t.innerType._def,e)});function Xa(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>Xa(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 r_(t,e)}}var r_,Qa=j(()=>{Wt();r_=(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":ae(n,"minimum",r.value,r.message,e);break;case"max":ae(n,"maximum",r.value,r.message,e);break}return n}});function Fh(t,e){return{...J(t.innerType._def,e),default:t.defaultValue()}}var el=j(()=>{$e()});function Hh(t,e){return e.effectStrategy==="input"?J(t.schema._def,e):we(e)}var tl=j(()=>{$e();ot()});function Kh(t){return{type:"string",enum:Array.from(t.values)}}var nl=j(()=>{});function Vh(t,e){let n=[J(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),J(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(s_(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 s_,rl=j(()=>{$e();s_=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Gh(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 sl=j(()=>{});function To(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ae(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":ze(n,pt.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":ze(n,r.regex,r.message,e);break;case"cuid":ze(n,pt.cuid,r.message,e);break;case"cuid2":ze(n,pt.cuid2,r.message,e);break;case"startsWith":ze(n,RegExp(`^${il(r.value,e)}`),r.message,e);break;case"endsWith":ze(n,RegExp(`${il(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":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{ze(n,RegExp(il(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":ze(n,pt.base64url,r.message,e);break;case"jwt":ze(n,pt.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&ze(n,pt.ipv4Cidr,r.message,e),r.version!=="v4"&&ze(n,pt.ipv6Cidr,r.message,e);break}case"emoji":ze(n,pt.emoji(),r.message,e);break;case"ulid":{ze(n,pt.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ht(n,"binary",r.message,e);break}case"contentEncoding:base64":{ae(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{ze(n,pt.base64,r.message,e);break}}break}case"nanoid":ze(n,pt.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function il(t,e){return e.patternStrategy==="escape"?i_(t):t}function i_(t){let e="";for(let n=0;n<t.length;n++)o_.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}}})):ae(t,"format",e,n,r)}function ze(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:Wh(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ae(t,"pattern",Wh(e,r),n,r)}function Wh(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
|
|
1954
|
+
`});import*as Rh from"zod/v3";import*as mn from"zod/v4-mini";function xt(t){return!!t._zod}function gn(t){let e=Object.values(t);if(e.length===0)return mn.object({});let n=e.every(xt),r=e.every(s=>!xt(s));if(n)return mn.object(t);if(r)return Rh.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Wt(t,e){return xt(t)?mn.safeParse(t,e):t.safeParse(e)}async function no(t,e){return xt(t)?await mn.safeParseAsync(t,e):await t.safeParseAsync(e)}function Jt(t){if(!t)return;let e;if(xt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function zn(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 gn(t)}}if(xt(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 Qk(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function ro(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 ${Qk(e.path)}`:e.message).join(`
|
|
1955
|
+
`);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Eh(t){return t.description}function Ph(t){if(xt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Bn(t){if(xt(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 Ar=j(()=>{});import*as c from"zod/v4";function Vh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Gh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var La,Ah,Yt,oo,Te,Ih,Ch,jC,eS,tS,ja,et,Ir,Oh,Ie,ot,it,Ce,io,Nh,Da,Lh,jh,Ua,Cr,V,Ma,Dh,Uh,DC,ao,nS,lo,rS,Or,Fn,Mh,sS,oS,iS,aS,lS,cS,qa,dS,uS,za,co,pS,hS,uo,fS,Nr,Lr,mS,jr,Hn,gS,Dr,po,ho,fo,UC,mo,go,bo,qh,zh,Bh,Ba,Fh,Ur,Kn,Hh,bS,yo,yS,wo,wS,Fa,vS,vo,kS,SS,_S,$S,xS,TS,RS,ES,PS,AS,ko,IS,CS,So,Ha,Ka,Va,OS,NS,LS,Ga,jS,DS,US,MS,qS,Kh,_o,zS,$o,MC,BS,Vn,FS,qC,Mr,HS,Wa,KS,VS,GS,WS,JS,YS,ZS,so,XS,QS,e_,qr,Ja,t_,n_,r_,s_,o_,i_,a_,l_,c_,d_,u_,p_,h_,f_,m_,g_,b_,y_,Gn,w_,v_,k_,xo,S_,__,$_,Ya,x_,zC,BC,FC,HC,KC,VC,z,Na,Wn=j(()=>{La="2025-11-25",Ah=[La,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Yt="io.modelcontextprotocol/related-task",oo="2.0",Te=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Ih=c.union([c.string(),c.number().int()]),Ch=c.string(),jC=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),eS=c.object({ttl:c.number().optional()}),tS=c.object({taskId:c.string()}),ja=c.looseObject({progressToken:Ih.optional(),[Yt]:tS.optional()}),et=c.object({_meta:ja.optional()}),Ir=et.extend({task:eS.optional()}),Oh=t=>Ir.safeParse(t).success,Ie=c.object({method:c.string(),params:et.loose().optional()}),ot=c.object({_meta:ja.optional()}),it=c.object({method:c.string(),params:ot.loose().optional()}),Ce=c.looseObject({_meta:ja.optional()}),io=c.union([c.string(),c.number().int()]),Nh=c.object({jsonrpc:c.literal(oo),id:io,...Ie.shape}).strict(),Da=t=>Nh.safeParse(t).success,Lh=c.object({jsonrpc:c.literal(oo),...it.shape}).strict(),jh=t=>Lh.safeParse(t).success,Ua=c.object({jsonrpc:c.literal(oo),id:io,result:Ce}).strict(),Cr=t=>Ua.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"})(V||(V={}));Ma=c.object({jsonrpc:c.literal(oo),id:io.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),Dh=t=>Ma.safeParse(t).success,Uh=c.union([Nh,Lh,Ua,Ma]),DC=c.union([Ua,Ma]),ao=Ce.strict(),nS=ot.extend({requestId:io.optional(),reason:c.string().optional()}),lo=it.extend({method:c.literal("notifications/cancelled"),params:nS}),rS=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Or=c.object({icons:c.array(rS).optional()}),Fn=c.object({name:c.string(),title:c.string().optional()}),Mh=Fn.extend({...Fn.shape,...Or.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),sS=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),oS=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:sS.optional(),url:Te.optional()}),c.record(c.string(),c.unknown()).optional())),iS=c.looseObject({list:Te.optional(),cancel:Te.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:Te.optional()}).optional(),elicitation:c.looseObject({create:Te.optional()}).optional()}).optional()}),aS=c.looseObject({list:Te.optional(),cancel:Te.optional(),requests:c.looseObject({tools:c.looseObject({call:Te.optional()}).optional()}).optional()}),lS=c.object({experimental:c.record(c.string(),Te).optional(),sampling:c.object({context:Te.optional(),tools:Te.optional()}).optional(),elicitation:oS.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:iS.optional(),extensions:c.record(c.string(),Te).optional()}),cS=et.extend({protocolVersion:c.string(),capabilities:lS,clientInfo:Mh}),qa=Ie.extend({method:c.literal("initialize"),params:cS}),dS=c.object({experimental:c.record(c.string(),Te).optional(),logging:Te.optional(),completions:Te.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:aS.optional(),extensions:c.record(c.string(),Te).optional()}),uS=Ce.extend({protocolVersion:c.string(),capabilities:dS,serverInfo:Mh,instructions:c.string().optional()}),za=it.extend({method:c.literal("notifications/initialized"),params:ot.optional()}),co=Ie.extend({method:c.literal("ping"),params:et.optional()}),pS=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),hS=c.object({...ot.shape,...pS.shape,progressToken:Ih}),uo=it.extend({method:c.literal("notifications/progress"),params:hS}),fS=et.extend({cursor:Ch.optional()}),Nr=Ie.extend({params:fS.optional()}),Lr=Ce.extend({nextCursor:Ch.optional()}),mS=c.enum(["working","input_required","completed","failed","cancelled"]),jr=c.object({taskId:c.string(),status:mS,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Hn=Ce.extend({task:jr}),gS=ot.merge(jr),Dr=it.extend({method:c.literal("notifications/tasks/status"),params:gS}),po=Ie.extend({method:c.literal("tasks/get"),params:et.extend({taskId:c.string()})}),ho=Ce.merge(jr),fo=Ie.extend({method:c.literal("tasks/result"),params:et.extend({taskId:c.string()})}),UC=Ce.loose(),mo=Nr.extend({method:c.literal("tasks/list")}),go=Lr.extend({tasks:c.array(jr)}),bo=Ie.extend({method:c.literal("tasks/cancel"),params:et.extend({taskId:c.string()})}),qh=Ce.merge(jr),zh=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),Bh=zh.extend({text:c.string()}),Ba=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Fh=zh.extend({blob:Ba}),Ur=c.enum(["user","assistant"]),Kn=c.object({audience:c.array(Ur).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),Hh=c.object({...Fn.shape,...Or.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Kn.optional(),_meta:c.optional(c.looseObject({}))}),bS=c.object({...Fn.shape,...Or.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Kn.optional(),_meta:c.optional(c.looseObject({}))}),yo=Nr.extend({method:c.literal("resources/list")}),yS=Lr.extend({resources:c.array(Hh)}),wo=Nr.extend({method:c.literal("resources/templates/list")}),wS=Lr.extend({resourceTemplates:c.array(bS)}),Fa=et.extend({uri:c.string()}),vS=Fa,vo=Ie.extend({method:c.literal("resources/read"),params:vS}),kS=Ce.extend({contents:c.array(c.union([Bh,Fh]))}),SS=it.extend({method:c.literal("notifications/resources/list_changed"),params:ot.optional()}),_S=Fa,$S=Ie.extend({method:c.literal("resources/subscribe"),params:_S}),xS=Fa,TS=Ie.extend({method:c.literal("resources/unsubscribe"),params:xS}),RS=ot.extend({uri:c.string()}),ES=it.extend({method:c.literal("notifications/resources/updated"),params:RS}),PS=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),AS=c.object({...Fn.shape,...Or.shape,description:c.optional(c.string()),arguments:c.optional(c.array(PS)),_meta:c.optional(c.looseObject({}))}),ko=Nr.extend({method:c.literal("prompts/list")}),IS=Lr.extend({prompts:c.array(AS)}),CS=et.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),So=Ie.extend({method:c.literal("prompts/get"),params:CS}),Ha=c.object({type:c.literal("text"),text:c.string(),annotations:Kn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ka=c.object({type:c.literal("image"),data:Ba,mimeType:c.string(),annotations:Kn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Va=c.object({type:c.literal("audio"),data:Ba,mimeType:c.string(),annotations:Kn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),OS=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()}),NS=c.object({type:c.literal("resource"),resource:c.union([Bh,Fh]),annotations:Kn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),LS=Hh.extend({type:c.literal("resource_link")}),Ga=c.union([Ha,Ka,Va,LS,NS]),jS=c.object({role:Ur,content:Ga}),DS=Ce.extend({description:c.string().optional(),messages:c.array(jS)}),US=it.extend({method:c.literal("notifications/prompts/list_changed"),params:ot.optional()}),MS=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),qS=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),Kh=c.object({...Fn.shape,...Or.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Te).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Te).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:MS.optional(),execution:qS.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),_o=Nr.extend({method:c.literal("tools/list")}),zS=Lr.extend({tools:c.array(Kh)}),$o=Ce.extend({content:c.array(Ga).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),MC=$o.or(Ce.extend({toolResult:c.unknown()})),BS=Ir.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Vn=Ie.extend({method:c.literal("tools/call"),params:BS}),FS=it.extend({method:c.literal("notifications/tools/list_changed"),params:ot.optional()}),qC=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Mr=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),HS=et.extend({level:Mr}),Wa=Ie.extend({method:c.literal("logging/setLevel"),params:HS}),KS=ot.extend({level:Mr,logger:c.string().optional(),data:c.unknown()}),VS=it.extend({method:c.literal("notifications/message"),params:KS}),GS=c.object({name:c.string().optional()}),WS=c.object({hints:c.array(GS).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()}),JS=c.object({mode:c.enum(["auto","required","none"]).optional()}),YS=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(Ga).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ZS=c.discriminatedUnion("type",[Ha,Ka,Va]),so=c.discriminatedUnion("type",[Ha,Ka,Va,OS,YS]),XS=c.object({role:Ur,content:c.union([so,c.array(so)]),_meta:c.record(c.string(),c.unknown()).optional()}),QS=Ir.extend({messages:c.array(XS),modelPreferences:WS.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:Te.optional(),tools:c.array(Kh).optional(),toolChoice:JS.optional()}),e_=Ie.extend({method:c.literal("sampling/createMessage"),params:QS}),qr=Ce.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Ur,content:ZS}),Ja=Ce.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Ur,content:c.union([so,c.array(so)])}),t_=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),n_=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()}),r_=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()}),s_=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),o_=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()}),i_=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()}),a_=c.union([s_,o_]),l_=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()}),c_=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()}),d_=c.union([l_,c_]),u_=c.union([i_,a_,d_]),p_=c.union([u_,t_,n_,r_]),h_=Ir.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),p_),required:c.array(c.string()).optional()})}),f_=Ir.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),m_=c.union([h_,f_]),g_=Ie.extend({method:c.literal("elicitation/create"),params:m_}),b_=ot.extend({elicitationId:c.string()}),y_=it.extend({method:c.literal("notifications/elicitation/complete"),params:b_}),Gn=Ce.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())}),w_=c.object({type:c.literal("ref/resource"),uri:c.string()}),v_=c.object({type:c.literal("ref/prompt"),name:c.string()}),k_=et.extend({ref:c.union([v_,w_]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),xo=Ie.extend({method:c.literal("completion/complete"),params:k_});S_=Ce.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),__=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),$_=Ie.extend({method:c.literal("roots/list"),params:et.optional()}),Ya=Ce.extend({roots:c.array(__)}),x_=it.extend({method:c.literal("notifications/roots/list_changed"),params:ot.optional()}),zC=c.union([co,qa,xo,Wa,So,ko,yo,wo,vo,$S,TS,Vn,_o,po,fo,mo,bo]),BC=c.union([lo,uo,za,x_,Dr]),FC=c.union([ao,qr,Ja,Gn,Ya,ho,go,Hn]),HC=c.union([co,e_,g_,$_,po,fo,mo,bo]),KC=c.union([lo,uo,VS,ES,SS,FS,US,Dr,y_]),VC=c.union([ao,uS,S_,DS,IS,yS,wS,kS,$o,zS,ho,go,Hn]),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===V.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new Na(s.elicitations,n)}return new t(e,n,r)}},Na=class extends z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(V.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Zt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Wh=j(()=>{});var Yh,Jh,Zh,To=j(()=>{Yh=Symbol("Let zodToJsonSchema decide on which parser to use"),Jh={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"},Zh=t=>typeof t=="string"?{...Jh,name:t}:{...Jh,...t}});var Xh,Za=j(()=>{To();Xh=t=>{let e=Zh(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 Xa(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function le(t,e,n,r,s){t[e]=n,Xa(t,e,r,s)}var Xt=j(()=>{});var Ro,Eo=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 at=j(()=>{Eo()});import{ZodFirstPartyTypeKind as T_}from"zod/v3";function Qh(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==T_.ZodAny&&(n.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&le(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&le(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(le(n,"minItems",t.exactLength.value,t.exactLength.message,e),le(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var Qa=j(()=>{Xt();xe()});function ef(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?le(n,"minimum",r.value,r.message,e):le(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),le(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?le(n,"maximum",r.value,r.message,e):le(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),le(n,"maximum",r.value,r.message,e));break;case"multipleOf":le(n,"multipleOf",r.value,r.message,e);break}return n}var el=j(()=>{Xt()});function tf(){return{type:"boolean"}}var tl=j(()=>{});function Po(t,e){return Y(t.type._def,e)}var Ao=j(()=>{xe()});var nf,nl=j(()=>{xe();nf=(t,e)=>Y(t.innerType._def,e)});function rl(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>rl(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 R_(t,e)}}var R_,sl=j(()=>{Xt();R_=(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":le(n,"minimum",r.value,r.message,e);break;case"max":le(n,"maximum",r.value,r.message,e);break}return n}});function rf(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var ol=j(()=>{xe()});function sf(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):we(e)}var il=j(()=>{xe();at()});function of(t){return{type:"string",enum:Array.from(t.values)}}var al=j(()=>{});function af(t,e){let n=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(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(E_(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 E_,ll=j(()=>{xe();E_=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function lf(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 cl=j(()=>{});function Io(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":le(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":le(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":gt(n,"email",r.message,e);break;case"format:idn-email":gt(n,"idn-email",r.message,e);break;case"pattern:zod":Fe(n,mt.email,r.message,e);break}break;case"url":gt(n,"uri",r.message,e);break;case"uuid":gt(n,"uuid",r.message,e);break;case"regex":Fe(n,r.regex,r.message,e);break;case"cuid":Fe(n,mt.cuid,r.message,e);break;case"cuid2":Fe(n,mt.cuid2,r.message,e);break;case"startsWith":Fe(n,RegExp(`^${ul(r.value,e)}`),r.message,e);break;case"endsWith":Fe(n,RegExp(`${ul(r.value,e)}$`),r.message,e);break;case"datetime":gt(n,"date-time",r.message,e);break;case"date":gt(n,"date",r.message,e);break;case"time":gt(n,"time",r.message,e);break;case"duration":gt(n,"duration",r.message,e);break;case"length":le(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),le(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Fe(n,RegExp(ul(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&>(n,"ipv4",r.message,e),r.version!=="v4"&>(n,"ipv6",r.message,e);break}case"base64url":Fe(n,mt.base64url,r.message,e);break;case"jwt":Fe(n,mt.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Fe(n,mt.ipv4Cidr,r.message,e),r.version!=="v4"&&Fe(n,mt.ipv6Cidr,r.message,e);break}case"emoji":Fe(n,mt.emoji(),r.message,e);break;case"ulid":{Fe(n,mt.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{gt(n,"binary",r.message,e);break}case"contentEncoding:base64":{le(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Fe(n,mt.base64,r.message,e);break}}break}case"nanoid":Fe(n,mt.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function ul(t,e){return e.patternStrategy==="escape"?A_(t):t}function A_(t){let e="";for(let n=0;n<t.length;n++)P_.has(t[n])||(e+="\\"),e+=t[n];return e}function gt(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}}})):le(t,"format",e,n,r)}function Fe(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:cf(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):le(t,"pattern",cf(e,r),n,r)}function cf(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
|
|
1863
1956
|
]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
|
|
1864
1957
|
]))`;continue}}if(n.s&&r[l]==="."){s+=i?`${r[l]}\r
|
|
1865
1958
|
`:`[${r[l]}\r
|
|
1866
|
-
]`;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 ol,pt,o_,Ro=j(()=>{Wt();pt={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:()=>(ol===void 0&&(ol=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ol),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-_]*$/};o_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Ur}from"zod/v3";function Eo(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===Ur.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===Ur.ZodString&&t.keyType._def.checks?.length){let{type:r,...s}=To(t.keyType._def,e);return{...n,propertyNames:s}}else{if(t.keyType?._def.typeName===Ur.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Ur.ZodBranded&&t.keyType._def.type._def.typeName===Ur.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...s}=$o(t.keyType._def,e);return{...n,propertyNames:s}}}return n}var Po=j(()=>{$e();Ro();xo();ot()});function Jh(t,e){if(e.mapStrategy==="record")return Eo(t,e);let n=J(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),r=J(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 al=j(()=>{$e();Po();ot()});function Yh(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 ll=j(()=>{});function Zh(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}var cl=j(()=>{ot()});function Xh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var dl=j(()=>{});function ef(t,e){if(e.target==="openApi3")return Qh(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Mr&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,o)=>{let i=Mr[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 Qh(t,e)}var Mr,Qh,Ao=j(()=>{$e();Mr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Qh=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>J(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 tf(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:Mr[t.innerType._def.typeName],nullable:!0}:{type:[Mr[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=J(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var ul=j(()=>{$e();Ao()});function nf(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",Ga(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}var pl=j(()=>{Wt()});function rf(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 u=l_(l);u&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=J(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(r.properties[a]=p,u||s.push(a))}s.length&&(r.required=s);let i=a_(t,e);return i!==void 0&&(r.additionalProperties=i),r}function a_(t,e){if(t.catchall._def.typeName!=="ZodNever")return J(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 l_(t){try{return t.isOptional()}catch{return!0}}var hl=j(()=>{$e()});var sf,fl=j(()=>{$e();ot();sf=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return J(t.innerType._def,e);let n=J(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:we(e)},n]}:we(e)}});var of,ml=j(()=>{$e();of=(t,e)=>{if(e.pipeStrategy==="input")return J(t.in._def,e);if(e.pipeStrategy==="output")return J(t.out._def,e);let n=J(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=J(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}}});function af(t,e){return J(t.type._def,e)}var gl=j(()=>{$e()});function lf(t,e){let r={type:"array",uniqueItems:!0,items:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var bl=j(()=>{Wt();$e()});function cf(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>J(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:J(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>J(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var yl=j(()=>{$e()});function df(t){return{not:we(t)}}var wl=j(()=>{ot()});function uf(t){return we(t)}var vl=j(()=>{ot()});var pf,kl=j(()=>{$e();pf=(t,e)=>J(t.innerType._def,e)});import{ZodFirstPartyTypeKind as oe}from"zod/v3";var hf,Sl=j(()=>{ot();Wa();Ja();Ya();xo();Za();Qa();el();tl();nl();rl();sl();al();ll();cl();dl();ul();pl();hl();fl();ml();gl();Po();bl();Ro();yl();wl();Ao();vl();kl();hf=(t,e,n)=>{switch(e){case oe.ZodString:return To(t,n);case oe.ZodNumber:return nf(t,n);case oe.ZodObject:return rf(t,n);case oe.ZodBigInt:return zh(t,n);case oe.ZodBoolean:return qh();case oe.ZodDate:return Xa(t,n);case oe.ZodUndefined:return df(n);case oe.ZodNull:return Xh(n);case oe.ZodArray:return Mh(t,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return ef(t,n);case oe.ZodIntersection:return Vh(t,n);case oe.ZodTuple:return cf(t,n);case oe.ZodRecord:return Eo(t,n);case oe.ZodLiteral:return Gh(t,n);case oe.ZodEnum:return Kh(t);case oe.ZodNativeEnum:return Yh(t);case oe.ZodNullable:return tf(t,n);case oe.ZodOptional:return sf(t,n);case oe.ZodMap:return Jh(t,n);case oe.ZodSet:return lf(t,n);case oe.ZodLazy:return()=>t.getter()._def;case oe.ZodPromise:return af(t,n);case oe.ZodNaN:case oe.ZodNever:return Zh(n);case oe.ZodEffects:return Hh(t,n);case oe.ZodAny:return we(n);case oe.ZodUnknown:return uf(n);case oe.ZodDefault:return Fh(t,n);case oe.ZodBranded:return $o(t,n);case oe.ZodReadonly:return pf(t,n);case oe.ZodCatch:return Bh(t,n);case oe.ZodPipeline:return of(t,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(r=>{})(e)}}});function J(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==jh)return a}if(r&&!n){let a=c_(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=hf(t,t.typeName,e),i=typeof o=="function"?J(o(),e):o;if(i&&d_(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var c_,d_,$e=j(()=>{ko();Sl();_o();ot();c_=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:So(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}},d_=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var ff=j(()=>{});var _l,$l=j(()=>{$e();Va();ot();_l=(t,e)=>{let n=Uh(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:J(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??we(n)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=J(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 mf=j(()=>{ko();Va();Wt();_o();$e();ff();ot();Wa();Ja();Ya();xo();Za();Qa();el();tl();nl();rl();sl();al();ll();cl();dl();ul();pl();hl();fl();ml();gl();kl();Po();bl();Ro();yl();wl();Ao();vl();Sl();$l();$l()});import*as gf from"zod/v4-mini";function u_(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function xl(t,e){return kt(t)?gf.toJSONSchema(t,{target:u_(e?.target),io:e?.pipeStrategy??"input"}):_l(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Tl(t){let n=Kt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Un(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Rl(t,e){let n=Ht(t,e);if(!n.success)throw n.error;return n.data}var El=j(()=>{Rr();mf()});function bf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yf(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];bf(i)&&bf(o)?n[s]={...i,...o}:n[s]=o}return n}var p_,Io,wf=j(()=>{Rr();Hn();Nh();El();p_=6e4,Io=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(ro,n=>{this._oncancel(n)}),this.setNotificationHandler(oo,n=>{this._onprogress(n)}),this.setRequestHandler(so,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(io,async(n,r)=>{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(K.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(lo,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,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),a.type==="response")p(l);else{let g=l,$=new z(g.error.code,g.error.message,g.error.data);p($)}else{let g=a.type==="response"?"Response":"Error";this._onerror(new Error(`${g} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new z(K.InvalidParams,`Task not found: ${o}`);if(!Gt(i.status))return await this._waitForTaskUpdate(o,r.signal),await s();if(Gt(i.status)){let a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Vt]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(co,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(K.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(po,async(n,r)=>{try{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(K.InvalidParams,`Task not found: ${n.params.taskId}`);if(Gt(s.status))throw new z(K.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(K.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof z?s:new z(K.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(K.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),Pr(o)||_h(o)?this._onresponse(o):Ca(o)?this._onrequest(o,i):Sh(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(K.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?.[Vt]?.taskId;if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:K.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):s?.send(p).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=wh(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let g={relatedRequestId:e.id};o&&(g.relatedTask={taskId:o}),await this.notification(p,g)},sendRequest:async(p,g,$)=>{if(i.signal.aborted)throw new z(K.ConnectionClosed,"Request was cancelled");let v={...$,relatedRequestId:e.id};o&&!v.relatedTask&&(v.relatedTask={taskId:o});let S=v.relatedTask?.taskId??o;return S&&l&&await l.updateTaskStatus(S,"input_required"),await this.request(p,g,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,u)).then(async p=>{if(i.signal.aborted)return;let g={result:p,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:g,timestamp:Date.now()},s?.sessionId):await s?.send(g)},async p=>{if(i.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:K.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:g,timestamp:Date.now()},s?.sessionId):await s?.send(g)}).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),Pr(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(Pr(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),Pr(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(K.InternalError,String(i))}}return}let o;try{let i=await this.request(e,zn,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(K.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Gt(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(K.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(K.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(u=>setTimeout(u,l)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(K.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=r??{};return new Promise((u,p)=>{let g=C=>{p(C)};if(!this._transport){g(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(C){g(C);return}r?.signal?.throwIfAborted();let $=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:$};r?.onprogress&&(this._progressHandlers.set($,r.onprogress),v.params={...e.params,_meta:{...e.params?._meta||{},progressToken:$}}),a&&(v.params={...v.params,task:a}),l&&(v.params={...v.params,_meta:{...v.params?._meta||{},[Vt]:l}});let S=C=>{this._responseHandlers.delete($),this._progressHandlers.delete($),this._cleanupTimeout($),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:$,reason:String(C)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(se=>this._onerror(new Error(`Failed to send cancellation: ${se}`)));let D=C instanceof z?C:new z(K.RequestTimeout,String(C));p(D)};this._responseHandlers.set($,C=>{if(!r?.signal?.aborted){if(C instanceof Error)return p(C);try{let D=Ht(n,C.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),r?.signal?.addEventListener("abort",()=>{S(r?.signal?.reason)});let T=r?.timeout??p_,E=()=>S(z.fromError(K.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout($,T,r?.maxTotalTimeout,E,r?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let C=D=>{let se=this._responseHandlers.get($);se?se(D):this._onerror(new Error(`Response handler missing for side-channeled request ${$}`))};this._requestResolvers.set($,C),this._enqueueTaskMessage(P,{type:"request",message:v,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout($),p(D)})}else this._transport.send(v,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(C=>{this._cleanupTimeout($),p(C)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},ao,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},uo,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},Th,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||{},[Vt]: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||{},[Vt]: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||{},[Vt]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Tl(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=Tl(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"&&Ca(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new z(K.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(K.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,r);n.addEventListener("abort",()=>{clearTimeout(i),o(new z(K.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(K.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=Nr.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Gt(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(K.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Gt(a.status))throw new z(K.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 u=Nr.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Gt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}});var Br=M(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var zr=class{};he._CodeOrName=zr;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var pn=class extends zr{constructor(e){if(super(),!he.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}}};he.Name=pn;var it=class extends zr{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 pn&&(n[r.str]=(n[r.str]||0)+1),n),{})}};he._Code=it;he.nil=new it("");function vf(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Al(n,e[r]),n.push(t[++r]);return new it(n)}he._=vf;var Pl=new it("+");function kf(t,...e){let n=[qr(t[0])],r=0;for(;r<e.length;)n.push(Pl),Al(n,e[r]),n.push(Pl,qr(t[++r]));return h_(n),new it(n)}he.str=kf;function Al(t,e){e instanceof it?t.push(...e._items):e instanceof pn?t.push(e):t.push(g_(e))}he.addCodeArg=Al;function h_(t){let e=1;for(;e<t.length-1;){if(t[e]===Pl){let n=f_(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function f_(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof pn||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 pn))return`"${t}${e.slice(1)}`}function m_(t,e){return e.emptyStr()?t:t.emptyStr()?e:kf`${t}${e}`}he.strConcat=m_;function g_(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:qr(Array.isArray(t)?t.join(","):t)}function b_(t){return new it(qr(t))}he.stringify=b_;function qr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=qr;function y_(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new it(`.${t}`):vf`[${t}]`}he.getProperty=y_;function w_(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new it(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=w_;function v_(t){return new it(t.toString())}he.regexpCode=v_});var Ol=M(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ValueScope=Ge.ValueScopeName=Ge.Scope=Ge.varKinds=Ge.UsedValueState=void 0;var Ve=Br(),Il=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Co;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Co||(Ge.UsedValueState=Co={}));Ge.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};var Oo=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=Oo;var No=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=No;var k_=(0,Ve._)`\n`,Cl=class extends Oo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?k_:Ve.nil}}get(){return this._scope}name(e){return new No(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]=[]),u=l.length;return l[u]=n.ref,s.setValue(n,{property:o,itemIndex:u}),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(u=>{if(l.has(u))return;l.set(u,Co.Started);let p=n(u);if(p){let g=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const;o=(0,Ve._)`${o}${g} ${u} = ${p};${this.opts._n}`}else if(p=s?.(u))o=(0,Ve._)`${o}${p}${this.opts._n}`;else throw new Il(u);l.set(u,Co.Completed)})}return o}};Ge.ValueScope=Cl});var ee=M(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 le=Br(),ft=Ol(),Jt=Br();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return Jt._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return Jt.str}});Object.defineProperty(te,"strConcat",{enumerable:!0,get:function(){return Jt.strConcat}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return Jt.nil}});Object.defineProperty(te,"getProperty",{enumerable:!0,get:function(){return Jt.getProperty}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return Jt.stringify}});Object.defineProperty(te,"regexpCode",{enumerable:!0,get:function(){return Jt.regexpCode}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return Jt.Name}});var Uo=Ol();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return Uo.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return Uo.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return Uo.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return Uo.varKinds}});te.operators={GT:new le._Code(">"),GTE:new le._Code(">="),LT:new le._Code("<"),LTE:new le._Code("<="),EQ:new le._Code("==="),NEQ:new le._Code("!=="),NOT:new le._Code("!"),OR:new le._Code("||"),AND:new le._Code("&&"),ADD:new le._Code("+")};var Ct=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Nl=class extends Ct{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=Vn(this.rhs,e,n)),this}get names(){return this.rhs instanceof le._CodeOrName?this.rhs.names:{}}},Lo=class extends Ct{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 le.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Vn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof le.Name?{}:{...this.lhs.names};return Do(e,this.rhs)}},Ll=class extends Lo{constructor(e,n,r,s){super(e,r,s),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},jl=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Dl=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ul=class extends Ct{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ml=class extends Ct{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=Vn(this.code,e,n),this}get names(){return this.code instanceof le._CodeOrName?this.code.names:{}}},Fr=class extends Ct{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)||(S_(e,o.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>mn(e,n.names),{})}},Ot=class extends Fr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},zl=class extends Fr{},Kn=class extends Ot{};Kn.kind="else";var hn=class t extends Ot{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 Kn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Sf(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=Vn(this.condition,e,n),this}get names(){let e=super.names;return Do(e,this.condition),this.else&&mn(e,this.else.names),e}};hn.kind="if";var fn=class extends Ot{};fn.kind="for";var ql=class extends fn{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=Vn(this.iteration,e,n),this}get names(){return mn(super.names,this.iteration.names)}},Bl=class extends fn{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=Do(super.names,this.from);return Do(e,this.to)}},jo=class extends fn{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=Vn(this.iterable,e,n),this}get names(){return mn(super.names,this.iterable.names)}},Hr=class extends Ot{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)}};Hr.kind="func";var Kr=class extends Fr{render(e){return"return "+super.render(e)}};Kr.kind="return";var Fl=class extends Ot{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&&mn(e,this.catch.names),this.finally&&mn(e,this.finally.names),e}},Vr=class extends Ot{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Vr.kind="catch";var Gr=class extends Ot{render(e){return"finally"+super.render(e)}};Gr.kind="finally";var Hl=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
1867
|
-
`:""},this._extScope=e,this._scope=new ft.Scope({parent:e}),this._nodes=[new zl]}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 Lo(e,n,r))}add(e,n){return this._leafNode(new Ll(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==le.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,le.addCodeArg)(n,s));return n.push("}"),new le._Code(n)}if(e,n,r){if(this._blockNode(new hn(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 hn(e))}else(){return this._elseNode(new Kn)}endIf(){return this._endBlockNode(hn,Kn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new ql(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 Bl(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 le.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,le._)`${i}.length`,a=>{this.var(o,(0,le._)`${i}[${a}]`),r(o)})}return this._for(new jo("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,le._)`Object.keys(${n})`,r);let o=this._scope.toName(e);return this._for(new jo("in",s,o,n),()=>r(o))}endFor(){return this._endBlockNode(fn)}label(e){return this._leafNode(new jl(e))}break(e){return this._leafNode(new Dl(e))}return(e){let n=new Kr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Kr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Fl;if(this._blockNode(s),this.code(e),n){let o=this.name("e");this._currNode=s.catch=new Vr(o),n(o)}return r&&(this._currNode=s.finally=new Gr,this.code(r)),this._endBlockNode(Vr,Gr)}throw(e){return this._leafNode(new Ul(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=le.nil,r,s){return this._blockNode(new Hr(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Hr)}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 hn))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=Hl;function mn(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function Do(t,e){return e instanceof le._CodeOrName?mn(t,e.names):t}function Vn(t,e,n){if(t instanceof le.Name)return r(t);if(!s(t))return t;return new le._Code(t._items.reduce((o,i)=>(i instanceof le.Name&&(i=r(i)),i instanceof le._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 le._Code&&o._items.some(i=>i instanceof le.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function S_(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Sf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,le._)`!${Kl(t)}`}te.not=Sf;var __=_f(te.operators.AND);function $_(...t){return t.reduce(__)}te.and=$_;var x_=_f(te.operators.OR);function T_(...t){return t.reduce(x_)}te.or=T_;function _f(t){return(e,n)=>e===le.nil?n:n===le.nil?e:(0,le._)`${Kl(e)} ${t} ${Kl(n)}`}function Kl(t){return t instanceof le.Name?t:(0,le._)`(${t})`}});var ue=M(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(),R_=Br();function E_(t){let e={};for(let n of t)e[n]=!0;return e}ne.toHash=E_;function P_(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Tf(t,e),!Rf(e,t.self.RULES.all))}ne.alwaysValidSchema=P_;function Tf(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]||Af(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=Tf;function Rf(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ne.schemaHasRules=Rf;function A_(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=A_;function I_({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=I_;function C_(t){return Ef(decodeURIComponent(t))}ne.unescapeFragment=C_;function O_(t){return encodeURIComponent(Gl(t))}ne.escapeFragment=O_;function Gl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=Gl;function Ef(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=Ef;function N_(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ne.eachItem=N_;function $f({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:$f({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} || {}`),Wl(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Pf}),items:$f({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 Pf(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,ge._)`{}`);return e!==void 0&&Wl(t,n,e),n}ne.evaluatedPropsToName=Pf;function Wl(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(r)}`,!0))}ne.setEvaluated=Wl;var xf={};function L_(t,e){return t.scopeValue("func",{ref:e,code:xf[e.code]||(xf[e.code]=new R_._Code(e.code))})}ne.useFunc=L_;var Vl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Vl||(ne.Type=Vl={}));function j_(t,e,n){if(t instanceof ge.Name){let r=e===Vl.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():"/"+Gl(t)}ne.getErrorPath=j_;function Af(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=Af});var Nt=M(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var Ne=ee(),D_={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")};Jl.default=D_});var Wr=M(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var pe=ee(),Mo=ue(),qe=Nt();Le.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,pe.str)`"${t}" keyword must be ${e} ($data)`:(0,pe.str)`"${t}" keyword is invalid ($data)`};function U_(t,e=Le.keywordError,n,r){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=Of(t,e,n);r??(i||a)?If(o,l):Cf(s,(0,pe._)`[${l}]`)}Le.reportError=U_;function M_(t,e=Le.keywordError,n){let{it:r}=t,{gen:s,compositeRule:o,allErrors:i}=r,a=Of(t,e,n);If(s,a),o||i||Cf(r,qe.default.vErrors)}Le.reportExtraError=M_;function z_(t,e){t.assign(qe.default.errors,e),t.if((0,pe._)`${qe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${qe.default.vErrors}.length`,e),()=>t.assign(qe.default.vErrors,null)))}Le.resetErrorsCount=z_;function q_({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,pe._)`${qe.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(qe.default.instancePath,o.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,n),t.assign((0,pe._)`${i}.data`,r))})}Le.extendErrors=q_;function If(t,e){let n=t.const("err",e);t.if((0,pe._)`${qe.default.vErrors} === null`,()=>t.assign(qe.default.vErrors,(0,pe._)`[${n}]`),(0,pe._)`${qe.default.vErrors}.push(${n})`),t.code((0,pe._)`${qe.default.errors}++`)}function Cf(t,e){let{gen:n,validateName:r,schemaEnv:s}=t;s.$async?n.throw((0,pe._)`new ${t.ValidationError}(${e})`):(n.assign((0,pe._)`${r}.errors`,e),n.return(!1))}var gn={keyword:new pe.Name("keyword"),schemaPath:new pe.Name("schemaPath"),params:new pe.Name("params"),propertyName:new pe.Name("propertyName"),message:new pe.Name("message"),schema:new pe.Name("schema"),parentSchema:new pe.Name("parentSchema")};function Of(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,pe._)`{}`:B_(t,e,n)}function B_(t,e,n={}){let{gen:r,it:s}=t,o=[F_(s,n),H_(t,n)];return K_(t,e,o),r.object(...o)}function F_({errorPath:t},{instancePath:e}){let n=e?(0,pe.str)`${t}${(0,Mo.getErrorPath)(e,Mo.Type.Str)}`:t;return[qe.default.instancePath,(0,pe.strConcat)(qe.default.instancePath,n)]}function H_({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let s=r?e:(0,pe.str)`${e}/${t}`;return n&&(s=(0,pe.str)`${s}${(0,Mo.getErrorPath)(n,Mo.Type.Str)}`),[gn.schemaPath,s]}function K_(t,{params:e,message:n},r){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:g}=a;r.push([gn.keyword,s],[gn.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),l.messages&&r.push([gn.message,typeof n=="function"?n(t):n]),l.verbose&&r.push([gn.schema,i],[gn.parentSchema,(0,pe._)`${p}${g}`],[qe.default.data,o]),u&&r.push([gn.propertyName,u])}});var Lf=M(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.boolOrEmptySchema=Gn.topBoolOrEmptySchema=void 0;var V_=Wr(),G_=ee(),W_=Nt(),J_={message:"boolean schema is false"};function Y_(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Nf(t,!1):typeof n=="object"&&n.$async===!0?e.return(W_.default.data):(e.assign((0,G_._)`${r}.errors`,null),e.return(!0))}Gn.topBoolOrEmptySchema=Y_;function Z_(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Nf(t)):n.var(e,!0)}Gn.boolOrEmptySchema=Z_;function Nf(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,V_.reportError)(s,J_,void 0,e)}});var Yl=M(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.getRules=Wn.isJSONType=void 0;var X_=["string","number","integer","boolean","null","object","array"],Q_=new Set(X_);function e$(t){return typeof t=="string"&&Q_.has(t)}Wn.isJSONType=e$;function t$(){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:{}}}Wn.getRules=t$});var Zl=M(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.shouldUseRule=Yt.shouldUseGroup=Yt.schemaHasRulesForType=void 0;function n$({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&jf(t,r)}Yt.schemaHasRulesForType=n$;function jf(t,e){return e.rules.some(n=>Df(t,n))}Yt.shouldUseGroup=jf;function Df(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))}Yt.shouldUseRule=Df});var Jr=M(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 r$=Yl(),s$=Zl(),o$=Wr(),Q=ee(),Uf=ue(),Jn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Jn||(je.DataType=Jn={}));function i$(t){let e=Mf(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=i$;function Mf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(r$.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}je.getJSONTypes=Mf;function a$(t,e){let{gen:n,data:r,opts:s}=t,o=l$(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,s$.schemaHasRulesForType)(t,e[0]));if(i){let a=Ql(e,r,s.strictNumbers,Jn.Wrong);n.if(a,()=>{o.length?c$(t,e,o):ec(t)})}return i}je.coerceAndCheckDataType=a$;var zf=new Set(["string","number","integer","boolean","null"]);function l$(t,e){return e?t.filter(n=>zf.has(n)||e==="array"&&n==="array"):[]}function c$(t,e,n){let{gen:r,data:s,opts:o}=t,i=r.let("dataType",(0,Q._)`typeof ${s}`),a=r.let("coerced",(0,Q._)`undefined`);o.coerceTypes==="array"&&r.if((0,Q._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,Q._)`${s}[0]`).assign(i,(0,Q._)`typeof ${s}`).if(Ql(e,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,Q._)`${a} !== undefined`);for(let u of n)(zf.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);r.else(),ec(t),r.endIf(),r.if((0,Q._)`${a} !== undefined`,()=>{r.assign(s,a),d$(t,a)});function l(u){switch(u){case"string":r.elseIf((0,Q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Q._)`"" + ${s}`).elseIf((0,Q._)`${s} === null`).assign(a,(0,Q._)`""`);return;case"number":r.elseIf((0,Q._)`${i} == "boolean" || ${s} === null
|
|
1868
|
-
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,
|
|
1869
|
-
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,
|
|
1870
|
-
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,Q._)`[${s}]`)}}}function d$({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Q._)`${e} !== undefined`,()=>t.assign((0,Q._)`${e}[${n}]`,r))}function Xl(t,e,n,r=Jn.Correct){let s=r===Jn.Correct?Q.operators.EQ:Q.operators.NEQ,o;switch(t){case"null":return(0,Q._)`${e} ${s} null`;case"array":o=(0,Q._)`Array.isArray(${e})`;break;case"object":o=(0,Q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,Q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,Q._)`typeof ${e} ${s} ${t}`}return r===Jn.Correct?o:(0,Q.not)(o);function i(a=Q.nil){return(0,Q.and)((0,Q._)`typeof ${e} == "number"`,a,n?(0,Q._)`isFinite(${e})`:Q.nil)}}je.checkDataType=Xl;function Ql(t,e,n,r){if(t.length===1)return Xl(t[0],e,n,r);let s,o=(0,Uf.toHash)(t);if(o.array&&o.object){let i=(0,Q._)`typeof ${e} != "object"`;s=o.null?i:(0,Q._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=Q.nil;o.number&&delete o.integer;for(let i in o)s=(0,Q.and)(s,Xl(i,e,n,r));return s}je.checkDataTypes=Ql;var u$={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Q._)`{type: ${t}}`:(0,Q._)`{type: ${e}}`};function ec(t){let e=p$(t);(0,o$.reportError)(e,u$)}je.reportTypeError=ec;function p$(t){let{gen:e,data:n,schema:r}=t,s=(0,Uf.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:t}}});var Bf=M(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.assignDefaults=void 0;var Yn=ee(),h$=ue();function f$(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let s in n)qf(t,s,n[s].default);else e==="array"&&Array.isArray(r)&&r.forEach((s,o)=>qf(t,o,s.default))}zo.assignDefaults=f$;function qf(t,e,n){let{gen:r,compositeRule:s,data:o,opts:i}=t;if(n===void 0)return;let a=(0,Yn._)`${o}${(0,Yn.getProperty)(e)}`;if(s){(0,h$.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Yn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Yn._)`${l} || ${a} === null || ${a} === ""`),r.if(l,(0,Yn._)`${a} = ${(0,Yn.stringify)(n)}`)}});var at=M(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=ee(),tc=ue(),Zt=Nt(),m$=ue();function g$(t,e){let{gen:n,data:r,it:s}=t;n.if(rc(n,r,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,be._)`${e}`},!0),t.error()})}me.checkReportMissingProp=g$;function b$({gen:t,data:e,it:{opts:n}},r,s){return(0,be.or)(...r.map(o=>(0,be.and)(rc(t,e,o,n.ownProperties),(0,be._)`${s} = ${o}`)))}me.checkMissingProp=b$;function y$(t,e){t.setParams({missingProperty:e},!0),t.error()}me.reportMissingProp=y$;function Ff(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,be._)`Object.prototype.hasOwnProperty`})}me.hasPropFunc=Ff;function nc(t,e,n){return(0,be._)`${Ff(t)}.call(${e}, ${n})`}me.isOwnProperty=nc;function w$(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} !== undefined`;return r?(0,be._)`${s} && ${nc(t,e,n)}`:s}me.propertyInData=w$;function rc(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} === undefined`;return r?(0,be.or)(s,(0,be.not)(nc(t,e,n))):s}me.noPropertyInData=rc;function Hf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}me.allSchemaProperties=Hf;function v$(t,e){return Hf(e).filter(n=>!(0,tc.alwaysValidSchema)(t,e[n]))}me.schemaProperties=v$;function k$({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:s,errorPath:o},it:i},a,l,u){let p=u?(0,be._)`${t}, ${e}, ${r}${s}`:e,g=[[Zt.default.instancePath,(0,be.strConcat)(Zt.default.instancePath,o)],[Zt.default.parentData,i.parentData],[Zt.default.parentDataProperty,i.parentDataProperty],[Zt.default.rootData,Zt.default.rootData]];i.opts.dynamicRef&&g.push([Zt.default.dynamicAnchors,Zt.default.dynamicAnchors]);let $=(0,be._)`${p}, ${n.object(...g)}`;return l!==be.nil?(0,be._)`${a}.call(${l}, ${$})`:(0,be._)`${a}(${$})`}me.callValidateCode=k$;var S$=(0,be._)`new RegExp`;function _$({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"?S$:(0,m$.useFunc)(t,s)}(${n}, ${r})`})}me.usePattern=_$;function $$(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,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:tc.Type.Num},o),e.if((0,be.not)(o),a)})}}me.validateArray=$$;function x$(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,tc.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((l,u)=>{let p=t.subschema({keyword:r,schemaProp:u,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=x$});var Gf=M(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.validateKeywordUsage=St.validSchemaType=St.funcKeywordCode=St.macroKeywordCode=void 0;var Be=ee(),bn=Nt(),T$=at(),R$=Wr();function E$(t,e){let{gen:n,keyword:r,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=Vf(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:Be.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}St.macroKeywordCode=E$;function P$(t,e){var n;let{gen:r,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;I$(l,e);let u=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,p=Vf(r,s,u),g=r.let("valid");t.block$data(g,$),t.ok((n=e.valid)!==null&&n!==void 0?n:g);function $(){if(e.errors===!1)T(),e.modifying&&Kf(t),E(()=>t.error());else{let P=e.async?v():S();e.modifying&&Kf(t),E(()=>A$(t,P))}}function v(){let P=r.let("ruleErrs",null);return r.try(()=>T((0,Be._)`await `),C=>r.assign(g,!1).if((0,Be._)`${C} instanceof ${l.ValidationError}`,()=>r.assign(P,(0,Be._)`${C}.errors`),()=>r.throw(C))),P}function S(){let P=(0,Be._)`${p}.errors`;return r.assign(P,null),T(Be.nil),P}function T(P=e.async?(0,Be._)`await `:Be.nil){let C=l.opts.passContext?bn.default.this:bn.default.self,D=!("compile"in e&&!a||e.schema===!1);r.assign(g,(0,Be._)`${P}${(0,T$.callValidateCode)(t,p,C,D)}`,e.modifying)}function E(P){var C;r.if((0,Be.not)((C=e.valid)!==null&&C!==void 0?C:g),P)}}St.funcKeywordCode=P$;function Kf(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Be._)`${r.parentData}[${r.parentDataProperty}]`))}function A$(t,e){let{gen:n}=t;n.if((0,Be._)`Array.isArray(${e})`,()=>{n.assign(bn.default.vErrors,(0,Be._)`${bn.default.vErrors} === null ? ${e} : ${bn.default.vErrors}.concat(${e})`).assign(bn.default.errors,(0,Be._)`${bn.default.vErrors}.length`),(0,R$.extendErrors)(t)},()=>t.error())}function I$({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Vf(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,Be.stringify)(n)})}function C$(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")}St.validSchemaType=C$;function O$({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)}}St.validateKeywordUsage=O$});var Jf=M(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.extendSubschemaMode=Xt.extendSubschemaData=Xt.getSubschema=void 0;var _t=ee(),Wf=ue();function N$(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,_t._)`${t.schemaPath}${(0,_t.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,_t._)`${t.schemaPath}${(0,_t.getProperty)(e)}${(0,_t.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Wf.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')}Xt.getSubschema=N$;function L$(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:u,dataPathArr:p,opts:g}=e,$=a.let("data",(0,_t._)`${e.data}${(0,_t.getProperty)(n)}`,!0);l($),t.errorPath=(0,_t.str)`${u}${(0,Wf.getErrorPath)(n,r,g.jsPropertySyntax)}`,t.parentDataProperty=(0,_t._)`${n}`,t.dataPathArr=[...p,t.parentDataProperty]}if(s!==void 0){let u=s instanceof _t.Name?s:a.let("data",s,!0);l(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Xt.extendSubschemaData=L$;function j$(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}Xt.extendSubschemaMode=j$});var sc=M((EL,Yf)=>{"use strict";Yf.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 Xf=M((PL,Zf)=>{"use strict";var Qt=Zf.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(){};qo(e,r,s,t,"",t)};Qt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Qt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Qt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Qt.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 qo(t,e,n,r,s,o,i,a,l,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,s,o,i,a,l,u);for(var p in r){var g=r[p];if(Array.isArray(g)){if(p in Qt.arrayKeywords)for(var $=0;$<g.length;$++)qo(t,e,n,g[$],s+"/"+p+"/"+$,o,s,p,r,$)}else if(p in Qt.propsKeywords){if(g&&typeof g=="object")for(var v in g)qo(t,e,n,g[v],s+"/"+p+"/"+D$(v),o,s,p,r,v)}else(p in Qt.keywords||t.allKeys&&!(p in Qt.skipKeywords))&&qo(t,e,n,g,s+"/"+p,o,s,p,r)}n(r,s,o,i,a,l,u)}}function D$(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Yr=M(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.getSchemaRefs=We.resolveUrl=We.normalizeId=We._getFullPath=We.getFullPath=We.inlineRef=void 0;var U$=ue(),M$=sc(),z$=Xf(),q$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function B$(t,e=!0){return typeof t=="boolean"?!0:e===!0?!oc(t):e?Qf(t)<=e:!1}We.inlineRef=B$;var F$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function oc(t){for(let e in t){if(F$.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(oc)||typeof n=="object"&&oc(n))return!0}return!1}function Qf(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!q$.has(n)&&(typeof t[n]=="object"&&(0,U$.eachItem)(t[n],r=>e+=Qf(r)),e===1/0))return 1/0}return e}function em(t,e="",n){n!==!1&&(e=Zn(e));let r=t.parse(e);return tm(t,r)}We.getFullPath=em;function tm(t,e){return t.serialize(e).split("#")[0]+"#"}We._getFullPath=tm;var H$=/#\/?$/;function Zn(t){return t?t.replace(H$,""):""}We.normalizeId=Zn;function K$(t,e,n){return n=Zn(n),t.resolve(e,n)}We.resolveUrl=K$;var V$=/^[a-z_][-a-z0-9._]*$/i;function G$(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,s=Zn(t[n]||e),o={"":s},i=em(r,s,!1),a={},l=new Set;return z$(t,{allKeys:!0},(g,$,v,S)=>{if(S===void 0)return;let T=i+$,E=o[S];typeof g[n]=="string"&&(E=P.call(this,g[n])),C.call(this,g.$anchor),C.call(this,g.$dynamicAnchor),o[$]=E;function P(D){let se=this.opts.uriResolver.resolve;if(D=Zn(E?se(E,D):D),l.has(D))throw p(D);l.add(D);let G=this.refs[D];return typeof G=="string"&&(G=this.refs[G]),typeof G=="object"?u(g,G.schema,D):D!==Zn(T)&&(D[0]==="#"?(u(g,a[D],D),a[D]=g):this.refs[D]=T),D}function C(D){if(typeof D=="string"){if(!V$.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(g,$,v){if($!==void 0&&!M$(g,$))throw p(v)}function p(g){return new Error(`reference "${g}" resolves to more than one schema`)}}We.getSchemaRefs=G$});var Qr=M(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.getData=en.KeywordCxt=en.validateFunctionCode=void 0;var im=Lf(),nm=Jr(),ac=Zl(),Bo=Jr(),W$=Bf(),Xr=Gf(),ic=Jf(),q=ee(),Z=Nt(),J$=Yr(),Lt=ue(),Zr=Wr();function Y$(t){if(cm(t)&&(dm(t),lm(t))){Q$(t);return}am(t,()=>(0,im.topBoolOrEmptySchema)(t))}en.validateFunctionCode=Y$;function am({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"; ${rm(n,s)}`),X$(t,s),t.code(o)}):t.func(e,(0,q._)`${Z.default.data}, ${Z$(s)}`,r.$async,()=>t.code(rm(n,s)).code(o))}function Z$(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 X$(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 Q$(t){let{schema:e,opts:n,gen:r}=t;am(t,()=>{n.$comment&&e.$comment&&pm(t),sx(t),r.let(Z.default.vErrors,null),r.let(Z.default.errors,0),n.unevaluated&&ex(t),um(t),ax(t)})}function ex(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 rm(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 tx(t,e){if(cm(t)&&(dm(t),lm(t))){nx(t,e);return}(0,im.boolOrEmptySchema)(t,e)}function lm({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 cm(t){return typeof t.schema!="boolean"}function nx(t,e){let{schema:n,gen:r,opts:s}=t;s.$comment&&n.$comment&&pm(t),ox(t),ix(t);let o=r.const("_errs",Z.default.errors);um(t,o),r.var(e,(0,q._)`${o} === ${Z.default.errors}`)}function dm(t){(0,Lt.checkUnknownRules)(t),rx(t)}function um(t,e){if(t.opts.jtd)return sm(t,[],!1,e);let n=(0,nm.getSchemaTypes)(t.schema),r=(0,nm.coerceAndCheckDataType)(t,n);sm(t,n,!r,e)}function rx(t){let{schema:e,errSchemaPath:n,opts:r,self:s}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Lt.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function sx(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Lt.checkStrictMode)(t,"default is ignored in the schema root")}function ox(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,J$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function ix(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function pm({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 ax(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&&lx(t),e.return((0,q._)`${Z.default.errors} === 0`))}function lx({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 sm(t,e,n,r){let{gen:s,schema:o,data:i,allErrors:a,opts:l,self:u}=t,{RULES:p}=u;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,Lt.schemaHasRulesButRef)(o,p))){s.block(()=>fm(t,"$ref",p.all.$ref.definition));return}l.jtd||cx(t,e),s.block(()=>{for(let $ of p.rules)g($);g(p.post)});function g($){(0,ac.shouldUseGroup)(o,$)&&($.type?(s.if((0,Bo.checkDataType)($.type,i,l.strictNumbers)),om(t,$),e.length===1&&e[0]===$.type&&n&&(s.else(),(0,Bo.reportTypeError)(t)),s.endIf()):om(t,$),a||s.if((0,q._)`${Z.default.errors} === ${r||0}`))}}function om(t,e){let{gen:n,schema:r,opts:{useDefaults:s}}=t;s&&(0,W$.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,ac.shouldUseRule)(r,o)&&fm(t,o.keyword,o.definition,e.type)})}function cx(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(dx(t,e),t.opts.allowUnionTypes||ux(t,e),px(t,t.dataTypes))}function dx(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{hm(t.dataTypes,n)||lc(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),fx(t,e)}}function ux(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&lc(t,"use allowUnionTypes to allow union type keyword")}function px(t,e){let n=t.self.RULES.all;for(let r in n){let s=n[r];if(typeof s=="object"&&(0,ac.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>hx(e,i))&&lc(t,`missing type "${o.join(",")}" for keyword "${r}"`)}}}function hx(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function hm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function fx(t,e){let n=[];for(let r of t.dataTypes)hm(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function lc(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Lt.checkStrictMode)(t,e,t.opts.strictTypes)}var Fo=class{constructor(e,n,r){if((0,Xr.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,Lt.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",mm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Xr.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?Zr.reportExtraError:Zr.reportError)(this,this.def.error,n)}$dataError(){(0,Zr.reportError)(this,this.def.$dataError||Zr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Zr.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,Bo.checkDataTypes)(l,n,o.opts.strictNumbers,Bo.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,ic.getSubschema)(this.it,e);(0,ic.extendSubschemaData)(r,this.it,e),(0,ic.extendSubschemaMode)(r,e);let s={...this.it,...r,items:void 0,props:void 0};return tx(s,n),s}mergeEvaluated(e,n){let{it:r,gen:s}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Lt.mergeEvaluated.props(s,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Lt.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}};en.KeywordCxt=Fo;function fm(t,e,n,r){let s=new Fo(t,n,e);"code"in n?n.code(s,r):s.$data&&n.validate?(0,Xr.funcKeywordCode)(s,n):"macro"in n?(0,Xr.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,Xr.funcKeywordCode)(s,n)}var mx=/^\/(?:[^~]|~0|~1)*$/,gx=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function mm(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let s,o;if(t==="")return Z.default.rootData;if(t[0]==="/"){if(!mx.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Z.default.rootData}else{let u=gx.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+u[1];if(s=u[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 u of a)u&&(o=(0,q._)`${o}${(0,q.getProperty)((0,Lt.unescapeJsonPointer)(u))}`,i=(0,q._)`${i} && ${o}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}en.getData=mm});var Ho=M(dc=>{"use strict";Object.defineProperty(dc,"__esModule",{value:!0});var cc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};dc.default=cc});var es=M(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var uc=Yr(),pc=class extends Error{constructor(e,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,uc.resolveUrl)(e,n,r),this.missingSchema=(0,uc.normalizeId)((0,uc.getFullPath)(e,this.missingRef))}};hc.default=pc});var Vo=M(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var mt=ee(),bx=Ho(),yn=Nt(),gt=Yr(),gm=ue(),yx=Qr(),Xn=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,gt.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=Xn;function mc(t){let e=bm.call(this,t);if(e)return e;let n=(0,gt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new mt.CodeGen(this.scope,{es5:r,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:bx.default,code:(0,mt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:yn.default.data,parentData:yn.default.parentData,parentDataProperty:yn.default.parentDataProperty,dataNames:[yn.default.data],dataPathArr:[mt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,mt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:mt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,mt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,yx.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let g=i.toString();p=`${i.scopeRefs(yn.default.scope)}return ${g}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let v=new Function(`${yn.default.self}`,`${yn.default.scope}`,p)(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:g,scopeValues:i._values}),this.opts.unevaluated){let{props:S,items:T}=u;v.evaluated={props:S instanceof mt.Name?void 0:S,items:T instanceof mt.Name?void 0:T,dynamicProps:S instanceof mt.Name,dynamicItems:T instanceof mt.Name},v.source&&(v.source.evaluated=(0,mt.stringify)(v.evaluated))}return t.validate=v,t}catch(g){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),g}finally{this._compilations.delete(t)}}lt.compileSchema=mc;function wx(t,e,n){var r;n=(0,gt.resolveUrl)(this.opts.uriResolver,e,n);let s=t.refs[n];if(s)return s;let o=Sx.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 Xn({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=vx.call(this,o)}lt.resolveRef=wx;function vx(t){return(0,gt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:mc.call(this,t)}function bm(t){for(let e of this._compilations)if(kx(e,t))return e}lt.getCompilingSchema=bm;function kx(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Sx(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Ko.call(this,t,e)}function Ko(t,e){let n=this.opts.uriResolver.parse(e),r=(0,gt._getFullPath)(this.opts.uriResolver,n),s=(0,gt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===s)return fc.call(this,n,t);let o=(0,gt.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Ko.call(this,t,i);return typeof a?.schema!="object"?void 0:fc.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||mc.call(this,i),o===(0,gt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(s=(0,gt.resolveUrl)(this.opts.uriResolver,s,u)),new Xn({schema:a,schemaId:l,root:t,baseId:s})}return fc.call(this,n,i)}}lt.resolveSchema=Ko;var _x=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function fc(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,gm.unescapeFragment)(a)];if(l===void 0)return;n=l;let u=typeof n=="object"&&n[this.opts.schemaId];!_x.has(a)&&u&&(e=(0,gt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,gm.schemaHasRulesButRef)(n,this.RULES)){let a=(0,gt.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=Ko.call(this,r,a)}let{schemaId:i}=this.opts;if(o=o||new Xn({schema:n,schemaId:i,root:r,baseId:e}),o.schema!==o.root.schema)return o}});var ym=M((LL,$x)=>{$x.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 yc=M((jL,$m)=>{"use strict";var xx=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),vm=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),gc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),km=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Tx=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function bc(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 Rx=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function wm(t){return t.length=0,!0}function Ex(t,e,n){if(t.length){let r=bc(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function Px(t){let e=0,n={error:!1,address:"",zone:""},r=[],s=[],o=!1,i=!1,a=Ex;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){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(u==="%"){if(!a(s,r,n))break;a=wm}else{s.push(u);continue}}return s.length&&(a===wm?n.zone=s.join(""):i?r.push(s.join("")):r.push(bc(s))),n.address=r.join(""),n}function Sm(t){if(Ax(t,":")<2)return{host:t,isIPV6:!1};let e=Px(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 Ax(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function Ix(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 Cx={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Ox=/[@/?#:]/g,Nx=/[@/?#]/g;function _m(t,e){let n=e?Nx:Ox;return n.lastIndex=0,t.replace(n,r=>Cx[r])}function Lx(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(gc(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&km(i)?n+=i:n+="%"+o,r+=2;continue}}n+=t[r]}return n}function jx(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(gc(r)){let s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&km(o)?e+=o:e+="%"+s,n+=2;continue}}Tx(t[n])?e+=t[n]:e+=escape(t[n])}return e}function Dx(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(gc(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function Ux(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!vm(n)){let r=Sm(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=_m(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}$m.exports={nonSimpleDomain:Rx,recomposeAuthority:Ux,reescapeHostDelimiters:_m,normalizePercentEncoding:Lx,normalizePathEncoding:jx,escapePreservingEscapes:Dx,removeDotSegments:Ix,isIPv4:vm,isUUID:xx,normalizeIPv6:Sm,stringArrayToHexStripped:bc}});var Pm=M((DL,Em)=>{"use strict";var{isUUID:Mx}=yc(),zx=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,qx=["http","https","ws","wss","urn","urn:uuid"];function Bx(t){return qx.indexOf(t)!==-1}function wc(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 xm(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Tm(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 Fx(t){return t.secure=wc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Hx(t){if((t.port===(wc(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 Kx(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(zx);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=vc(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Vx(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=vc(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 Gx(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!Mx(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function Wx(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Rm={scheme:"http",domainHost:!0,parse:xm,serialize:Tm},Jx={scheme:"https",domainHost:Rm.domainHost,parse:xm,serialize:Tm},Go={scheme:"ws",domainHost:!0,parse:Fx,serialize:Hx},Yx={scheme:"wss",domainHost:Go.domainHost,parse:Go.parse,serialize:Go.serialize},Zx={scheme:"urn",parse:Kx,serialize:Vx,skipNormalize:!0},Xx={scheme:"urn:uuid",parse:Gx,serialize:Wx,skipNormalize:!0},Wo={http:Rm,https:Jx,ws:Go,wss:Yx,urn:Zx,"urn:uuid":Xx};Object.setPrototypeOf(Wo,null);function vc(t){return t&&(Wo[t]||Wo[t.toLowerCase()])||void 0}Em.exports={wsIsSecure:wc,SCHEMES:Wo,isValidSchemeName:Bx,getSchemeHandler:vc}});var Nm=M((UL,Zo)=>{"use strict";var{normalizeIPv6:Qx,removeDotSegments:ts,recomposeAuthority:eT,normalizePercentEncoding:tT,normalizePathEncoding:nT,escapePreservingEscapes:rT,reescapeHostDelimiters:sT,isIPv4:oT,nonSimpleDomain:iT}=yc(),{SCHEMES:aT,getSchemeHandler:Im}=Pm();function lT(t,e){return typeof t=="string"?t=mT(t,e):typeof t=="object"&&(t=Yo(wn(t,e),e)),t}function cT(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=Jo(t,r),{parsed:i,malformedAuthorityOrPort:a}=Jo(e,r);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=Cm(s,i,r,!0);return r.skipEscape=!0,wn(l,r)}function Cm(t,e,n,r){let s={};return r||(t=Yo(wn(t,n),n),e=Yo(wn(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=ts(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=ts(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=ts(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=ts(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 dT(t,e,n){let r=Am(t,n),s=Am(e,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function wn(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=Im(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=tT(n.path):(n.path=rT(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");let i=eT(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=ts(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 uT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,pT=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,hT=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function fT(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 Jo(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(pT);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(hT);if(a!==null){let u=a[1],p=u.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):u.length!==p.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",s=!0))}let l=t.match(uT);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 u=fT(r,l);if(u!==void 0&&(r.error=r.error||u,s=!0),r.host)if(oT(r.host)===!1){let $=Qx(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=Im(n.scheme||r.scheme);if(!n.unicodeSupport&&(!p||!p.unicodeSupport)&&r.host&&(n.domainHost||p&&p.domainHost)&&o===!1&&iT(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(g){r.error=r.error||"Host's domain name can not be converted to ASCII: "+g}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=sT(unescape(r.host),o))),r.path&&(r.path=nT(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 Yo(t,e){return Jo(t,e).parsed}function mT(t,e){return Om(t,e).normalized}function Om(t,e){let{parsed:n,malformedAuthorityOrPort:r}=Jo(t,e);return{normalized:r?t:wn(n,e),malformedAuthorityOrPort:r}}function Am(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=Om(t,e);return r?void 0:n}if(typeof t=="object")return wn(t,e)}var kc={SCHEMES:aT,normalize:lT,resolve:cT,resolveComponent:Cm,equal:dT,serialize:wn,parse:Yo};Zo.exports=kc;Zo.exports.default=kc;Zo.exports.fastUri=kc});var jm=M(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Lm=Nm();Lm.code='require("ajv/dist/runtime/uri").default';Sc.default=Lm});var Hm=M(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=void 0;var gT=Qr();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return gT.KeywordCxt}});var Qn=ee();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return Qn._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return Qn.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return Qn.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return Qn.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return Qn.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return Qn.CodeGen}});var bT=Ho(),qm=es(),yT=Yl(),ns=Vo(),wT=ee(),rs=Yr(),Xo=Jr(),$c=ue(),Dm=ym(),vT=jm(),Bm=(t,e)=>new RegExp(t,e);Bm.code="new RegExp";var kT=["removeAdditional","useDefaults","coerceTypes"],ST=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_T={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."},$T={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Um=200;function xT(t){var e,n,r,s,o,i,a,l,u,p,g,$,v,S,T,E,P,C,D,se,G,Fe,He,_n,$n;let sn=t.strict,jt=(e=t.code)===null||e===void 0?void 0:e.optimize,wt=jt===!0||jt===void 0?1:jt||0,bs=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:Bm,$i=(s=t.uriResolver)!==null&&s!==void 0?s:vT.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:sn)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:sn)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:sn)!==null&&p!==void 0?p:"log",strictTuples:($=(g=t.strictTuples)!==null&&g!==void 0?g:sn)!==null&&$!==void 0?$:"log",strictRequired:(S=(v=t.strictRequired)!==null&&v!==void 0?v:sn)!==null&&S!==void 0?S:!1,code:t.code?{...t.code,optimize:wt,regExp:bs}:{optimize:wt,regExp:bs},loopRequired:(T=t.loopRequired)!==null&&T!==void 0?T:Um,loopEnum:(E=t.loopEnum)!==null&&E!==void 0?E:Um,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(C=t.messages)!==null&&C!==void 0?C:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(se=t.schemaId)!==null&&se!==void 0?se:"$id",addUsedSchema:(G=t.addUsedSchema)!==null&&G!==void 0?G:!0,validateSchema:(Fe=t.validateSchema)!==null&&Fe!==void 0?Fe:!0,validateFormats:(He=t.validateFormats)!==null&&He!==void 0?He:!0,unicodeRegExp:(_n=t.unicodeRegExp)!==null&&_n!==void 0?_n:!0,int32range:($n=t.int32range)!==null&&$n!==void 0?$n:!0,uriResolver:$i}}var ss=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,...xT(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new wT.ValueScope({scope:{},prefixes:ST,es5:n,lines:r}),this.logger=IT(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,yT.getRules)(),Mm.call(this,_T,e,"NOT SUPPORTED"),Mm.call(this,$T,e,"DEPRECATED","warn"),this._metaOpts=PT.call(this),e.formats&&RT.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ET.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),TT.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,s=Dm;r==="id"&&(s={...Dm},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,g){await o.call(this,p.$schema);let $=this._addSchema(p,g);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(g){if(!(g instanceof qm.default))throw g;return a.call(this,g),await l.call(this,g.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:g}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${g} cannot be resolved`)}async function l(p){let g=await u.call(this,p);this.refs[p]||await o.call(this,g.$schema),this.refs[p]||this.addSchema(g,p,n)}async function u(p){let g=this._loading[p];if(g)return g;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,rs.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=zm.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,s=new ns.SchemaEnv({schema:{},schemaId:r});if(n=ns.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=zm.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,rs.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(OT.call(this,r,n),!n)return(0,$c.eachItem)(r,o=>_c.call(this,o)),this;LT.call(this,n);let s={...n,type:(0,Xo.getJSONTypes)(n.type),schemaType:(0,Xo.getJSONTypes)(n.schemaType)};return(0,$c.eachItem)(r,s.type.length===0?o=>_c.call(this,o,s):o=>s.type.forEach(i=>_c.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:u}=l.definition,p=i[a];u&&p&&(i[a]=Fm(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,rs.normalizeId)(i||r);let u=rs.getSchemaRefs.call(this,e,r);return l=new ns.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),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):ns.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{ns.compileSchema.call(this,e)}finally{this.opts=n}}};ss.ValidationError=bT.default;ss.MissingRefError=qm.default;Ie.default=ss;function Mm(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 zm(t){return t=(0,rs.normalizeId)(t),this.schemas[t]||this.refs[t]}function TT(){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 RT(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function ET(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 PT(){let t={...this.opts};for(let e of kT)delete t[e];return t}var AT={log(){},warn(){},error(){}};function IT(t){if(t===!1)return AT;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 CT=/^[a-z_$][a-z0-9_$:-]*$/i;function OT(t,e){let{RULES:n}=this;if((0,$c.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!CT.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 _c(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,Xo.getJSONTypes)(e.type),schemaType:(0,Xo.getJSONTypes)(e.schemaType)}};e.before?NT.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 NT(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 LT(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Fm(e)),t.validateSchema=this.compile(e,!0))}var jT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Fm(t){return{anyOf:[t,jT]}}});var Km=M(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var DT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};xc.default=DT});var Jm=M(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.callRef=vn.getValidate=void 0;var UT=es(),Vm=at(),Je=ee(),er=Nt(),Gm=Vo(),Qo=ue(),MT={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:u}=o;if((n==="#"||n==="#/")&&s===u.baseId)return g();let p=Gm.resolveRef.call(l,u,s,n);if(p===void 0)throw new UT.default(r.opts.uriResolver,s,n);if(p instanceof Gm.SchemaEnv)return $(p);return v(p);function g(){if(o===u)return ei(t,i,o,o.$async);let S=e.scopeValue("root",{ref:u});return ei(t,(0,Je._)`${S}.validate`,u,u.$async)}function $(S){let T=Wm(t,S);ei(t,T,S,S.$async)}function v(S){let T=e.scopeValue("schema",a.code.source===!0?{ref:S,code:(0,Je.stringify)(S)}:{ref:S}),E=e.name("valid"),P=t.subschema({schema:S,dataTypes:[],schemaPath:Je.nil,topSchemaRef:T,errSchemaPath:n},E);t.mergeEvaluated(P),t.ok(E)}}};function Wm(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Je._)`${n.scopeValue("wrapper",{ref:e})}.validate`}vn.getValidate=Wm;function ei(t,e,n,r){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,u=l.passContext?er.default.this:Je.nil;r?p():g();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let S=s.let("valid");s.try(()=>{s.code((0,Je._)`await ${(0,Vm.callValidateCode)(t,e,u)}`),v(e),i||s.assign(S,!0)},T=>{s.if((0,Je._)`!(${T} instanceof ${o.ValidationError})`,()=>s.throw(T)),$(T),i||s.assign(S,!1)}),t.ok(S)}function g(){t.result((0,Vm.callValidateCode)(t,e,u),()=>v(e),()=>$(e))}function $(S){let T=(0,Je._)`${S}.errors`;s.assign(er.default.vErrors,(0,Je._)`${er.default.vErrors} === null ? ${T} : ${er.default.vErrors}.concat(${T})`),s.assign(er.default.errors,(0,Je._)`${er.default.vErrors}.length`)}function v(S){var T;if(!o.opts.unevaluated)return;let E=(T=n?.validate)===null||T===void 0?void 0:T.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._)`${S}.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._)`${S}.evaluated.items`);o.items=Qo.mergeEvaluated.items(s,P,o.items,Je.Name)}}}vn.callRef=ei;vn.default=MT});var Ym=M(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var zT=Km(),qT=Jm(),BT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",zT.default,qT.default];Tc.default=BT});var Zm=M(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var ti=ee(),tn=ti.operators,ni={maximum:{okStr:"<=",ok:tn.LTE,fail:tn.GT},minimum:{okStr:">=",ok:tn.GTE,fail:tn.LT},exclusiveMaximum:{okStr:"<",ok:tn.LT,fail:tn.GTE},exclusiveMinimum:{okStr:">",ok:tn.GT,fail:tn.LTE}},FT={message:({keyword:t,schemaCode:e})=>(0,ti.str)`must be ${ni[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ti._)`{comparison: ${ni[t].okStr}, limit: ${e}}`},HT={keyword:Object.keys(ni),type:"number",schemaType:"number",$data:!0,error:FT,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,ti._)`${n} ${ni[e].fail} ${r} || isNaN(${n})`)}};Rc.default=HT});var Xm=M(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var os=ee(),KT={message:({schemaCode:t})=>(0,os.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,os._)`{multipleOf: ${t}}`},VT={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:KT,code(t){let{gen:e,data:n,schemaCode:r,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,os._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,os._)`${i} !== parseInt(${i})`;t.fail$data((0,os._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Ec.default=VT});var eg=M(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});function Qm(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}Pc.default=Qm;Qm.code='require("ajv/dist/runtime/ucs2length").default'});var tg=M(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var kn=ee(),GT=ue(),WT=eg(),JT={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,kn.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,kn._)`{limit: ${t}}`},YT={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:JT,code(t){let{keyword:e,data:n,schemaCode:r,it:s}=t,o=e==="maxLength"?kn.operators.GT:kn.operators.LT,i=s.opts.unicode===!1?(0,kn._)`${n}.length`:(0,kn._)`${(0,GT.useFunc)(t.gen,WT.default)}(${n})`;t.fail$data((0,kn._)`${i} ${o} ${r}`)}};Ac.default=YT});var ng=M(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var ZT=at(),XT=ue(),tr=ee(),QT={message:({schemaCode:t})=>(0,tr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,tr._)`{pattern: ${t}}`},eR={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:QT,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,u=l.code==="new RegExp"?(0,tr._)`new RegExp`:(0,XT.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,tr._)`${u}(${o}, ${a}).test(${n})`),()=>e.assign(p,!1)),t.fail$data((0,tr._)`!${p}`)}else{let l=(0,ZT.usePattern)(t,s);t.fail$data((0,tr._)`!${l}.test(${n})`)}}};Ic.default=eR});var rg=M(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var is=ee(),tR={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,is.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,is._)`{limit: ${t}}`},nR={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:tR,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxProperties"?is.operators.GT:is.operators.LT;t.fail$data((0,is._)`Object.keys(${n}).length ${s} ${r}`)}};Cc.default=nR});var sg=M(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var as=at(),ls=ee(),rR=ue(),sR={message:({params:{missingProperty:t}})=>(0,ls.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ls._)`{missingProperty: ${t}}`},oR={keyword:"required",type:"object",schemaType:"array",$data:!0,error:sR,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?u():p(),a.strictRequired){let v=t.parentSchema.properties,{definedProperties:S}=t.it;for(let T of n)if(v?.[T]===void 0&&!S.has(T)){let E=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${T}" is not defined at "${E}" (strictRequired)`;(0,rR.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(ls.nil,g);else for(let v of n)(0,as.checkReportMissingProp)(t,v)}function p(){let v=e.let("missing");if(l||o){let S=e.let("valid",!0);t.block$data(S,()=>$(v,S)),t.ok(S)}else e.if((0,as.checkMissingProp)(t,n,v)),(0,as.reportMissingProp)(t,v),e.else()}function g(){e.forOf("prop",r,v=>{t.setParams({missingProperty:v}),e.if((0,as.noPropertyInData)(e,s,v,a.ownProperties),()=>t.error())})}function $(v,S){t.setParams({missingProperty:v}),e.forOf(v,r,()=>{e.assign(S,(0,as.propertyInData)(e,s,v,a.ownProperties)),e.if((0,ls.not)(S),()=>{t.error(),e.break()})},ls.nil)}}};Oc.default=oR});var og=M(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var cs=ee(),iR={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,cs.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,cs._)`{limit: ${t}}`},aR={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:iR,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxItems"?cs.operators.GT:cs.operators.LT;t.fail$data((0,cs._)`${n}.length ${s} ${r}`)}};Nc.default=aR});var ri=M(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var ig=sc();ig.code='require("ajv/dist/runtime/equal").default';Lc.default=ig});var ag=M(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var jc=Jr(),Ce=ee(),lR=ue(),cR=ri(),dR={message:({params:{i:t,j:e}})=>(0,Ce.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ce._)`{i: ${t}, j: ${e}}`},uR={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:dR,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"),u=o.items?(0,jc.getSchemaTypes)(o.items):[];t.block$data(l,p,(0,Ce._)`${i} === false`),t.ok(l);function p(){let S=e.let("i",(0,Ce._)`${n}.length`),T=e.let("j");t.setParams({i:S,j:T}),e.assign(l,!0),e.if((0,Ce._)`${S} > 1`,()=>(g()?$:v)(S,T))}function g(){return u.length>0&&!u.some(S=>S==="object"||S==="array")}function $(S,T){let E=e.name("item"),P=(0,jc.checkDataTypes)(u,E,a.opts.strictNumbers,jc.DataType.Wrong),C=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${S}--;`,()=>{e.let(E,(0,Ce._)`${n}[${S}]`),e.if(P,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${E} == "string"`,(0,Ce._)`${E} += "_"`),e.if((0,Ce._)`typeof ${C}[${E}] == "number"`,()=>{e.assign(T,(0,Ce._)`${C}[${E}]`),t.error(),e.assign(l,!1).break()}).code((0,Ce._)`${C}[${E}] = ${S}`)})}function v(S,T){let E=(0,lR.useFunc)(e,cR.default),P=e.name("outer");e.label(P).for((0,Ce._)`;${S}--;`,()=>e.for((0,Ce._)`${T} = ${S}; ${T}--;`,()=>e.if((0,Ce._)`${E}(${n}[${S}], ${n}[${T}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Dc.default=uR});var lg=M(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var Uc=ee(),pR=ue(),hR=ri(),fR={message:"must be equal to constant",params:({schemaCode:t})=>(0,Uc._)`{allowedValue: ${t}}`},mR={keyword:"const",$data:!0,error:fR,code(t){let{gen:e,data:n,$data:r,schemaCode:s,schema:o}=t;r||o&&typeof o=="object"?t.fail$data((0,Uc._)`!${(0,pR.useFunc)(e,hR.default)}(${n}, ${s})`):t.fail((0,Uc._)`${o} !== ${n}`)}};Mc.default=mR});var cg=M(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var ds=ee(),gR=ue(),bR=ri(),yR={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ds._)`{allowedValues: ${t}}`},wR={keyword:"enum",schemaType:"array",$data:!0,error:yR,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,u=()=>l??(l=(0,gR.useFunc)(e,bR.default)),p;if(a||r)p=e.let("valid"),t.block$data(p,g);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let v=e.const("vSchema",o);p=(0,ds.or)(...s.map((S,T)=>$(v,T)))}t.pass(p);function g(){e.assign(p,!1),e.forOf("v",o,v=>e.if((0,ds._)`${u()}(${n}, ${v})`,()=>e.assign(p,!0).break()))}function $(v,S){let T=s[S];return typeof T=="object"&&T!==null?(0,ds._)`${u()}(${n}, ${v}[${S}])`:(0,ds._)`${n} === ${T}`}}};zc.default=wR});var dg=M(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var vR=Zm(),kR=Xm(),SR=tg(),_R=ng(),$R=rg(),xR=sg(),TR=og(),RR=ag(),ER=lg(),PR=cg(),AR=[vR.default,kR.default,SR.default,_R.default,$R.default,xR.default,TR.default,RR.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},ER.default,PR.default];qc.default=AR});var Fc=M(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.validateAdditionalItems=void 0;var Sn=ee(),Bc=ue(),IR={message:({params:{len:t}})=>(0,Sn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Sn._)`{limit: ${t}}`},CR={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:IR,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}ug(t,r)}};function ug(t,e){let{gen:n,schema:r,data:s,keyword:o,it:i}=t;i.items=!0;let a=n.const("len",(0,Sn._)`${s}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Sn._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Bc.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Sn._)`${a} <= ${e.length}`);n.if((0,Sn.not)(u),()=>l(u)),t.ok(u)}function l(u){n.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:Bc.Type.Num},u),i.allErrors||n.if((0,Sn.not)(u),()=>n.break())})}}us.validateAdditionalItems=ug;us.default=CR});var Hc=M(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.validateTuple=void 0;var pg=ee(),si=ue(),OR=at(),NR={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return hg(t,"additionalItems",e);n.items=!0,!(0,si.alwaysValidSchema)(n,e)&&t.ok((0,OR.validateArray)(t))}};function hg(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=si.mergeEvaluated.items(r,n.length,a.items));let l=r.name("valid"),u=r.const("len",(0,pg._)`${o}.length`);n.forEach((g,$)=>{(0,si.alwaysValidSchema)(a,g)||(r.if((0,pg._)`${u} > ${$}`,()=>t.subschema({keyword:i,schemaProp:$,dataProp:$},l)),t.ok(l))});function p(g){let{opts:$,errSchemaPath:v}=a,S=n.length,T=S===g.minItems&&(S===g.maxItems||g[e]===!1);if($.strictTuples&&!T){let E=`"${i}" is ${S}-tuple, but minItems or maxItems/${e} are not specified or different at path "${v}"`;(0,si.checkStrictMode)(a,E,$.strictTuples)}}}ps.validateTuple=hg;ps.default=NR});var fg=M(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var LR=Hc(),jR={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,LR.validateTuple)(t,"items")};Kc.default=jR});var gg=M(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var mg=ee(),DR=ue(),UR=at(),MR=Fc(),zR={message:({params:{len:t}})=>(0,mg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,mg._)`{limit: ${t}}`},qR={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:zR,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:s}=n;r.items=!0,!(0,DR.alwaysValidSchema)(r,e)&&(s?(0,MR.validateAdditionalItems)(t,s):t.ok((0,UR.validateArray)(t)))}};Vc.default=qR});var bg=M(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var ct=ee(),oi=ue(),BR={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}}`},FR={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:BR,code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t,i,a,{minContains:l,maxContains:u}=r;o.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=e.const("len",(0,ct._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,oi.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,oi.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,oi.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 g=e.name("valid");a===void 0&&i===1?v(g,()=>e.if(g,()=>e.break())):i===0?(e.let(g,!0),a!==void 0&&e.if((0,ct._)`${s}.length > 0`,$)):(e.let(g,!1),$()),t.result(g,()=>t.reset());function $(){let T=e.name("_valid"),E=e.let("count",0);v(T,()=>e.if(T,()=>S(E)))}function v(T,E){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:oi.Type.Num,compositeRule:!0},T),E()})}function S(T){e.code((0,ct._)`${T}++`),a===void 0?e.if((0,ct._)`${T} >= ${i}`,()=>e.assign(g,!0).break()):(e.if((0,ct._)`${T} > ${a}`,()=>e.assign(g,!1).break()),i===1?e.assign(g,!0):e.if((0,ct._)`${T} >= ${i}`,()=>e.assign(g,!0)))}}};Gc.default=FR});var vg=M($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.validateSchemaDeps=$t.validatePropertyDeps=$t.error=void 0;var Wc=ee(),HR=ue(),hs=at();$t.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Wc.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Wc._)`{property: ${t},
|
|
1959
|
+
]`;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 dl,mt,P_,Co=j(()=>{Xt();mt={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:()=>(dl===void 0&&(dl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),dl),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-_]*$/};P_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as zr}from"zod/v3";function Oo(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===zr.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===zr.ZodString&&t.keyType._def.checks?.length){let{type:r,...s}=Io(t.keyType._def,e);return{...n,propertyNames:s}}else{if(t.keyType?._def.typeName===zr.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===zr.ZodBranded&&t.keyType._def.type._def.typeName===zr.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...s}=Po(t.keyType._def,e);return{...n,propertyNames:s}}}return n}var No=j(()=>{xe();Co();Ao();at()});function df(t,e){if(e.mapStrategy==="record")return Oo(t,e);let n=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),r=Y(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 pl=j(()=>{xe();No();at()});function uf(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 hl=j(()=>{});function pf(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}var fl=j(()=>{at()});function hf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ml=j(()=>{});function mf(t,e){if(e.target==="openApi3")return ff(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Br&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,o)=>{let i=Br[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 ff(t,e)}var Br,ff,Lo=j(()=>{xe();Br={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};ff=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>Y(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 gf(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:Br[t.innerType._def.typeName],nullable:!0}:{type:[Br[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var gl=j(()=>{xe();Lo()});function bf(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",Xa(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?le(n,"minimum",r.value,r.message,e):le(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),le(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?le(n,"maximum",r.value,r.message,e):le(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),le(n,"maximum",r.value,r.message,e));break;case"multipleOf":le(n,"multipleOf",r.value,r.message,e);break}return n}var bl=j(()=>{Xt()});function yf(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 u=C_(l);u&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=Y(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(r.properties[a]=p,u||s.push(a))}s.length&&(r.required=s);let i=I_(t,e);return i!==void 0&&(r.additionalProperties=i),r}function I_(t,e){if(t.catchall._def.typeName!=="ZodNever")return Y(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 C_(t){try{return t.isOptional()}catch{return!0}}var yl=j(()=>{xe()});var wf,wl=j(()=>{xe();at();wf=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:we(e)},n]}:we(e)}});var vf,vl=j(()=>{xe();vf=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let n=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}}});function kf(t,e){return Y(t.type._def,e)}var kl=j(()=>{xe()});function Sf(t,e){let r={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&le(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&le(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var Sl=j(()=>{Xt();xe()});function _f(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Y(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var _l=j(()=>{xe()});function $f(t){return{not:we(t)}}var $l=j(()=>{at()});function xf(t){return we(t)}var xl=j(()=>{at()});var Tf,Tl=j(()=>{xe();Tf=(t,e)=>Y(t.innerType._def,e)});import{ZodFirstPartyTypeKind as ie}from"zod/v3";var Rf,Rl=j(()=>{at();Qa();el();tl();Ao();nl();sl();ol();il();al();ll();cl();pl();hl();fl();ml();gl();bl();yl();wl();vl();kl();No();Sl();Co();_l();$l();Lo();xl();Tl();Rf=(t,e,n)=>{switch(e){case ie.ZodString:return Io(t,n);case ie.ZodNumber:return bf(t,n);case ie.ZodObject:return yf(t,n);case ie.ZodBigInt:return ef(t,n);case ie.ZodBoolean:return tf();case ie.ZodDate:return rl(t,n);case ie.ZodUndefined:return $f(n);case ie.ZodNull:return hf(n);case ie.ZodArray:return Qh(t,n);case ie.ZodUnion:case ie.ZodDiscriminatedUnion:return mf(t,n);case ie.ZodIntersection:return af(t,n);case ie.ZodTuple:return _f(t,n);case ie.ZodRecord:return Oo(t,n);case ie.ZodLiteral:return lf(t,n);case ie.ZodEnum:return of(t);case ie.ZodNativeEnum:return uf(t);case ie.ZodNullable:return gf(t,n);case ie.ZodOptional:return wf(t,n);case ie.ZodMap:return df(t,n);case ie.ZodSet:return Sf(t,n);case ie.ZodLazy:return()=>t.getter()._def;case ie.ZodPromise:return kf(t,n);case ie.ZodNaN:case ie.ZodNever:return pf(n);case ie.ZodEffects:return sf(t,n);case ie.ZodAny:return we(n);case ie.ZodUnknown:return xf(n);case ie.ZodDefault:return rf(t,n);case ie.ZodBranded:return Po(t,n);case ie.ZodReadonly:return Tf(t,n);case ie.ZodCatch:return nf(t,n);case ie.ZodPipeline:return vf(t,n);case ie.ZodFunction:case ie.ZodVoid:case ie.ZodSymbol:return;default:return(r=>{})(e)}}});function Y(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==Yh)return a}if(r&&!n){let a=O_(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=Rf(t,t.typeName,e),i=typeof o=="function"?Y(o(),e):o;if(i&&N_(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var O_,N_,xe=j(()=>{To();Rl();Eo();at();O_=(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}},N_=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var Ef=j(()=>{});var El,Pl=j(()=>{xe();Za();at();El=(t,e)=>{let n=Xh(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:Y(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??we(n)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=Y(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 Pf=j(()=>{To();Za();Xt();Eo();xe();Ef();at();Qa();el();tl();Ao();nl();sl();ol();il();al();ll();cl();pl();hl();fl();ml();gl();bl();yl();wl();vl();kl();Tl();No();Sl();Co();_l();$l();Lo();xl();Rl();Pl();Pl()});import*as Af from"zod/v4-mini";function L_(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Al(t,e){return xt(t)?Af.toJSONSchema(t,{target:L_(e?.target),io:e?.pipeStrategy??"input"}):El(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Il(t){let n=Jt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Bn(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Cl(t,e){let n=Wt(t,e);if(!n.success)throw n.error;return n.data}var Ol=j(()=>{Ar();Pf()});function If(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Cf(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];If(i)&&If(o)?n[s]={...i,...o}:n[s]=o}return n}var j_,jo,Of=j(()=>{Ar();Wn();Wh();Ol();j_=6e4,jo=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(lo,n=>{this._oncancel(n)}),this.setNotificationHandler(uo,n=>{this._onprogress(n)}),this.setRequestHandler(co,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(po,async(n,r)=>{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(V.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(fo,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,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),a.type==="response")p(l);else{let g=l,x=new z(g.error.code,g.error.message,g.error.data);p(x)}else{let g=a.type==="response"?"Response":"Error";this._onerror(new Error(`${g} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new z(V.InvalidParams,`Task not found: ${o}`);if(!Zt(i.status))return await this._waitForTaskUpdate(o,r.signal),await s();if(Zt(i.status)){let a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Yt]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(mo,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(V.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(bo,async(n,r)=>{try{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(V.InvalidParams,`Task not found: ${n.params.taskId}`);if(Zt(s.status))throw new z(V.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(V.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof z?s:new z(V.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(V.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),Cr(o)||Dh(o)?this._onresponse(o):Da(o)?this._onrequest(o,i):jh(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(V.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?.[Yt]?.taskId;if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:V.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):s?.send(p).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Oh(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let g={relatedRequestId:e.id};o&&(g.relatedTask={taskId:o}),await this.notification(p,g)},sendRequest:async(p,g,x)=>{if(i.signal.aborted)throw new z(V.ConnectionClosed,"Request was cancelled");let b={...x,relatedRequestId:e.id};o&&!b.relatedTask&&(b.relatedTask={taskId:o});let S=b.relatedTask?.taskId??o;return S&&l&&await l.updateTaskStatus(S,"input_required"),await this.request(p,g,b)},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,u)).then(async p=>{if(i.signal.aborted)return;let g={result:p,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:g,timestamp:Date.now()},s?.sessionId):await s?.send(g)},async p=>{if(i.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:V.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:g,timestamp:Date.now()},s?.sessionId):await s?.send(g)}).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),Cr(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(Cr(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),Cr(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(V.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Hn,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(V.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Zt(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(V.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(V.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(u=>setTimeout(u,l)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(V.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=r??{};return new Promise((u,p)=>{let g=N=>{p(N)};if(!this._transport){g(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(N){g(N);return}r?.signal?.throwIfAborted();let x=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:x};r?.onprogress&&(this._progressHandlers.set(x,r.onprogress),b.params={...e.params,_meta:{...e.params?._meta||{},progressToken:x}}),a&&(b.params={...b.params,task:a}),l&&(b.params={...b.params,_meta:{...b.params?._meta||{},[Yt]:l}});let S=N=>{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(N)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(W=>this._onerror(new Error(`Failed to send cancellation: ${W}`)));let D=N instanceof z?N:new z(V.RequestTimeout,String(N));p(D)};this._responseHandlers.set(x,N=>{if(!r?.signal?.aborted){if(N instanceof Error)return p(N);try{let D=Wt(n,N.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),r?.signal?.addEventListener("abort",()=>{S(r?.signal?.reason)});let T=r?.timeout??j_,R=()=>S(z.fromError(V.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(x,T,r?.maxTotalTimeout,R,r?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let N=D=>{let W=this._responseHandlers.get(x);W?W(D):this._onerror(new Error(`Response handler missing for side-channeled request ${x}`))};this._requestResolvers.set(x,N),this._enqueueTaskMessage(P,{type:"request",message:b,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(x),p(D)})}else this._transport.send(b,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(N=>{this._cleanupTimeout(x),p(N)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},ho,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},go,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},qh,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||{},[Yt]: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||{},[Yt]: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||{},[Yt]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Il(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,o)=>{let i=Cl(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=Il(e);this._notificationHandlers.set(r,s=>{let o=Cl(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"&&Da(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new z(V.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(V.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,r);n.addEventListener("abort",()=>{clearTimeout(i),o(new z(V.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(V.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=Dr.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Zt(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(V.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Zt(a.status))throw new z(V.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 u=Dr.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Zt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}});var Kr=M(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var Fr=class{};he._CodeOrName=Fr;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var bn=class extends Fr{constructor(e){if(super(),!he.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}}};he.Name=bn;var lt=class extends Fr{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 bn&&(n[r.str]=(n[r.str]||0)+1),n),{})}};he._Code=lt;he.nil=new lt("");function Nf(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Ll(n,e[r]),n.push(t[++r]);return new lt(n)}he._=Nf;var Nl=new lt("+");function Lf(t,...e){let n=[Hr(t[0])],r=0;for(;r<e.length;)n.push(Nl),Ll(n,e[r]),n.push(Nl,Hr(t[++r]));return D_(n),new lt(n)}he.str=Lf;function Ll(t,e){e instanceof lt?t.push(...e._items):e instanceof bn?t.push(e):t.push(q_(e))}he.addCodeArg=Ll;function D_(t){let e=1;for(;e<t.length-1;){if(t[e]===Nl){let n=U_(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function U_(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof bn||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 bn))return`"${t}${e.slice(1)}`}function M_(t,e){return e.emptyStr()?t:t.emptyStr()?e:Lf`${t}${e}`}he.strConcat=M_;function q_(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Hr(Array.isArray(t)?t.join(","):t)}function z_(t){return new lt(Hr(t))}he.stringify=z_;function Hr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Hr;function B_(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new lt(`.${t}`):Nf`[${t}]`}he.getProperty=B_;function F_(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new lt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=F_;function H_(t){return new lt(t.toString())}he.regexpCode=H_});var Ul=M(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.ValueScope=Ye.ValueScopeName=Ye.Scope=Ye.varKinds=Ye.UsedValueState=void 0;var Je=Kr(),jl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Do;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Do||(Ye.UsedValueState=Do={}));Ye.varKinds={const:new Je.Name("const"),let:new Je.Name("let"),var:new Je.Name("var")};var Uo=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Je.Name?e:this.name(e)}name(e){return new Je.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}}};Ye.Scope=Uo;var Mo=class extends Je.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Je._)`.${new Je.Name(n)}[${r}]`}};Ye.ValueScopeName=Mo;var K_=(0,Je._)`\n`,Dl=class extends Uo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?K_:Je.nil}}get(){return this._scope}name(e){return new Mo(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]=[]),u=l.length;return l[u]=n.ref,s.setValue(n,{property:o,itemIndex:u}),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,Je._)`${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=Je.nil;for(let i in e){let a=e[i];if(!a)continue;let l=r[i]=r[i]||new Map;a.forEach(u=>{if(l.has(u))return;l.set(u,Do.Started);let p=n(u);if(p){let g=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const;o=(0,Je._)`${o}${g} ${u} = ${p};${this.opts._n}`}else if(p=s?.(u))o=(0,Je._)`${o}${p}${this.opts._n}`;else throw new jl(u);l.set(u,Do.Completed)})}return o}};Ye.ValueScope=Dl});var te=M(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var ce=Kr(),bt=Ul(),Qt=Kr();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return Qt._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return Qt.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return Qt.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return Qt.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return Qt.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return Qt.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return Qt.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return Qt.Name}});var Fo=Ul();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Fo.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Fo.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Fo.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Fo.varKinds}});ne.operators={GT:new ce._Code(">"),GTE:new ce._Code(">="),LT:new ce._Code("<"),LTE:new ce._Code("<="),EQ:new ce._Code("==="),NEQ:new ce._Code("!=="),NOT:new ce._Code("!"),OR:new ce._Code("||"),AND:new ce._Code("&&"),ADD:new ce._Code("+")};var Lt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Ml=class extends Lt{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?bt.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=Yn(this.rhs,e,n)),this}get names(){return this.rhs instanceof ce._CodeOrName?this.rhs.names:{}}},qo=class extends Lt{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 ce.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Yn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ce.Name?{}:{...this.lhs.names};return Bo(e,this.rhs)}},ql=class extends qo{constructor(e,n,r,s){super(e,r,s),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},zl=class extends Lt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Bl=class extends Lt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Fl=class extends Lt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Hl=class extends Lt{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=Yn(this.code,e,n),this}get names(){return this.code instanceof ce._CodeOrName?this.code.names:{}}},Vr=class extends Lt{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)||(V_(e,o.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>vn(e,n.names),{})}},jt=class extends Vr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Kl=class extends Vr{},Jn=class extends jt{};Jn.kind="else";var yn=class t extends jt{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 Jn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(jf(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=Yn(this.condition,e,n),this}get names(){let e=super.names;return Bo(e,this.condition),this.else&&vn(e,this.else.names),e}};yn.kind="if";var wn=class extends jt{};wn.kind="for";var Vl=class extends wn{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=Yn(this.iteration,e,n),this}get names(){return vn(super.names,this.iteration.names)}},Gl=class extends wn{constructor(e,n,r,s){super(),this.varKind=e,this.name=n,this.from=r,this.to=s}render(e){let n=e.es5?bt.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=Bo(super.names,this.from);return Bo(e,this.to)}},zo=class extends wn{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=Yn(this.iterable,e,n),this}get names(){return vn(super.names,this.iterable.names)}},Gr=class extends jt{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)}};Gr.kind="func";var Wr=class extends Vr{render(e){return"return "+super.render(e)}};Wr.kind="return";var Wl=class extends jt{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&&vn(e,this.catch.names),this.finally&&vn(e,this.finally.names),e}},Jr=class extends jt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Jr.kind="catch";var Yr=class extends jt{render(e){return"finally"+super.render(e)}};Yr.kind="finally";var Jl=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
1960
|
+
`:""},this._extScope=e,this._scope=new bt.Scope({parent:e}),this._nodes=[new Kl]}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 Ml(e,o,r)),o}const(e,n,r){return this._def(bt.varKinds.const,e,n,r)}let(e,n,r){return this._def(bt.varKinds.let,e,n,r)}var(e,n,r){return this._def(bt.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new qo(e,n,r))}add(e,n){return this._leafNode(new ql(e,ne.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new Hl(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,ce.addCodeArg)(n,s));return n.push("}"),new ce._Code(n)}if(e,n,r){if(this._blockNode(new yn(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 yn(e))}else(){return this._elseNode(new Jn)}endIf(){return this._endBlockNode(yn,Jn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Vl(e),n)}forRange(e,n,r,s,o=this.opts.es5?bt.varKinds.var:bt.varKinds.let){let i=this._scope.toName(e);return this._for(new Gl(o,i,n,r),()=>s(i))}forOf(e,n,r,s=bt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=n instanceof ce.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,ce._)`${i}.length`,a=>{this.var(o,(0,ce._)`${i}[${a}]`),r(o)})}return this._for(new zo("of",s,o,n),()=>r(o))}forIn(e,n,r,s=this.opts.es5?bt.varKinds.var:bt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ce._)`Object.keys(${n})`,r);let o=this._scope.toName(e);return this._for(new zo("in",s,o,n),()=>r(o))}endFor(){return this._endBlockNode(wn)}label(e){return this._leafNode(new zl(e))}break(e){return this._leafNode(new Bl(e))}return(e){let n=new Wr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Wr)}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 Jr(o),n(o)}return r&&(this._currNode=s.finally=new Yr,this.code(r)),this._endBlockNode(Jr,Yr)}throw(e){return this._leafNode(new Fl(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=ce.nil,r,s){return this._blockNode(new Gr(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Gr)}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 yn))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}};ne.CodeGen=Jl;function vn(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function Bo(t,e){return e instanceof ce._CodeOrName?vn(t,e.names):t}function Yn(t,e,n){if(t instanceof ce.Name)return r(t);if(!s(t))return t;return new ce._Code(t._items.reduce((o,i)=>(i instanceof ce.Name&&(i=r(i)),i instanceof ce._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 ce._Code&&o._items.some(i=>i instanceof ce.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function V_(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function jf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${Yl(t)}`}ne.not=jf;var G_=Df(ne.operators.AND);function W_(...t){return t.reduce(G_)}ne.and=W_;var J_=Df(ne.operators.OR);function Y_(...t){return t.reduce(J_)}ne.or=Y_;function Df(t){return(e,n)=>e===ce.nil?n:n===ce.nil?e:(0,ce._)`${Yl(e)} ${t} ${Yl(n)}`}function Yl(t){return t instanceof ce.Name?t:(0,ce._)`(${t})`}});var ue=M(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.checkStrictMode=re.getErrorPath=re.Type=re.useFunc=re.setEvaluated=re.evaluatedPropsToName=re.mergeEvaluated=re.eachItem=re.unescapeJsonPointer=re.escapeJsonPointer=re.escapeFragment=re.unescapeFragment=re.schemaRefOrVal=re.schemaHasRulesButRef=re.schemaHasRules=re.checkUnknownRules=re.alwaysValidSchema=re.toHash=void 0;var ge=te(),Z_=Kr();function X_(t){let e={};for(let n of t)e[n]=!0;return e}re.toHash=X_;function Q_(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(qf(t,e),!zf(e,t.self.RULES.all))}re.alwaysValidSchema=Q_;function qf(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]||Hf(t,`unknown keyword: "${o}"`)}re.checkUnknownRules=qf;function zf(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}re.schemaHasRules=zf;function e$(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}re.schemaHasRulesButRef=e$;function t$({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)}`}re.schemaRefOrVal=t$;function n$(t){return Bf(decodeURIComponent(t))}re.unescapeFragment=n$;function r$(t){return encodeURIComponent(Xl(t))}re.escapeFragment=r$;function Xl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=Xl;function Bf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=Bf;function s$(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}re.eachItem=s$;function Uf({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}}re.mergeEvaluated={props:Uf({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} || {}`),Ql(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Ff}),items:Uf({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 Ff(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,ge._)`{}`);return e!==void 0&&Ql(t,n,e),n}re.evaluatedPropsToName=Ff;function Ql(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(r)}`,!0))}re.setEvaluated=Ql;var Mf={};function o$(t,e){return t.scopeValue("func",{ref:e,code:Mf[e.code]||(Mf[e.code]=new Z_._Code(e.code))})}re.useFunc=o$;var Zl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Zl||(re.Type=Zl={}));function i$(t,e,n){if(t instanceof ge.Name){let r=e===Zl.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():"/"+Xl(t)}re.getErrorPath=i$;function Hf(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}re.checkStrictMode=Hf});var Dt=M(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var De=te(),a$={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};ec.default=a$});var Zr=M(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.extendErrors=Ue.resetErrorsCount=Ue.reportExtraError=Ue.reportError=Ue.keyword$DataError=Ue.keywordError=void 0;var pe=te(),Ho=ue(),He=Dt();Ue.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};Ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,pe.str)`"${t}" keyword must be ${e} ($data)`:(0,pe.str)`"${t}" keyword is invalid ($data)`};function l$(t,e=Ue.keywordError,n,r){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=Gf(t,e,n);r??(i||a)?Kf(o,l):Vf(s,(0,pe._)`[${l}]`)}Ue.reportError=l$;function c$(t,e=Ue.keywordError,n){let{it:r}=t,{gen:s,compositeRule:o,allErrors:i}=r,a=Gf(t,e,n);Kf(s,a),o||i||Vf(r,He.default.vErrors)}Ue.reportExtraError=c$;function d$(t,e){t.assign(He.default.errors,e),t.if((0,pe._)`${He.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${He.default.vErrors}.length`,e),()=>t.assign(He.default.vErrors,null)))}Ue.resetErrorsCount=d$;function u$({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,He.default.errors,a=>{t.const(i,(0,pe._)`${He.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(He.default.instancePath,o.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,n),t.assign((0,pe._)`${i}.data`,r))})}Ue.extendErrors=u$;function Kf(t,e){let n=t.const("err",e);t.if((0,pe._)`${He.default.vErrors} === null`,()=>t.assign(He.default.vErrors,(0,pe._)`[${n}]`),(0,pe._)`${He.default.vErrors}.push(${n})`),t.code((0,pe._)`${He.default.errors}++`)}function Vf(t,e){let{gen:n,validateName:r,schemaEnv:s}=t;s.$async?n.throw((0,pe._)`new ${t.ValidationError}(${e})`):(n.assign((0,pe._)`${r}.errors`,e),n.return(!1))}var kn={keyword:new pe.Name("keyword"),schemaPath:new pe.Name("schemaPath"),params:new pe.Name("params"),propertyName:new pe.Name("propertyName"),message:new pe.Name("message"),schema:new pe.Name("schema"),parentSchema:new pe.Name("parentSchema")};function Gf(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,pe._)`{}`:p$(t,e,n)}function p$(t,e,n={}){let{gen:r,it:s}=t,o=[h$(s,n),f$(t,n)];return m$(t,e,o),r.object(...o)}function h$({errorPath:t},{instancePath:e}){let n=e?(0,pe.str)`${t}${(0,Ho.getErrorPath)(e,Ho.Type.Str)}`:t;return[He.default.instancePath,(0,pe.strConcat)(He.default.instancePath,n)]}function f$({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let s=r?e:(0,pe.str)`${e}/${t}`;return n&&(s=(0,pe.str)`${s}${(0,Ho.getErrorPath)(n,Ho.Type.Str)}`),[kn.schemaPath,s]}function m$(t,{params:e,message:n},r){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:g}=a;r.push([kn.keyword,s],[kn.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),l.messages&&r.push([kn.message,typeof n=="function"?n(t):n]),l.verbose&&r.push([kn.schema,i],[kn.parentSchema,(0,pe._)`${p}${g}`],[He.default.data,o]),u&&r.push([kn.propertyName,u])}});var Jf=M(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.boolOrEmptySchema=Zn.topBoolOrEmptySchema=void 0;var g$=Zr(),b$=te(),y$=Dt(),w$={message:"boolean schema is false"};function v$(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Wf(t,!1):typeof n=="object"&&n.$async===!0?e.return(y$.default.data):(e.assign((0,b$._)`${r}.errors`,null),e.return(!0))}Zn.topBoolOrEmptySchema=v$;function k$(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Wf(t)):n.var(e,!0)}Zn.boolOrEmptySchema=k$;function Wf(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,g$.reportError)(s,w$,void 0,e)}});var tc=M(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.getRules=Xn.isJSONType=void 0;var S$=["string","number","integer","boolean","null","object","array"],_$=new Set(S$);function $$(t){return typeof t=="string"&&_$.has(t)}Xn.isJSONType=$$;function x$(){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:{}}}Xn.getRules=x$});var nc=M(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.shouldUseRule=en.shouldUseGroup=en.schemaHasRulesForType=void 0;function T$({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&Yf(t,r)}en.schemaHasRulesForType=T$;function Yf(t,e){return e.rules.some(n=>Zf(t,n))}en.shouldUseGroup=Yf;function Zf(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))}en.shouldUseRule=Zf});var Xr=M(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.reportTypeError=Me.checkDataTypes=Me.checkDataType=Me.coerceAndCheckDataType=Me.getJSONTypes=Me.getSchemaTypes=Me.DataType=void 0;var R$=tc(),E$=nc(),P$=Zr(),ee=te(),Xf=ue(),Qn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Qn||(Me.DataType=Qn={}));function A$(t){let e=Qf(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}Me.getSchemaTypes=A$;function Qf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(R$.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Me.getJSONTypes=Qf;function I$(t,e){let{gen:n,data:r,opts:s}=t,o=C$(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,E$.schemaHasRulesForType)(t,e[0]));if(i){let a=sc(e,r,s.strictNumbers,Qn.Wrong);n.if(a,()=>{o.length?O$(t,e,o):oc(t)})}return i}Me.coerceAndCheckDataType=I$;var em=new Set(["string","number","integer","boolean","null"]);function C$(t,e){return e?t.filter(n=>em.has(n)||e==="array"&&n==="array"):[]}function O$(t,e,n){let{gen:r,data:s,opts:o}=t,i=r.let("dataType",(0,ee._)`typeof ${s}`),a=r.let("coerced",(0,ee._)`undefined`);o.coerceTypes==="array"&&r.if((0,ee._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,ee._)`${s}[0]`).assign(i,(0,ee._)`typeof ${s}`).if(sc(e,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,ee._)`${a} !== undefined`);for(let u of n)(em.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);r.else(),oc(t),r.endIf(),r.if((0,ee._)`${a} !== undefined`,()=>{r.assign(s,a),N$(t,a)});function l(u){switch(u){case"string":r.elseIf((0,ee._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ee._)`"" + ${s}`).elseIf((0,ee._)`${s} === null`).assign(a,(0,ee._)`""`);return;case"number":r.elseIf((0,ee._)`${i} == "boolean" || ${s} === null
|
|
1961
|
+
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,ee._)`+${s}`);return;case"integer":r.elseIf((0,ee._)`${i} === "boolean" || ${s} === null
|
|
1962
|
+
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,ee._)`+${s}`);return;case"boolean":r.elseIf((0,ee._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,ee._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":r.elseIf((0,ee._)`${s} === "" || ${s} === 0 || ${s} === false`),r.assign(a,null);return;case"array":r.elseIf((0,ee._)`${i} === "string" || ${i} === "number"
|
|
1963
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,ee._)`[${s}]`)}}}function N$({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${n}]`,r))}function rc(t,e,n,r=Qn.Correct){let s=r===Qn.Correct?ee.operators.EQ:ee.operators.NEQ,o;switch(t){case"null":return(0,ee._)`${e} ${s} null`;case"array":o=(0,ee._)`Array.isArray(${e})`;break;case"object":o=(0,ee._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,ee._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,ee._)`typeof ${e} ${s} ${t}`}return r===Qn.Correct?o:(0,ee.not)(o);function i(a=ee.nil){return(0,ee.and)((0,ee._)`typeof ${e} == "number"`,a,n?(0,ee._)`isFinite(${e})`:ee.nil)}}Me.checkDataType=rc;function sc(t,e,n,r){if(t.length===1)return rc(t[0],e,n,r);let s,o=(0,Xf.toHash)(t);if(o.array&&o.object){let i=(0,ee._)`typeof ${e} != "object"`;s=o.null?i:(0,ee._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=ee.nil;o.number&&delete o.integer;for(let i in o)s=(0,ee.and)(s,rc(i,e,n,r));return s}Me.checkDataTypes=sc;var L$={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function oc(t){let e=j$(t);(0,P$.reportError)(e,L$)}Me.reportTypeError=oc;function j$(t){let{gen:e,data:n,schema:r}=t,s=(0,Xf.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:t}}});var nm=M(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.assignDefaults=void 0;var er=te(),D$=ue();function U$(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let s in n)tm(t,s,n[s].default);else e==="array"&&Array.isArray(r)&&r.forEach((s,o)=>tm(t,o,s.default))}Ko.assignDefaults=U$;function tm(t,e,n){let{gen:r,compositeRule:s,data:o,opts:i}=t;if(n===void 0)return;let a=(0,er._)`${o}${(0,er.getProperty)(e)}`;if(s){(0,D$.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,er._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,er._)`${l} || ${a} === null || ${a} === ""`),r.if(l,(0,er._)`${a} = ${(0,er.stringify)(n)}`)}});var ct=M(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=te(),ic=ue(),tn=Dt(),M$=ue();function q$(t,e){let{gen:n,data:r,it:s}=t;n.if(lc(n,r,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,be._)`${e}`},!0),t.error()})}me.checkReportMissingProp=q$;function z$({gen:t,data:e,it:{opts:n}},r,s){return(0,be.or)(...r.map(o=>(0,be.and)(lc(t,e,o,n.ownProperties),(0,be._)`${s} = ${o}`)))}me.checkMissingProp=z$;function B$(t,e){t.setParams({missingProperty:e},!0),t.error()}me.reportMissingProp=B$;function rm(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,be._)`Object.prototype.hasOwnProperty`})}me.hasPropFunc=rm;function ac(t,e,n){return(0,be._)`${rm(t)}.call(${e}, ${n})`}me.isOwnProperty=ac;function F$(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} !== undefined`;return r?(0,be._)`${s} && ${ac(t,e,n)}`:s}me.propertyInData=F$;function lc(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} === undefined`;return r?(0,be.or)(s,(0,be.not)(ac(t,e,n))):s}me.noPropertyInData=lc;function sm(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}me.allSchemaProperties=sm;function H$(t,e){return sm(e).filter(n=>!(0,ic.alwaysValidSchema)(t,e[n]))}me.schemaProperties=H$;function K$({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:s,errorPath:o},it:i},a,l,u){let p=u?(0,be._)`${t}, ${e}, ${r}${s}`:e,g=[[tn.default.instancePath,(0,be.strConcat)(tn.default.instancePath,o)],[tn.default.parentData,i.parentData],[tn.default.parentDataProperty,i.parentDataProperty],[tn.default.rootData,tn.default.rootData]];i.opts.dynamicRef&&g.push([tn.default.dynamicAnchors,tn.default.dynamicAnchors]);let x=(0,be._)`${p}, ${n.object(...g)}`;return l!==be.nil?(0,be._)`${a}.call(${l}, ${x})`:(0,be._)`${a}(${x})`}me.callValidateCode=K$;var V$=(0,be._)`new RegExp`;function G$({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"?V$:(0,M$.useFunc)(t,s)}(${n}, ${r})`})}me.usePattern=G$;function W$(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,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:ic.Type.Num},o),e.if((0,be.not)(o),a)})}}me.validateArray=W$;function J$(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,ic.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((l,u)=>{let p=t.subschema({keyword:r,schemaProp:u,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=J$});var am=M(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.validateKeywordUsage=Tt.validSchemaType=Tt.funcKeywordCode=Tt.macroKeywordCode=void 0;var Ke=te(),Sn=Dt(),Y$=ct(),Z$=Zr();function X$(t,e){let{gen:n,keyword:r,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=im(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:Ke.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Tt.macroKeywordCode=X$;function Q$(t,e){var n;let{gen:r,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;tx(l,e);let u=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,p=im(r,s,u),g=r.let("valid");t.block$data(g,x),t.ok((n=e.valid)!==null&&n!==void 0?n:g);function x(){if(e.errors===!1)T(),e.modifying&&om(t),R(()=>t.error());else{let P=e.async?b():S();e.modifying&&om(t),R(()=>ex(t,P))}}function b(){let P=r.let("ruleErrs",null);return r.try(()=>T((0,Ke._)`await `),N=>r.assign(g,!1).if((0,Ke._)`${N} instanceof ${l.ValidationError}`,()=>r.assign(P,(0,Ke._)`${N}.errors`),()=>r.throw(N))),P}function S(){let P=(0,Ke._)`${p}.errors`;return r.assign(P,null),T(Ke.nil),P}function T(P=e.async?(0,Ke._)`await `:Ke.nil){let N=l.opts.passContext?Sn.default.this:Sn.default.self,D=!("compile"in e&&!a||e.schema===!1);r.assign(g,(0,Ke._)`${P}${(0,Y$.callValidateCode)(t,p,N,D)}`,e.modifying)}function R(P){var N;r.if((0,Ke.not)((N=e.valid)!==null&&N!==void 0?N:g),P)}}Tt.funcKeywordCode=Q$;function om(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Ke._)`${r.parentData}[${r.parentDataProperty}]`))}function ex(t,e){let{gen:n}=t;n.if((0,Ke._)`Array.isArray(${e})`,()=>{n.assign(Sn.default.vErrors,(0,Ke._)`${Sn.default.vErrors} === null ? ${e} : ${Sn.default.vErrors}.concat(${e})`).assign(Sn.default.errors,(0,Ke._)`${Sn.default.vErrors}.length`),(0,Z$.extendErrors)(t)},()=>t.error())}function tx({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function im(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,Ke.stringify)(n)})}function nx(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")}Tt.validSchemaType=nx;function rx({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)}}Tt.validateKeywordUsage=rx});var cm=M(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.extendSubschemaMode=nn.extendSubschemaData=nn.getSubschema=void 0;var Rt=te(),lm=ue();function sx(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,Rt._)`${t.schemaPath}${(0,Rt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Rt._)`${t.schemaPath}${(0,Rt.getProperty)(e)}${(0,Rt.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,lm.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')}nn.getSubschema=sx;function ox(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:u,dataPathArr:p,opts:g}=e,x=a.let("data",(0,Rt._)`${e.data}${(0,Rt.getProperty)(n)}`,!0);l(x),t.errorPath=(0,Rt.str)`${u}${(0,lm.getErrorPath)(n,r,g.jsPropertySyntax)}`,t.parentDataProperty=(0,Rt._)`${n}`,t.dataPathArr=[...p,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Rt.Name?s:a.let("data",s,!0);l(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}nn.extendSubschemaData=ox;function ix(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}nn.extendSubschemaMode=ix});var cc=M((lj,dm)=>{"use strict";dm.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 pm=M((cj,um)=>{"use strict";var rn=um.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(){};Vo(e,r,s,t,"",t)};rn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};rn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};rn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};rn.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 Vo(t,e,n,r,s,o,i,a,l,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,s,o,i,a,l,u);for(var p in r){var g=r[p];if(Array.isArray(g)){if(p in rn.arrayKeywords)for(var x=0;x<g.length;x++)Vo(t,e,n,g[x],s+"/"+p+"/"+x,o,s,p,r,x)}else if(p in rn.propsKeywords){if(g&&typeof g=="object")for(var b in g)Vo(t,e,n,g[b],s+"/"+p+"/"+ax(b),o,s,p,r,b)}else(p in rn.keywords||t.allKeys&&!(p in rn.skipKeywords))&&Vo(t,e,n,g,s+"/"+p,o,s,p,r)}n(r,s,o,i,a,l,u)}}function ax(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Qr=M(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getSchemaRefs=Ze.resolveUrl=Ze.normalizeId=Ze._getFullPath=Ze.getFullPath=Ze.inlineRef=void 0;var lx=ue(),cx=cc(),dx=pm(),ux=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function px(t,e=!0){return typeof t=="boolean"?!0:e===!0?!dc(t):e?hm(t)<=e:!1}Ze.inlineRef=px;var hx=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function dc(t){for(let e in t){if(hx.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(dc)||typeof n=="object"&&dc(n))return!0}return!1}function hm(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!ux.has(n)&&(typeof t[n]=="object"&&(0,lx.eachItem)(t[n],r=>e+=hm(r)),e===1/0))return 1/0}return e}function fm(t,e="",n){n!==!1&&(e=tr(e));let r=t.parse(e);return mm(t,r)}Ze.getFullPath=fm;function mm(t,e){return t.serialize(e).split("#")[0]+"#"}Ze._getFullPath=mm;var fx=/#\/?$/;function tr(t){return t?t.replace(fx,""):""}Ze.normalizeId=tr;function mx(t,e,n){return n=tr(n),t.resolve(e,n)}Ze.resolveUrl=mx;var gx=/^[a-z_][-a-z0-9._]*$/i;function bx(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,s=tr(t[n]||e),o={"":s},i=fm(r,s,!1),a={},l=new Set;return dx(t,{allKeys:!0},(g,x,b,S)=>{if(S===void 0)return;let T=i+x,R=o[S];typeof g[n]=="string"&&(R=P.call(this,g[n])),N.call(this,g.$anchor),N.call(this,g.$dynamicAnchor),o[x]=R;function P(D){let W=this.opts.uriResolver.resolve;if(D=tr(R?W(R,D):D),l.has(D))throw p(D);l.add(D);let K=this.refs[D];return typeof K=="string"&&(K=this.refs[K]),typeof K=="object"?u(g,K.schema,D):D!==tr(T)&&(D[0]==="#"?(u(g,a[D],D),a[D]=g):this.refs[D]=T),D}function N(D){if(typeof D=="string"){if(!gx.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(g,x,b){if(x!==void 0&&!cx(g,x))throw p(b)}function p(g){return new Error(`reference "${g}" resolves to more than one schema`)}}Ze.getSchemaRefs=bx});var ns=M(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.getData=sn.KeywordCxt=sn.validateFunctionCode=void 0;var vm=Jf(),gm=Xr(),pc=nc(),Go=Xr(),yx=nm(),ts=am(),uc=cm(),B=te(),X=Dt(),wx=Qr(),Ut=ue(),es=Zr();function vx(t){if(_m(t)&&($m(t),Sm(t))){_x(t);return}km(t,()=>(0,vm.topBoolOrEmptySchema)(t))}sn.validateFunctionCode=vx;function km({gen:t,validateName:e,schema:n,schemaEnv:r,opts:s},o){s.code.es5?t.func(e,(0,B._)`${X.default.data}, ${X.default.valCxt}`,r.$async,()=>{t.code((0,B._)`"use strict"; ${bm(n,s)}`),Sx(t,s),t.code(o)}):t.func(e,(0,B._)`${X.default.data}, ${kx(s)}`,r.$async,()=>t.code(bm(n,s)).code(o))}function kx(t){return(0,B._)`{${X.default.instancePath}="", ${X.default.parentData}, ${X.default.parentDataProperty}, ${X.default.rootData}=${X.default.data}${t.dynamicRef?(0,B._)`, ${X.default.dynamicAnchors}={}`:B.nil}}={}`}function Sx(t,e){t.if(X.default.valCxt,()=>{t.var(X.default.instancePath,(0,B._)`${X.default.valCxt}.${X.default.instancePath}`),t.var(X.default.parentData,(0,B._)`${X.default.valCxt}.${X.default.parentData}`),t.var(X.default.parentDataProperty,(0,B._)`${X.default.valCxt}.${X.default.parentDataProperty}`),t.var(X.default.rootData,(0,B._)`${X.default.valCxt}.${X.default.rootData}`),e.dynamicRef&&t.var(X.default.dynamicAnchors,(0,B._)`${X.default.valCxt}.${X.default.dynamicAnchors}`)},()=>{t.var(X.default.instancePath,(0,B._)`""`),t.var(X.default.parentData,(0,B._)`undefined`),t.var(X.default.parentDataProperty,(0,B._)`undefined`),t.var(X.default.rootData,X.default.data),e.dynamicRef&&t.var(X.default.dynamicAnchors,(0,B._)`{}`)})}function _x(t){let{schema:e,opts:n,gen:r}=t;km(t,()=>{n.$comment&&e.$comment&&Tm(t),Ex(t),r.let(X.default.vErrors,null),r.let(X.default.errors,0),n.unevaluated&&$x(t),xm(t),Ix(t)})}function $x(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,B._)`${n}.evaluated`),e.if((0,B._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,B._)`${t.evaluated}.props`,(0,B._)`undefined`)),e.if((0,B._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,B._)`${t.evaluated}.items`,(0,B._)`undefined`))}function bm(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,B._)`/*# sourceURL=${n} */`:B.nil}function xx(t,e){if(_m(t)&&($m(t),Sm(t))){Tx(t,e);return}(0,vm.boolOrEmptySchema)(t,e)}function Sm({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 _m(t){return typeof t.schema!="boolean"}function Tx(t,e){let{schema:n,gen:r,opts:s}=t;s.$comment&&n.$comment&&Tm(t),Px(t),Ax(t);let o=r.const("_errs",X.default.errors);xm(t,o),r.var(e,(0,B._)`${o} === ${X.default.errors}`)}function $m(t){(0,Ut.checkUnknownRules)(t),Rx(t)}function xm(t,e){if(t.opts.jtd)return ym(t,[],!1,e);let n=(0,gm.getSchemaTypes)(t.schema),r=(0,gm.coerceAndCheckDataType)(t,n);ym(t,n,!r,e)}function Rx(t){let{schema:e,errSchemaPath:n,opts:r,self:s}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Ut.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function Ex(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Ut.checkStrictMode)(t,"default is ignored in the schema root")}function Px(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,wx.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Ax(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Tm({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:s}){let o=n.$comment;if(s.$comment===!0)t.code((0,B._)`${X.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,B.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,B._)`${X.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function Ix(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=t;n.$async?e.if((0,B._)`${X.default.errors} === 0`,()=>e.return(X.default.data),()=>e.throw((0,B._)`new ${s}(${X.default.vErrors})`)):(e.assign((0,B._)`${r}.errors`,X.default.vErrors),o.unevaluated&&Cx(t),e.return((0,B._)`${X.default.errors} === 0`))}function Cx({gen:t,evaluated:e,props:n,items:r}){n instanceof B.Name&&t.assign((0,B._)`${e}.props`,n),r instanceof B.Name&&t.assign((0,B._)`${e}.items`,r)}function ym(t,e,n,r){let{gen:s,schema:o,data:i,allErrors:a,opts:l,self:u}=t,{RULES:p}=u;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,Ut.schemaHasRulesButRef)(o,p))){s.block(()=>Em(t,"$ref",p.all.$ref.definition));return}l.jtd||Ox(t,e),s.block(()=>{for(let x of p.rules)g(x);g(p.post)});function g(x){(0,pc.shouldUseGroup)(o,x)&&(x.type?(s.if((0,Go.checkDataType)(x.type,i,l.strictNumbers)),wm(t,x),e.length===1&&e[0]===x.type&&n&&(s.else(),(0,Go.reportTypeError)(t)),s.endIf()):wm(t,x),a||s.if((0,B._)`${X.default.errors} === ${r||0}`))}}function wm(t,e){let{gen:n,schema:r,opts:{useDefaults:s}}=t;s&&(0,yx.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,pc.shouldUseRule)(r,o)&&Em(t,o.keyword,o.definition,e.type)})}function Ox(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Nx(t,e),t.opts.allowUnionTypes||Lx(t,e),jx(t,t.dataTypes))}function Nx(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Rm(t.dataTypes,n)||hc(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),Ux(t,e)}}function Lx(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&hc(t,"use allowUnionTypes to allow union type keyword")}function jx(t,e){let n=t.self.RULES.all;for(let r in n){let s=n[r];if(typeof s=="object"&&(0,pc.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>Dx(e,i))&&hc(t,`missing type "${o.join(",")}" for keyword "${r}"`)}}}function Dx(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Rm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Ux(t,e){let n=[];for(let r of t.dataTypes)Rm(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function hc(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Ut.checkStrictMode)(t,e,t.opts.strictTypes)}var Wo=class{constructor(e,n,r){if((0,ts.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,Ut.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",Pm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ts.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",X.default.errors))}result(e,n,r){this.failResult((0,B.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,B.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,B._)`${n} !== undefined && (${(0,B.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?es.reportExtraError:es.reportError)(this,this.def.error,n)}$dataError(){(0,es.reportError)(this,this.def.$dataError||es.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,es.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=B.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=B.nil,n=B.nil){if(!this.$data)return;let{gen:r,schemaCode:s,schemaType:o,def:i}=this;r.if((0,B.or)((0,B._)`${s} === undefined`,n)),e!==B.nil&&r.assign(e,!0),(o.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==B.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:s,it:o}=this;return(0,B.or)(i(),a());function i(){if(r.length){if(!(n instanceof B.Name))throw new Error("ajv implementation error");let l=Array.isArray(r)?r:[r];return(0,B._)`${(0,Go.checkDataTypes)(l,n,o.opts.strictNumbers,Go.DataType.Wrong)}`}return B.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,B._)`!${l}(${n})`}return B.nil}}subschema(e,n){let r=(0,uc.getSubschema)(this.it,e);(0,uc.extendSubschemaData)(r,this.it,e),(0,uc.extendSubschemaMode)(r,e);let s={...this.it,...r,items:void 0,props:void 0};return xx(s,n),s}mergeEvaluated(e,n){let{it:r,gen:s}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Ut.mergeEvaluated.props(s,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Ut.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,B.Name)),!0}};sn.KeywordCxt=Wo;function Em(t,e,n,r){let s=new Wo(t,n,e);"code"in n?n.code(s,r):s.$data&&n.validate?(0,ts.funcKeywordCode)(s,n):"macro"in n?(0,ts.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,ts.funcKeywordCode)(s,n)}var Mx=/^\/(?:[^~]|~0|~1)*$/,qx=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Pm(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let s,o;if(t==="")return X.default.rootData;if(t[0]==="/"){if(!Mx.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=X.default.rootData}else{let u=qx.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+u[1];if(s=u[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 u of a)u&&(o=(0,B._)`${o}${(0,B.getProperty)((0,Ut.unescapeJsonPointer)(u))}`,i=(0,B._)`${i} && ${o}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}sn.getData=Pm});var Jo=M(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var fc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};mc.default=fc});var rs=M(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var gc=Qr(),bc=class extends Error{constructor(e,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,gc.resolveUrl)(e,n,r),this.missingSchema=(0,gc.normalizeId)((0,gc.getFullPath)(e,this.missingRef))}};yc.default=bc});var Zo=M(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.resolveSchema=dt.getCompilingSchema=dt.resolveRef=dt.compileSchema=dt.SchemaEnv=void 0;var yt=te(),zx=Jo(),_n=Dt(),wt=Qr(),Am=ue(),Bx=ns(),nr=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,wt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};dt.SchemaEnv=nr;function vc(t){let e=Im.call(this,t);if(e)return e;let n=(0,wt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new yt.CodeGen(this.scope,{es5:r,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:zx.default,code:(0,yt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:_n.default.data,parentData:_n.default.parentData,parentDataProperty:_n.default.parentDataProperty,dataNames:[_n.default.data],dataPathArr:[yt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,yt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:yt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,yt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,Bx.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let g=i.toString();p=`${i.scopeRefs(_n.default.scope)}return ${g}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let b=new Function(`${_n.default.self}`,`${_n.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:b}),b.errors=null,b.schema=t.schema,b.schemaEnv=t,t.$async&&(b.$async=!0),this.opts.code.source===!0&&(b.source={validateName:l,validateCode:g,scopeValues:i._values}),this.opts.unevaluated){let{props:S,items:T}=u;b.evaluated={props:S instanceof yt.Name?void 0:S,items:T instanceof yt.Name?void 0:T,dynamicProps:S instanceof yt.Name,dynamicItems:T instanceof yt.Name},b.source&&(b.source.evaluated=(0,yt.stringify)(b.evaluated))}return t.validate=b,t}catch(g){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),g}finally{this._compilations.delete(t)}}dt.compileSchema=vc;function Fx(t,e,n){var r;n=(0,wt.resolveUrl)(this.opts.uriResolver,e,n);let s=t.refs[n];if(s)return s;let o=Vx.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 nr({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=Hx.call(this,o)}dt.resolveRef=Fx;function Hx(t){return(0,wt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:vc.call(this,t)}function Im(t){for(let e of this._compilations)if(Kx(e,t))return e}dt.getCompilingSchema=Im;function Kx(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Vx(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Yo.call(this,t,e)}function Yo(t,e){let n=this.opts.uriResolver.parse(e),r=(0,wt._getFullPath)(this.opts.uriResolver,n),s=(0,wt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===s)return wc.call(this,n,t);let o=(0,wt.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Yo.call(this,t,i);return typeof a?.schema!="object"?void 0:wc.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||vc.call(this,i),o===(0,wt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(s=(0,wt.resolveUrl)(this.opts.uriResolver,s,u)),new nr({schema:a,schemaId:l,root:t,baseId:s})}return wc.call(this,n,i)}}dt.resolveSchema=Yo;var Gx=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function wc(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,Am.unescapeFragment)(a)];if(l===void 0)return;n=l;let u=typeof n=="object"&&n[this.opts.schemaId];!Gx.has(a)&&u&&(e=(0,wt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,Am.schemaHasRulesButRef)(n,this.RULES)){let a=(0,wt.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=Yo.call(this,r,a)}let{schemaId:i}=this.opts;if(o=o||new nr({schema:n,schemaId:i,root:r,baseId:e}),o.schema!==o.root.schema)return o}});var Cm=M((mj,Wx)=>{Wx.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 _c=M((gj,Um)=>{"use strict";var Jx=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Nm=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),kc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Lm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Yx=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Sc(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 Zx=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Om(t){return t.length=0,!0}function Xx(t,e,n){if(t.length){let r=Sc(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function Qx(t){let e=0,n={error:!1,address:"",zone:""},r=[],s=[],o=!1,i=!1,a=Xx;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){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(u==="%"){if(!a(s,r,n))break;a=Om}else{s.push(u);continue}}return s.length&&(a===Om?n.zone=s.join(""):i?r.push(s.join("")):r.push(Sc(s))),n.address=r.join(""),n}function jm(t){if(eT(t,":")<2)return{host:t,isIPV6:!1};let e=Qx(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 eT(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function tT(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 nT={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},rT=/[@/?#:]/g,sT=/[@/?#]/g;function Dm(t,e){let n=e?sT:rT;return n.lastIndex=0,t.replace(n,r=>nT[r])}function oT(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(kc(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&Lm(i)?n+=i:n+="%"+o,r+=2;continue}}n+=t[r]}return n}function iT(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(kc(r)){let s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&Lm(o)?e+=o:e+="%"+s,n+=2;continue}}Yx(t[n])?e+=t[n]:e+=escape(t[n])}return e}function aT(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(kc(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function lT(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Nm(n)){let r=jm(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=Dm(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}Um.exports={nonSimpleDomain:Zx,recomposeAuthority:lT,reescapeHostDelimiters:Dm,normalizePercentEncoding:oT,normalizePathEncoding:iT,escapePreservingEscapes:aT,removeDotSegments:tT,isIPv4:Nm,isUUID:Jx,normalizeIPv6:jm,stringArrayToHexStripped:Sc}});var Fm=M((bj,Bm)=>{"use strict";var{isUUID:cT}=_c(),dT=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,uT=["http","https","ws","wss","urn","urn:uuid"];function pT(t){return uT.indexOf(t)!==-1}function $c(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 Mm(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function qm(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 hT(t){return t.secure=$c(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function fT(t){if((t.port===($c(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 mT(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(dT);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=xc(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function gT(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=xc(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 bT(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!cT(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function yT(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var zm={scheme:"http",domainHost:!0,parse:Mm,serialize:qm},wT={scheme:"https",domainHost:zm.domainHost,parse:Mm,serialize:qm},Xo={scheme:"ws",domainHost:!0,parse:hT,serialize:fT},vT={scheme:"wss",domainHost:Xo.domainHost,parse:Xo.parse,serialize:Xo.serialize},kT={scheme:"urn",parse:mT,serialize:gT,skipNormalize:!0},ST={scheme:"urn:uuid",parse:bT,serialize:yT,skipNormalize:!0},Qo={http:zm,https:wT,ws:Xo,wss:vT,urn:kT,"urn:uuid":ST};Object.setPrototypeOf(Qo,null);function xc(t){return t&&(Qo[t]||Qo[t.toLowerCase()])||void 0}Bm.exports={wsIsSecure:$c,SCHEMES:Qo,isValidSchemeName:pT,getSchemeHandler:xc}});var Wm=M((yj,ni)=>{"use strict";var{normalizeIPv6:_T,removeDotSegments:ss,recomposeAuthority:$T,normalizePercentEncoding:xT,normalizePathEncoding:TT,escapePreservingEscapes:RT,reescapeHostDelimiters:ET,isIPv4:PT,nonSimpleDomain:AT}=_c(),{SCHEMES:IT,getSchemeHandler:Km}=Fm();function CT(t,e){return typeof t=="string"?t=MT(t,e):typeof t=="object"&&(t=ti($n(t,e),e)),t}function OT(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=ei(t,r),{parsed:i,malformedAuthorityOrPort:a}=ei(e,r);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=Vm(s,i,r,!0);return r.skipEscape=!0,$n(l,r)}function Vm(t,e,n,r){let s={};return r||(t=ti($n(t,n),n),e=ti($n(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=ss(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=ss(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=ss(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=ss(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 NT(t,e,n){let r=Hm(t,n),s=Hm(e,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function $n(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=Km(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=xT(n.path):(n.path=RT(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");let i=$T(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=ss(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 LT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,jT=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,DT=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function UT(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 ei(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(jT);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(DT);if(a!==null){let u=a[1],p=u.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):u.length!==p.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",s=!0))}let l=t.match(LT);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 u=UT(r,l);if(u!==void 0&&(r.error=r.error||u,s=!0),r.host)if(PT(r.host)===!1){let x=_T(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 p=Km(n.scheme||r.scheme);if(!n.unicodeSupport&&(!p||!p.unicodeSupport)&&r.host&&(n.domainHost||p&&p.domainHost)&&o===!1&&AT(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(g){r.error=r.error||"Host's domain name can not be converted to ASCII: "+g}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=ET(unescape(r.host),o))),r.path&&(r.path=TT(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 ti(t,e){return ei(t,e).parsed}function MT(t,e){return Gm(t,e).normalized}function Gm(t,e){let{parsed:n,malformedAuthorityOrPort:r}=ei(t,e);return{normalized:r?t:$n(n,e),malformedAuthorityOrPort:r}}function Hm(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=Gm(t,e);return r?void 0:n}if(typeof t=="object")return $n(t,e)}var Tc={SCHEMES:IT,normalize:CT,resolve:OT,resolveComponent:Vm,equal:NT,serialize:$n,parse:ti};ni.exports=Tc;ni.exports.default=Tc;ni.exports.fastUri=Tc});var Ym=M(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var Jm=Wm();Jm.code='require("ajv/dist/runtime/uri").default';Rc.default=Jm});var sg=M(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.CodeGen=Oe.Name=Oe.nil=Oe.stringify=Oe.str=Oe._=Oe.KeywordCxt=void 0;var qT=ns();Object.defineProperty(Oe,"KeywordCxt",{enumerable:!0,get:function(){return qT.KeywordCxt}});var rr=te();Object.defineProperty(Oe,"_",{enumerable:!0,get:function(){return rr._}});Object.defineProperty(Oe,"str",{enumerable:!0,get:function(){return rr.str}});Object.defineProperty(Oe,"stringify",{enumerable:!0,get:function(){return rr.stringify}});Object.defineProperty(Oe,"nil",{enumerable:!0,get:function(){return rr.nil}});Object.defineProperty(Oe,"Name",{enumerable:!0,get:function(){return rr.Name}});Object.defineProperty(Oe,"CodeGen",{enumerable:!0,get:function(){return rr.CodeGen}});var zT=Jo(),tg=rs(),BT=tc(),os=Zo(),FT=te(),is=Qr(),ri=Xr(),Pc=ue(),Zm=Cm(),HT=Ym(),ng=(t,e)=>new RegExp(t,e);ng.code="new RegExp";var KT=["removeAdditional","useDefaults","coerceTypes"],VT=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),GT={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."},WT={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Xm=200;function JT(t){var e,n,r,s,o,i,a,l,u,p,g,x,b,S,T,R,P,N,D,W,K,Pe,Le,qt,zt;let cn=t.strict,Bt=(e=t.code)===null||e===void 0?void 0:e.optimize,St=Bt===!0||Bt===void 0?1:Bt||0,vs=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:ng,Pi=(s=t.uriResolver)!==null&&s!==void 0?s:HT.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:cn)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:cn)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:cn)!==null&&p!==void 0?p:"log",strictTuples:(x=(g=t.strictTuples)!==null&&g!==void 0?g:cn)!==null&&x!==void 0?x:"log",strictRequired:(S=(b=t.strictRequired)!==null&&b!==void 0?b:cn)!==null&&S!==void 0?S:!1,code:t.code?{...t.code,optimize:St,regExp:vs}:{optimize:St,regExp:vs},loopRequired:(T=t.loopRequired)!==null&&T!==void 0?T:Xm,loopEnum:(R=t.loopEnum)!==null&&R!==void 0?R:Xm,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(N=t.messages)!==null&&N!==void 0?N:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(W=t.schemaId)!==null&&W!==void 0?W:"$id",addUsedSchema:(K=t.addUsedSchema)!==null&&K!==void 0?K:!0,validateSchema:(Pe=t.validateSchema)!==null&&Pe!==void 0?Pe:!0,validateFormats:(Le=t.validateFormats)!==null&&Le!==void 0?Le:!0,unicodeRegExp:(qt=t.unicodeRegExp)!==null&&qt!==void 0?qt:!0,int32range:(zt=t.int32range)!==null&&zt!==void 0?zt:!0,uriResolver:Pi}}var as=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,...JT(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new FT.ValueScope({scope:{},prefixes:VT,es5:n,lines:r}),this.logger=tR(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,BT.getRules)(),Qm.call(this,GT,e,"NOT SUPPORTED"),Qm.call(this,WT,e,"DEPRECATED","warn"),this._metaOpts=QT.call(this),e.formats&&ZT.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&XT.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),YT.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,s=Zm;r==="id"&&(s={...Zm},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,g){await o.call(this,p.$schema);let x=this._addSchema(p,g);return x.validate||i.call(this,x)}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(g){if(!(g instanceof tg.default))throw g;return a.call(this,g),await l.call(this,g.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:g}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${g} cannot be resolved`)}async function l(p){let g=await u.call(this,p);this.refs[p]||await o.call(this,g.$schema),this.refs[p]||this.addSchema(g,p,n)}async function u(p){let g=this._loading[p];if(g)return g;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,is.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=eg.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,s=new os.SchemaEnv({schema:{},schemaId:r});if(n=os.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=eg.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,is.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(rR.call(this,r,n),!n)return(0,Pc.eachItem)(r,o=>Ec.call(this,o)),this;oR.call(this,n);let s={...n,type:(0,ri.getJSONTypes)(n.type),schemaType:(0,ri.getJSONTypes)(n.schemaType)};return(0,Pc.eachItem)(r,s.type.length===0?o=>Ec.call(this,o,s):o=>s.type.forEach(i=>Ec.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:u}=l.definition,p=i[a];u&&p&&(i[a]=rg(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,is.normalizeId)(i||r);let u=is.getSchemaRefs.call(this,e,r);return l=new os.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),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):os.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{os.compileSchema.call(this,e)}finally{this.opts=n}}};as.ValidationError=zT.default;as.MissingRefError=tg.default;Oe.default=as;function Qm(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 eg(t){return t=(0,is.normalizeId)(t),this.schemas[t]||this.refs[t]}function YT(){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 ZT(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function XT(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 QT(){let t={...this.opts};for(let e of KT)delete t[e];return t}var eR={log(){},warn(){},error(){}};function tR(t){if(t===!1)return eR;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 nR=/^[a-z_$][a-z0-9_$:-]*$/i;function rR(t,e){let{RULES:n}=this;if((0,Pc.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!nR.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 Ec(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,ri.getJSONTypes)(e.type),schemaType:(0,ri.getJSONTypes)(e.schemaType)}};e.before?sR.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 sR(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 oR(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=rg(e)),t.validateSchema=this.compile(e,!0))}var iR={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rg(t){return{anyOf:[t,iR]}}});var og=M(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var aR={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ac.default=aR});var cg=M(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.callRef=xn.getValidate=void 0;var lR=rs(),ig=ct(),Xe=te(),sr=Dt(),ag=Zo(),si=ue(),cR={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:u}=o;if((n==="#"||n==="#/")&&s===u.baseId)return g();let p=ag.resolveRef.call(l,u,s,n);if(p===void 0)throw new lR.default(r.opts.uriResolver,s,n);if(p instanceof ag.SchemaEnv)return x(p);return b(p);function g(){if(o===u)return oi(t,i,o,o.$async);let S=e.scopeValue("root",{ref:u});return oi(t,(0,Xe._)`${S}.validate`,u,u.$async)}function x(S){let T=lg(t,S);oi(t,T,S,S.$async)}function b(S){let T=e.scopeValue("schema",a.code.source===!0?{ref:S,code:(0,Xe.stringify)(S)}:{ref:S}),R=e.name("valid"),P=t.subschema({schema:S,dataTypes:[],schemaPath:Xe.nil,topSchemaRef:T,errSchemaPath:n},R);t.mergeEvaluated(P),t.ok(R)}}};function lg(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Xe._)`${n.scopeValue("wrapper",{ref:e})}.validate`}xn.getValidate=lg;function oi(t,e,n,r){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,u=l.passContext?sr.default.this:Xe.nil;r?p():g();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let S=s.let("valid");s.try(()=>{s.code((0,Xe._)`await ${(0,ig.callValidateCode)(t,e,u)}`),b(e),i||s.assign(S,!0)},T=>{s.if((0,Xe._)`!(${T} instanceof ${o.ValidationError})`,()=>s.throw(T)),x(T),i||s.assign(S,!1)}),t.ok(S)}function g(){t.result((0,ig.callValidateCode)(t,e,u),()=>b(e),()=>x(e))}function x(S){let T=(0,Xe._)`${S}.errors`;s.assign(sr.default.vErrors,(0,Xe._)`${sr.default.vErrors} === null ? ${T} : ${sr.default.vErrors}.concat(${T})`),s.assign(sr.default.errors,(0,Xe._)`${sr.default.vErrors}.length`)}function b(S){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=si.mergeEvaluated.props(s,R.props,o.props));else{let P=s.var("props",(0,Xe._)`${S}.evaluated.props`);o.props=si.mergeEvaluated.props(s,P,o.props,Xe.Name)}if(o.items!==!0)if(R&&!R.dynamicItems)R.items!==void 0&&(o.items=si.mergeEvaluated.items(s,R.items,o.items));else{let P=s.var("items",(0,Xe._)`${S}.evaluated.items`);o.items=si.mergeEvaluated.items(s,P,o.items,Xe.Name)}}}xn.callRef=oi;xn.default=cR});var dg=M(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var dR=og(),uR=cg(),pR=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",dR.default,uR.default];Ic.default=pR});var ug=M(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var ii=te(),on=ii.operators,ai={maximum:{okStr:"<=",ok:on.LTE,fail:on.GT},minimum:{okStr:">=",ok:on.GTE,fail:on.LT},exclusiveMaximum:{okStr:"<",ok:on.LT,fail:on.GTE},exclusiveMinimum:{okStr:">",ok:on.GT,fail:on.LTE}},hR={message:({keyword:t,schemaCode:e})=>(0,ii.str)`must be ${ai[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ii._)`{comparison: ${ai[t].okStr}, limit: ${e}}`},fR={keyword:Object.keys(ai),type:"number",schemaType:"number",$data:!0,error:hR,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,ii._)`${n} ${ai[e].fail} ${r} || isNaN(${n})`)}};Cc.default=fR});var pg=M(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var ls=te(),mR={message:({schemaCode:t})=>(0,ls.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ls._)`{multipleOf: ${t}}`},gR={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:mR,code(t){let{gen:e,data:n,schemaCode:r,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,ls._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,ls._)`${i} !== parseInt(${i})`;t.fail$data((0,ls._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Oc.default=gR});var fg=M(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});function hg(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}Nc.default=hg;hg.code='require("ajv/dist/runtime/ucs2length").default'});var mg=M(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var Tn=te(),bR=ue(),yR=fg(),wR={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Tn.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Tn._)`{limit: ${t}}`},vR={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:wR,code(t){let{keyword:e,data:n,schemaCode:r,it:s}=t,o=e==="maxLength"?Tn.operators.GT:Tn.operators.LT,i=s.opts.unicode===!1?(0,Tn._)`${n}.length`:(0,Tn._)`${(0,bR.useFunc)(t.gen,yR.default)}(${n})`;t.fail$data((0,Tn._)`${i} ${o} ${r}`)}};Lc.default=vR});var gg=M(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var kR=ct(),SR=ue(),or=te(),_R={message:({schemaCode:t})=>(0,or.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,or._)`{pattern: ${t}}`},$R={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_R,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,u=l.code==="new RegExp"?(0,or._)`new RegExp`:(0,SR.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,or._)`${u}(${o}, ${a}).test(${n})`),()=>e.assign(p,!1)),t.fail$data((0,or._)`!${p}`)}else{let l=(0,kR.usePattern)(t,s);t.fail$data((0,or._)`!${l}.test(${n})`)}}};jc.default=$R});var bg=M(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var cs=te(),xR={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,cs.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,cs._)`{limit: ${t}}`},TR={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:xR,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxProperties"?cs.operators.GT:cs.operators.LT;t.fail$data((0,cs._)`Object.keys(${n}).length ${s} ${r}`)}};Dc.default=TR});var yg=M(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var ds=ct(),us=te(),RR=ue(),ER={message:({params:{missingProperty:t}})=>(0,us.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,us._)`{missingProperty: ${t}}`},PR={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ER,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?u():p(),a.strictRequired){let b=t.parentSchema.properties,{definedProperties:S}=t.it;for(let T of n)if(b?.[T]===void 0&&!S.has(T)){let R=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${T}" is not defined at "${R}" (strictRequired)`;(0,RR.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(us.nil,g);else for(let b of n)(0,ds.checkReportMissingProp)(t,b)}function p(){let b=e.let("missing");if(l||o){let S=e.let("valid",!0);t.block$data(S,()=>x(b,S)),t.ok(S)}else e.if((0,ds.checkMissingProp)(t,n,b)),(0,ds.reportMissingProp)(t,b),e.else()}function g(){e.forOf("prop",r,b=>{t.setParams({missingProperty:b}),e.if((0,ds.noPropertyInData)(e,s,b,a.ownProperties),()=>t.error())})}function x(b,S){t.setParams({missingProperty:b}),e.forOf(b,r,()=>{e.assign(S,(0,ds.propertyInData)(e,s,b,a.ownProperties)),e.if((0,us.not)(S),()=>{t.error(),e.break()})},us.nil)}}};Uc.default=PR});var wg=M(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var ps=te(),AR={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,ps.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,ps._)`{limit: ${t}}`},IR={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:AR,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxItems"?ps.operators.GT:ps.operators.LT;t.fail$data((0,ps._)`${n}.length ${s} ${r}`)}};Mc.default=IR});var li=M(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var vg=cc();vg.code='require("ajv/dist/runtime/equal").default';qc.default=vg});var kg=M(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var zc=Xr(),Ne=te(),CR=ue(),OR=li(),NR={message:({params:{i:t,j:e}})=>(0,Ne.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ne._)`{i: ${t}, j: ${e}}`},LR={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:NR,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"),u=o.items?(0,zc.getSchemaTypes)(o.items):[];t.block$data(l,p,(0,Ne._)`${i} === false`),t.ok(l);function p(){let S=e.let("i",(0,Ne._)`${n}.length`),T=e.let("j");t.setParams({i:S,j:T}),e.assign(l,!0),e.if((0,Ne._)`${S} > 1`,()=>(g()?x:b)(S,T))}function g(){return u.length>0&&!u.some(S=>S==="object"||S==="array")}function x(S,T){let R=e.name("item"),P=(0,zc.checkDataTypes)(u,R,a.opts.strictNumbers,zc.DataType.Wrong),N=e.const("indices",(0,Ne._)`{}`);e.for((0,Ne._)`;${S}--;`,()=>{e.let(R,(0,Ne._)`${n}[${S}]`),e.if(P,(0,Ne._)`continue`),u.length>1&&e.if((0,Ne._)`typeof ${R} == "string"`,(0,Ne._)`${R} += "_"`),e.if((0,Ne._)`typeof ${N}[${R}] == "number"`,()=>{e.assign(T,(0,Ne._)`${N}[${R}]`),t.error(),e.assign(l,!1).break()}).code((0,Ne._)`${N}[${R}] = ${S}`)})}function b(S,T){let R=(0,CR.useFunc)(e,OR.default),P=e.name("outer");e.label(P).for((0,Ne._)`;${S}--;`,()=>e.for((0,Ne._)`${T} = ${S}; ${T}--;`,()=>e.if((0,Ne._)`${R}(${n}[${S}], ${n}[${T}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Bc.default=LR});var Sg=M(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var Fc=te(),jR=ue(),DR=li(),UR={message:"must be equal to constant",params:({schemaCode:t})=>(0,Fc._)`{allowedValue: ${t}}`},MR={keyword:"const",$data:!0,error:UR,code(t){let{gen:e,data:n,$data:r,schemaCode:s,schema:o}=t;r||o&&typeof o=="object"?t.fail$data((0,Fc._)`!${(0,jR.useFunc)(e,DR.default)}(${n}, ${s})`):t.fail((0,Fc._)`${o} !== ${n}`)}};Hc.default=MR});var _g=M(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var hs=te(),qR=ue(),zR=li(),BR={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,hs._)`{allowedValues: ${t}}`},FR={keyword:"enum",schemaType:"array",$data:!0,error:BR,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,u=()=>l??(l=(0,qR.useFunc)(e,zR.default)),p;if(a||r)p=e.let("valid"),t.block$data(p,g);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let b=e.const("vSchema",o);p=(0,hs.or)(...s.map((S,T)=>x(b,T)))}t.pass(p);function g(){e.assign(p,!1),e.forOf("v",o,b=>e.if((0,hs._)`${u()}(${n}, ${b})`,()=>e.assign(p,!0).break()))}function x(b,S){let T=s[S];return typeof T=="object"&&T!==null?(0,hs._)`${u()}(${n}, ${b}[${S}])`:(0,hs._)`${n} === ${T}`}}};Kc.default=FR});var $g=M(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var HR=ug(),KR=pg(),VR=mg(),GR=gg(),WR=bg(),JR=yg(),YR=wg(),ZR=kg(),XR=Sg(),QR=_g(),eE=[HR.default,KR.default,VR.default,GR.default,WR.default,JR.default,YR.default,ZR.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},XR.default,QR.default];Vc.default=eE});var Wc=M(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.validateAdditionalItems=void 0;var Rn=te(),Gc=ue(),tE={message:({params:{len:t}})=>(0,Rn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Rn._)`{limit: ${t}}`},nE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:tE,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Gc.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}xg(t,r)}};function xg(t,e){let{gen:n,schema:r,data:s,keyword:o,it:i}=t;i.items=!0;let a=n.const("len",(0,Rn._)`${s}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Rn._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Gc.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Rn._)`${a} <= ${e.length}`);n.if((0,Rn.not)(u),()=>l(u)),t.ok(u)}function l(u){n.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:Gc.Type.Num},u),i.allErrors||n.if((0,Rn.not)(u),()=>n.break())})}}fs.validateAdditionalItems=xg;fs.default=nE});var Jc=M(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.validateTuple=void 0;var Tg=te(),ci=ue(),rE=ct(),sE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Rg(t,"additionalItems",e);n.items=!0,!(0,ci.alwaysValidSchema)(n,e)&&t.ok((0,rE.validateArray)(t))}};function Rg(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=ci.mergeEvaluated.items(r,n.length,a.items));let l=r.name("valid"),u=r.const("len",(0,Tg._)`${o}.length`);n.forEach((g,x)=>{(0,ci.alwaysValidSchema)(a,g)||(r.if((0,Tg._)`${u} > ${x}`,()=>t.subschema({keyword:i,schemaProp:x,dataProp:x},l)),t.ok(l))});function p(g){let{opts:x,errSchemaPath:b}=a,S=n.length,T=S===g.minItems&&(S===g.maxItems||g[e]===!1);if(x.strictTuples&&!T){let R=`"${i}" is ${S}-tuple, but minItems or maxItems/${e} are not specified or different at path "${b}"`;(0,ci.checkStrictMode)(a,R,x.strictTuples)}}}ms.validateTuple=Rg;ms.default=sE});var Eg=M(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var oE=Jc(),iE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,oE.validateTuple)(t,"items")};Yc.default=iE});var Ag=M(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Pg=te(),aE=ue(),lE=ct(),cE=Wc(),dE={message:({params:{len:t}})=>(0,Pg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Pg._)`{limit: ${t}}`},uE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:dE,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:s}=n;r.items=!0,!(0,aE.alwaysValidSchema)(r,e)&&(s?(0,cE.validateAdditionalItems)(t,s):t.ok((0,lE.validateArray)(t)))}};Zc.default=uE});var Ig=M(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var ut=te(),di=ue(),pE={message:({params:{min:t,max:e}})=>e===void 0?(0,ut.str)`must contain at least ${t} valid item(s)`:(0,ut.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ut._)`{minContains: ${t}}`:(0,ut._)`{minContains: ${t}, maxContains: ${e}}`},hE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:pE,code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t,i,a,{minContains:l,maxContains:u}=r;o.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=e.const("len",(0,ut._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,di.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,di.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,di.alwaysValidSchema)(o,n)){let T=(0,ut._)`${p} >= ${i}`;a!==void 0&&(T=(0,ut._)`${T} && ${p} <= ${a}`),t.pass(T);return}o.items=!0;let g=e.name("valid");a===void 0&&i===1?b(g,()=>e.if(g,()=>e.break())):i===0?(e.let(g,!0),a!==void 0&&e.if((0,ut._)`${s}.length > 0`,x)):(e.let(g,!1),x()),t.result(g,()=>t.reset());function x(){let T=e.name("_valid"),R=e.let("count",0);b(T,()=>e.if(T,()=>S(R)))}function b(T,R){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:di.Type.Num,compositeRule:!0},T),R()})}function S(T){e.code((0,ut._)`${T}++`),a===void 0?e.if((0,ut._)`${T} >= ${i}`,()=>e.assign(g,!0).break()):(e.if((0,ut._)`${T} > ${a}`,()=>e.assign(g,!1).break()),i===1?e.assign(g,!0):e.if((0,ut._)`${T} >= ${i}`,()=>e.assign(g,!0)))}}};Xc.default=hE});var Ng=M(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.validateSchemaDeps=Et.validatePropertyDeps=Et.error=void 0;var Qc=te(),fE=ue(),gs=ct();Et.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Qc.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Qc._)`{property: ${t},
|
|
1871
1964
|
missingProperty: ${r},
|
|
1872
1965
|
depsCount: ${e},
|
|
1873
|
-
deps: ${n}}`};var KR={keyword:"dependencies",type:"object",schemaType:"object",error:$t.error,code(t){let[e,n]=VR(t);yg(t,e),wg(t,n)}};function VR({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 yg(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,hs.propertyInData)(n,r,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?n.if(l,()=>{for(let u of a)(0,hs.checkReportMissingProp)(t,u)}):(n.if((0,Wc._)`${l} && (${(0,hs.checkMissingProp)(t,a,o)})`),(0,hs.reportMissingProp)(t,o),n.else())}}$t.validatePropertyDeps=yg;function wg(t,e=t.schema){let{gen:n,data:r,keyword:s,it:o}=t,i=n.name("valid");for(let a in e)(0,HR.alwaysValidSchema)(o,e[a])||(n.if((0,hs.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=wg;$t.default=KR});var Sg=M(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var kg=ee(),GR=ue(),WR={message:"property name must be valid",params:({params:t})=>(0,kg._)`{propertyName: ${t.propertyName}}`},JR={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:WR,code(t){let{gen:e,schema:n,data:r,it:s}=t;if((0,GR.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,kg.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Jc.default=JR});var Zc=M(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var ii=at(),bt=ee(),YR=Nt(),ai=ue(),ZR={message:"must NOT have additional properties",params:({params:t})=>(0,bt._)`{additionalProperty: ${t.additionalProperty}}`},XR={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:ZR,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,ai.alwaysValidSchema)(i,n))return;let u=(0,ii.allSchemaProperties)(r.properties),p=(0,ii.allSchemaProperties)(r.patternProperties);g(),t.ok((0,bt._)`${o} === ${YR.default.errors}`);function g(){e.forIn("key",s,E=>{!u.length&&!p.length?S(E):e.if($(E),()=>S(E))})}function $(E){let P;if(u.length>8){let C=(0,ai.schemaRefOrVal)(i,r.properties,"properties");P=(0,ii.isOwnProperty)(e,C,E)}else u.length?P=(0,bt.or)(...u.map(C=>(0,bt._)`${E} === ${C}`)):P=bt.nil;return p.length&&(P=(0,bt.or)(P,...p.map(C=>(0,bt._)`${(0,ii.usePattern)(t,C)}.test(${E})`))),(0,bt.not)(P)}function v(E){e.code((0,bt._)`delete ${s}[${E}]`)}function S(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,ai.alwaysValidSchema)(i,n)){let P=e.name("valid");l.removeAdditional==="failing"?(T(E,P,!1),e.if((0,bt.not)(P),()=>{t.reset(),v(E)})):(T(E,P),a||e.if((0,bt.not)(P),()=>e.break()))}}function T(E,P,C){let D={keyword:"additionalProperties",dataProp:E,dataPropType:ai.Type.Str};C===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};Yc.default=XR});var xg=M(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var QR=Qr(),_g=at(),Xc=ue(),$g=Zc(),eE={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&&$g.default.code(new QR.KeywordCxt(o,$g.default,"additionalProperties"));let i=(0,_g.allSchemaProperties)(n);for(let g of i)o.definedProperties.add(g);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Xc.mergeEvaluated.props(e,(0,Xc.toHash)(i),o.props));let a=i.filter(g=>!(0,Xc.alwaysValidSchema)(o,n[g]));if(a.length===0)return;let l=e.name("valid");for(let g of a)u(g)?p(g):(e.if((0,_g.propertyInData)(e,s,g,o.opts.ownProperties)),p(g),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(g),t.ok(l);function u(g){return o.opts.useDefaults&&!o.compositeRule&&n[g].default!==void 0}function p(g){t.subschema({keyword:"properties",schemaProp:g,dataProp:g},l)}}};Qc.default=eE});var Pg=M(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var Tg=at(),li=ee(),Rg=ue(),Eg=ue(),tE={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,Tg.allSchemaProperties)(n),l=a.filter(T=>(0,Rg.alwaysValidSchema)(o,n[T]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,p=e.name("valid");o.props!==!0&&!(o.props instanceof li.Name)&&(o.props=(0,Eg.evaluatedPropsToName)(e,o.props));let{props:g}=o;$();function $(){for(let T of a)u&&v(T),o.allErrors?S(T):(e.var(p,!0),S(T),e.if(p))}function v(T){for(let E in u)new RegExp(T).test(E)&&(0,Rg.checkStrictMode)(o,`property ${E} matches pattern ${T} (use allowMatchingProperties)`)}function S(T){e.forIn("key",r,E=>{e.if((0,li._)`${(0,Tg.usePattern)(t,T)}.test(${E})`,()=>{let P=l.includes(T);P||t.subschema({keyword:"patternProperties",schemaProp:T,dataProp:E,dataPropType:Eg.Type.Str},p),o.opts.unevaluated&&g!==!0?e.assign((0,li._)`${g}[${E}]`,!0):!P&&!o.allErrors&&e.if((0,li.not)(p),()=>e.break())})})}}};ed.default=tE});var Ag=M(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var nE=ue(),rE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,nE.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"}};td.default=rE});var Ig=M(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var sE=at(),oE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:sE.validateUnion,error:{message:"must match a schema in anyOf"}};nd.default=oE});var Cg=M(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var ci=ee(),iE=ue(),aE={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ci._)`{passingSchemas: ${t.passing}}`},lE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:aE,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(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((p,g)=>{let $;(0,iE.alwaysValidSchema)(s,p)?e.var(l,!0):$=t.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},l),g>0&&e.if((0,ci._)`${l} && ${i}`).assign(i,!1).assign(a,(0,ci._)`[${a}, ${g}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,g),$&&t.mergeEvaluated($,ci.Name)})})}}};rd.default=lE});var Og=M(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var cE=ue(),dE={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,cE.alwaysValidSchema)(r,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};sd.default=dE});var jg=M(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var di=ee(),Lg=ue(),uE={message:({params:t})=>(0,di.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,di._)`{failingKeyword: ${t.ifClause}}`},pE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:uE,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Lg.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let s=Ng(r,"then"),o=Ng(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,u("then",p),u("else",p))}else s?e.if(a,u("then")):e.if((0,di.not)(a),u("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 u(p,g){return()=>{let $=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated($,i),g?e.assign(g,(0,di._)`${p}`):t.setParams({ifClause:p})}}}};function Ng(t,e){let n=t.schema[e];return n!==void 0&&!(0,Lg.alwaysValidSchema)(t,n)}od.default=pE});var Dg=M(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var hE=ue(),fE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,hE.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};id.default=fE});var Ug=M(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var mE=Fc(),gE=fg(),bE=Hc(),yE=gg(),wE=bg(),vE=vg(),kE=Sg(),SE=Zc(),_E=xg(),$E=Pg(),xE=Ag(),TE=Ig(),RE=Cg(),EE=Og(),PE=jg(),AE=Dg();function IE(t=!1){let e=[xE.default,TE.default,RE.default,EE.default,PE.default,AE.default,kE.default,SE.default,vE.default,_E.default,$E.default];return t?e.push(gE.default,yE.default):e.push(mE.default,bE.default),e.push(wE.default),e}ad.default=IE});var Mg=M(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var ke=ee(),CE={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},OE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:CE,code(t,e){let{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:g}=a;if(!l.validateFormats)return;s?$():v();function $(){let S=n.scopeValue("formats",{ref:g.formats,code:l.code.formats}),T=n.const("fDef",(0,ke._)`${S}[${i}]`),E=n.let("fType"),P=n.let("format");n.if((0,ke._)`typeof ${T} == "object" && !(${T} instanceof RegExp)`,()=>n.assign(E,(0,ke._)`${T}.type || "string"`).assign(P,(0,ke._)`${T}.validate`),()=>n.assign(E,(0,ke._)`"string"`).assign(P,T)),t.fail$data((0,ke.or)(C(),D()));function C(){return l.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${P}`}function D(){let se=p.$async?(0,ke._)`(${T}.async ? await ${P}(${r}) : ${P}(${r}))`:(0,ke._)`${P}(${r})`,G=(0,ke._)`(typeof ${P} == "function" ? ${se} : ${P}.test(${r}))`;return(0,ke._)`${P} && ${P} !== true && ${E} === ${e} && !${G}`}}function v(){let S=g.formats[o];if(!S){C();return}if(S===!0)return;let[T,E,P]=D(S);T===e&&t.pass(se());function C(){if(l.strictSchema===!1){g.logger.warn(G());return}throw new Error(G());function G(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function D(G){let Fe=G instanceof RegExp?(0,ke.regexpCode)(G):l.code.formats?(0,ke._)`${l.code.formats}${(0,ke.getProperty)(o)}`:void 0,He=n.scopeValue("formats",{key:o,ref:G,code:Fe});return typeof G=="object"&&!(G instanceof RegExp)?[G.type||"string",G.validate,(0,ke._)`${He}.validate`]:["string",G,He]}function se(){if(typeof S=="object"&&!(S instanceof RegExp)&&S.async){if(!p.$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})`}}}};ld.default=OE});var zg=M(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var NE=Mg(),LE=[NE.default];cd.default=LE});var qg=M(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.contentVocabulary=nr.metadataVocabulary=void 0;nr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];nr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Fg=M(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var jE=Ym(),DE=dg(),UE=Ug(),ME=zg(),Bg=qg(),zE=[jE.default,DE.default,(0,UE.default)(),ME.default,Bg.metadataVocabulary,Bg.contentVocabulary];dd.default=zE});var Kg=M(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.DiscrError=void 0;var Hg;(function(t){t.Tag="tag",t.Mapping="mapping"})(Hg||(ui.DiscrError=Hg={}))});var Gg=M(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var rr=ee(),ud=Kg(),Vg=Vo(),qE=es(),BE=ue(),FE={message:({params:{discrError:t,tagName:e}})=>t===ud.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,rr._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},HE={keyword:"discriminator",type:"object",schemaType:"object",error:FE,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),u=e.const("tag",(0,rr._)`${n}${(0,rr.getProperty)(a)}`);e.if((0,rr._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:ud.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let v=$();e.if(!1);for(let S in v)e.elseIf((0,rr._)`${u} === ${S}`),e.assign(l,g(v[S]));e.else(),t.error(!1,{discrError:ud.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function g(v){let S=e.name("valid"),T=t.subschema({keyword:"oneOf",schemaProp:v},S);return t.mergeEvaluated(T,rr.Name),S}function $(){var v;let S={},T=P(s),E=!0;for(let se=0;se<i.length;se++){let G=i[se];if(G?.$ref&&!(0,BE.schemaHasRulesButRef)(G,o.self.RULES)){let He=G.$ref;if(G=Vg.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,He),G instanceof Vg.SchemaEnv&&(G=G.schema),G===void 0)throw new qE.default(o.opts.uriResolver,o.baseId,He)}let Fe=(v=G?.properties)===null||v===void 0?void 0:v[a];if(typeof Fe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);E=E&&(T||P(G)),C(Fe,se)}if(!E)throw new Error(`discriminator: "${a}" must be required`);return S;function P({required:se}){return Array.isArray(se)&&se.includes(a)}function C(se,G){if(se.const)D(se.const,G);else if(se.enum)for(let Fe of se.enum)D(Fe,G);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(se,G){if(typeof se!="string"||se in S)throw new Error(`discriminator: "${a}" values must be unique strings`);S[se]=G}}}};pd.default=HE});var Wg=M((Tj,KE)=>{KE.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 fd=M((ye,hd)=>{"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 VE=Hm(),GE=Fg(),WE=Gg(),Jg=Wg(),JE=["/properties"],pi="http://json-schema.org/draft-07/schema",sr=class extends VE.default{_addVocabularies(){super._addVocabularies(),GE.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(WE.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Jg,JE):Jg;this.addMetaSchema(e,pi,!1),this.refs["http://json-schema.org/schema"]=pi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(pi)?pi:void 0)}};ye.Ajv=sr;hd.exports=ye=sr;hd.exports.Ajv=sr;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=sr;var YE=Qr();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return YE.KeywordCxt}});var or=ee();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return or._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return or.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return or.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return or.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return or.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return or.CodeGen}});var ZE=Ho();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return ZE.default}});var XE=es();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return XE.default}})});var rb=M(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.formatNames=Tt.fastFormats=Tt.fullFormats=void 0;function xt(t,e){return{validate:t,compare:e}}Tt.fullFormats={date:xt(Qg,yd),time:xt(gd(!0),wd),"date-time":xt(Yg(!0),tb),"iso-time":xt(gd(),eb),"iso-date-time":xt(Yg(),nb),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:s0,"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:u0,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:o0,int32:{type:"number",validate:l0},int64:{type:"number",validate:c0},float:{type:"number",validate:Xg},double:{type:"number",validate:Xg},password:!0,binary:!0};Tt.fastFormats={...Tt.fullFormats,date:xt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,yd),time:xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wd),"date-time":xt(/^\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,tb),"iso-time":xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,eb),"iso-date-time":xt(/^\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,nb),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};Tt.formatNames=Object.keys(Tt.fullFormats);function QE(t){return t%4===0&&(t%100!==0||t%400===0)}var e0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,t0=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Qg(t){let e=e0.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&&QE(n)?29:t0[r])}function yd(t,e){if(t&&e)return t>e?1:t<e?-1:0}var md=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function gd(t){return function(n){let r=md.exec(n);if(!r)return!1;let s=+r[1],o=+r[2],i=+r[3],a=r[4],l=r[5]==="-"?-1:1,u=+(r[6]||0),p=+(r[7]||0);if(u>23||p>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let g=o-p*l,$=s-u*l-(g<0?1:0);return($===23||$===-1)&&(g===59||g===-1)&&i<61}}function wd(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 eb(t,e){if(!(t&&e))return;let n=md.exec(t),r=md.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 bd=/t|\s/i;function Yg(t){let e=gd(t);return function(r){let s=r.split(bd);return s.length===2&&Qg(s[0])&&e(s[1])}}function tb(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function nb(t,e){if(!(t&&e))return;let[n,r]=t.split(bd),[s,o]=e.split(bd),i=yd(n,s);if(i!==void 0)return i||wd(r,o)}var n0=/\/|:/,r0=/^(?:[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 s0(t){return n0.test(t)&&r0.test(t)}var Zg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function o0(t){return Zg.lastIndex=0,Zg.test(t)}var i0=-(2**31),a0=2**31-1;function l0(t){return Number.isInteger(t)&&t<=a0&&t>=i0}function c0(t){return Number.isInteger(t)}function Xg(){return!0}var d0=/[^\\]\\Z/;function u0(t){if(d0.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var sb=M(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.formatLimitDefinition=void 0;var p0=fd(),yt=ee(),nn=yt.operators,hi={formatMaximum:{okStr:"<=",ok:nn.LTE,fail:nn.GT},formatMinimum:{okStr:">=",ok:nn.GTE,fail:nn.LT},formatExclusiveMaximum:{okStr:"<",ok:nn.LT,fail:nn.GTE},formatExclusiveMinimum:{okStr:">",ok:nn.GT,fail:nn.LTE}},h0={message:({keyword:t,schemaCode:e})=>(0,yt.str)`should be ${hi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,yt._)`{comparison: ${hi[t].okStr}, limit: ${e}}`};ir.formatLimitDefinition={keyword:Object.keys(hi),type:"string",schemaType:"string",$data:!0,error:h0,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 p0.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let $=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),v=e.const("fmt",(0,yt._)`${$}[${l.schemaCode}]`);t.fail$data((0,yt.or)((0,yt._)`typeof ${v} != "object"`,(0,yt._)`${v} instanceof RegExp`,(0,yt._)`typeof ${v}.compare != "function"`,g(v)))}function p(){let $=l.schema,v=a.formats[$];if(!v||v===!0)return;if(typeof v!="object"||v instanceof RegExp||typeof v.compare!="function")throw new Error(`"${s}": format "${$}" does not define "compare" function`);let S=e.scopeValue("formats",{key:$,ref:v,code:i.code.formats?(0,yt._)`${i.code.formats}${(0,yt.getProperty)($)}`:void 0});t.fail$data(g(S))}function g($){return(0,yt._)`${$}.compare(${n}, ${r}) ${hi[s].fail} 0`}},dependencies:["format"]};var f0=t=>(t.addKeyword(ir.formatLimitDefinition),t);ir.default=f0});var lb=M((fs,ab)=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});var ar=rb(),m0=sb(),vd=ee(),ob=new vd.Name("fullFormats"),g0=new vd.Name("fastFormats"),kd=(t,e={keywords:!0})=>{if(Array.isArray(e))return ib(t,e,ar.fullFormats,ob),t;let[n,r]=e.mode==="fast"?[ar.fastFormats,g0]:[ar.fullFormats,ob],s=e.formats||ar.formatNames;return ib(t,s,n,r),e.keywords&&(0,m0.default)(t),t};kd.get=(t,e="full")=>{let r=(e==="fast"?ar.fastFormats:ar.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function ib(t,e,n,r){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,vd._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}ab.exports=fs=kd;Object.defineProperty(fs,"__esModule",{value:!0});fs.default=kd});function b0(){let t=new cb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,db.default)(t),t}var cb,db,fi,ub=j(()=>{cb=jd(fd(),1),db=jd(lb(),1);fi=class{constructor(e){this._ajv=e??b0()}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 mi,pb=j(()=>{Hn();mi=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]:[],u=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(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let p=new Set(l.filter($=>$.type==="tool_use").map($=>$.id)),g=new Set(o.filter($=>$.type==="tool_result").map($=>$.toolUseId));if(p.size!==g.size||![...p].every($=>g.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},Dr,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},Fn,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 hb(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 fb(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 mb=j(()=>{});var gi,gb=j(()=>{wf();Hn();ub();Rr();pb();mb();gi=class extends Io{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(jr.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 fi,this.setRequestHandler(La,r=>this._oninitialize(r)),this.setNotificationHandler(ja,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Fa,async(r,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=jr.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new mi(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=yf(this._capabilities,e)}setRequestHandler(e,n){let s=Kt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=Un(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(l,u)=>{let p=Ht(Bn,l);if(!p.success){let S=p.error instanceof Error?p.error.message:String(p.error);throw new z(K.InvalidParams,`Invalid tools/call request: ${S}`)}let{params:g}=p.data,$=await Promise.resolve(n(l,u));if(g.task){let S=Ht(zn,$);if(!S.success){let T=S.error instanceof Error?S.error.message:String(S.error);throw new z(K.InvalidParams,`Invalid task creation result: ${T}`)}return S.data}let v=Ht(wo,$);if(!v.success){let S=v.error instanceof Error?v.error.message:String(v.error);throw new z(K.InvalidParams,`Invalid tools/call result: ${S}`)}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){fb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&hb(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:gh.includes(n)?n:Aa,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"},no)}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(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(u=>u.type==="tool_use");if(o){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(a.filter(g=>g.type==="tool_use").map(g=>g.id)),p=new Set(s.filter(g=>g.type==="tool_result").map(g=>g.toolUseId));if(u.size!==p.size||![...u].every(g=>p.has(g)))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},Ha,n):this.request({method:"sampling/createMessage",params:e},Dr,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},Fn,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},Fn,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(K.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(K.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 Sd(t){return!!t&&typeof t=="object"&&yb in t}function wb(t){return t[yb]?.complete}var yb,bb,vb=j(()=>{yb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(bb||(bb={}))});var kb=j(()=>{});function w0(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"),!y0.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 v0(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 _d(t){let e=w0(t);return v0(t,e.warnings),e.isValid}var y0,Sb=j(()=>{y0=/^[A-Za-z0-9._-]{1,128}$/});var bi,_b=j(()=>{bi=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 k0}from"zod";function Tb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Rb(t){return"_def"in t||"_zod"in t||Tb(t)}function $d(t){return typeof t!="object"||t===null||Rb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Tb)}function $b(t){if(t){if($d(t))return un(t);if(!Rb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function _0(t){let e=Kt(t);return e?Object.entries(e).map(([n,r])=>{let s=fh(r),o=mh(r);return{name:n,description:s,required:!o}}):[]}function rn(t){let n=Kt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Un(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function xb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var yi,S0,ms,Eb=j(()=>{gb();Rr();El();Hn();vb();kb();Sb();_b();yi=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 gi(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new bi(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(rn(yo)),this.server.assertCanSetRequestHandler(rn(Bn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(yo,()=>({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=Dn(n.inputSchema);return s?xl(s,{strictUnions:!0,pipeStrategy:"input"}):S0})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let s=Dn(n.outputSchema);s&&(r.outputSchema=xl(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Bn,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new z(K.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new z(K.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(K.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new z(K.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===K.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=Dn(e.inputSchema)??e.inputSchema,i=await Zs(o,n);if(!i.success){let a="error"in i?i.error:"Unknown error",l=Xs(a);throw new z(K.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(K.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let s=Dn(e.outputSchema),o=await Zs(s,n.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Xs(i);throw new z(K.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,u=a.task,p=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise($=>setTimeout($,p));let g=await r.taskStore.getTask(l);if(!g)throw new z(K.InternalError,`Task ${l} not found during polling`);u=g}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(rn(vo)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(vo,async e=>{switch(e.params.ref.type){case"ref/prompt":return Ch(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Oh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(K.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(K.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new z(K.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return ms;let o=Kt(r.argsSchema)?.[e.params.argument.name];if(!Sd(o))return ms;let i=wb(o);if(!i)return ms;let a=await i(e.params.argument.value,e.params.context);return xb(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 ms;throw new z(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ms;let o=await s(e.params.argument.value,e.params.context);return xb(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(rn(ho)),this.server.assertCanSetRequestHandler(rn(fo)),this.server.assertCanSetRequestHandler(rn(mo)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ho,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(fo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(mo,async(e,n)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new z(K.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(K.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(rn(go)),this.server.assertCanSetRequestHandler(rn(bo)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(go,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?_0(n.argsSchema):void 0}))})),this.server.setRequestHandler(bo,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new z(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new z(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=Dn(r.argsSchema),o=await Zs(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",u=Xs(l);throw new z(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}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:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,s,o){let i={title:n,description:r,argsSchema:s===void 0?void 0:un(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=un(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 u=l instanceof k0?l._def?.innerType:l;return Sd(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,s,o,i,a,l,u){_d(e);let p={title:n,description:r,inputSchema:$b(s),outputSchema:$b(o),annotations:i,execution:a,_meta:l,handler:u,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:g=>{typeof g.name<"u"&&g.name!==e&&(typeof g.name=="string"&&_d(g.name),delete this._registeredTools[e],g.name&&(this._registeredTools[g.name]=p)),typeof g.title<"u"&&(p.title=g.title),typeof g.description<"u"&&(p.description=g.description),typeof g.paramsSchema<"u"&&(p.inputSchema=un(g.paramsSchema)),typeof g.outputSchema<"u"&&(p.outputSchema=un(g.outputSchema)),typeof g.callback<"u"&&(p.handler=g.callback),typeof g.annotations<"u"&&(p.annotations=g.annotations),typeof g._meta<"u"&&(p._meta=g._meta),typeof g.enabled<"u"&&(p.enabled=g.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($d(l))s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!$d(n[0])&&(i=n.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(u=>typeof u=="object"&&u!==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:u}=n;return this._createRegisteredTool(e,s,o,i,a,l,{taskSupport:"forbidden"},u,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()}},S0={type:"object",properties:{}};ms={completion:{values:[],hasMore:!1}}});function x0(t){return $h.parse(JSON.parse(t))}function Pb(t){return JSON.stringify(t)+`
|
|
1874
|
-
`}var
|
|
1875
|
-
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
1966
|
+
deps: ${n}}`};var mE={keyword:"dependencies",type:"object",schemaType:"object",error:Et.error,code(t){let[e,n]=gE(t);Cg(t,e),Og(t,n)}};function gE({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 Cg(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,gs.propertyInData)(n,r,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?n.if(l,()=>{for(let u of a)(0,gs.checkReportMissingProp)(t,u)}):(n.if((0,Qc._)`${l} && (${(0,gs.checkMissingProp)(t,a,o)})`),(0,gs.reportMissingProp)(t,o),n.else())}}Et.validatePropertyDeps=Cg;function Og(t,e=t.schema){let{gen:n,data:r,keyword:s,it:o}=t,i=n.name("valid");for(let a in e)(0,fE.alwaysValidSchema)(o,e[a])||(n.if((0,gs.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))}Et.validateSchemaDeps=Og;Et.default=mE});var jg=M(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var Lg=te(),bE=ue(),yE={message:"property name must be valid",params:({params:t})=>(0,Lg._)`{propertyName: ${t.propertyName}}`},wE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:yE,code(t){let{gen:e,schema:n,data:r,it:s}=t;if((0,bE.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,Lg.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};ed.default=wE});var nd=M(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var ui=ct(),vt=te(),vE=Dt(),pi=ue(),kE={message:"must NOT have additional properties",params:({params:t})=>(0,vt._)`{additionalProperty: ${t.additionalProperty}}`},SE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:kE,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,pi.alwaysValidSchema)(i,n))return;let u=(0,ui.allSchemaProperties)(r.properties),p=(0,ui.allSchemaProperties)(r.patternProperties);g(),t.ok((0,vt._)`${o} === ${vE.default.errors}`);function g(){e.forIn("key",s,R=>{!u.length&&!p.length?S(R):e.if(x(R),()=>S(R))})}function x(R){let P;if(u.length>8){let N=(0,pi.schemaRefOrVal)(i,r.properties,"properties");P=(0,ui.isOwnProperty)(e,N,R)}else u.length?P=(0,vt.or)(...u.map(N=>(0,vt._)`${R} === ${N}`)):P=vt.nil;return p.length&&(P=(0,vt.or)(P,...p.map(N=>(0,vt._)`${(0,ui.usePattern)(t,N)}.test(${R})`))),(0,vt.not)(P)}function b(R){e.code((0,vt._)`delete ${s}[${R}]`)}function S(R){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){b(R);return}if(n===!1){t.setParams({additionalProperty:R}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,pi.alwaysValidSchema)(i,n)){let P=e.name("valid");l.removeAdditional==="failing"?(T(R,P,!1),e.if((0,vt.not)(P),()=>{t.reset(),b(R)})):(T(R,P),a||e.if((0,vt.not)(P),()=>e.break()))}}function T(R,P,N){let D={keyword:"additionalProperties",dataProp:R,dataPropType:pi.Type.Str};N===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};td.default=SE});var Mg=M(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var _E=ns(),Dg=ct(),rd=ue(),Ug=nd(),$E={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&&Ug.default.code(new _E.KeywordCxt(o,Ug.default,"additionalProperties"));let i=(0,Dg.allSchemaProperties)(n);for(let g of i)o.definedProperties.add(g);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=rd.mergeEvaluated.props(e,(0,rd.toHash)(i),o.props));let a=i.filter(g=>!(0,rd.alwaysValidSchema)(o,n[g]));if(a.length===0)return;let l=e.name("valid");for(let g of a)u(g)?p(g):(e.if((0,Dg.propertyInData)(e,s,g,o.opts.ownProperties)),p(g),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(g),t.ok(l);function u(g){return o.opts.useDefaults&&!o.compositeRule&&n[g].default!==void 0}function p(g){t.subschema({keyword:"properties",schemaProp:g,dataProp:g},l)}}};sd.default=$E});var Fg=M(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var qg=ct(),hi=te(),zg=ue(),Bg=ue(),xE={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,qg.allSchemaProperties)(n),l=a.filter(T=>(0,zg.alwaysValidSchema)(o,n[T]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,p=e.name("valid");o.props!==!0&&!(o.props instanceof hi.Name)&&(o.props=(0,Bg.evaluatedPropsToName)(e,o.props));let{props:g}=o;x();function x(){for(let T of a)u&&b(T),o.allErrors?S(T):(e.var(p,!0),S(T),e.if(p))}function b(T){for(let R in u)new RegExp(T).test(R)&&(0,zg.checkStrictMode)(o,`property ${R} matches pattern ${T} (use allowMatchingProperties)`)}function S(T){e.forIn("key",r,R=>{e.if((0,hi._)`${(0,qg.usePattern)(t,T)}.test(${R})`,()=>{let P=l.includes(T);P||t.subschema({keyword:"patternProperties",schemaProp:T,dataProp:R,dataPropType:Bg.Type.Str},p),o.opts.unevaluated&&g!==!0?e.assign((0,hi._)`${g}[${R}]`,!0):!P&&!o.allErrors&&e.if((0,hi.not)(p),()=>e.break())})})}}};od.default=xE});var Hg=M(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var TE=ue(),RE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,TE.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"}};id.default=RE});var Kg=M(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var EE=ct(),PE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:EE.validateUnion,error:{message:"must match a schema in anyOf"}};ad.default=PE});var Vg=M(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var fi=te(),AE=ue(),IE={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,fi._)`{passingSchemas: ${t.passing}}`},CE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:IE,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(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((p,g)=>{let x;(0,AE.alwaysValidSchema)(s,p)?e.var(l,!0):x=t.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},l),g>0&&e.if((0,fi._)`${l} && ${i}`).assign(i,!1).assign(a,(0,fi._)`[${a}, ${g}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,g),x&&t.mergeEvaluated(x,fi.Name)})})}}};ld.default=CE});var Gg=M(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var OE=ue(),NE={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,OE.alwaysValidSchema)(r,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};cd.default=NE});var Yg=M(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var mi=te(),Jg=ue(),LE={message:({params:t})=>(0,mi.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,mi._)`{failingKeyword: ${t.ifClause}}`},jE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:LE,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Jg.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let s=Wg(r,"then"),o=Wg(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,u("then",p),u("else",p))}else s?e.if(a,u("then")):e.if((0,mi.not)(a),u("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 u(p,g){return()=>{let x=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(x,i),g?e.assign(g,(0,mi._)`${p}`):t.setParams({ifClause:p})}}}};function Wg(t,e){let n=t.schema[e];return n!==void 0&&!(0,Jg.alwaysValidSchema)(t,n)}dd.default=jE});var Zg=M(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var DE=ue(),UE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,DE.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};ud.default=UE});var Xg=M(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var ME=Wc(),qE=Eg(),zE=Jc(),BE=Ag(),FE=Ig(),HE=Ng(),KE=jg(),VE=nd(),GE=Mg(),WE=Fg(),JE=Hg(),YE=Kg(),ZE=Vg(),XE=Gg(),QE=Yg(),e0=Zg();function t0(t=!1){let e=[JE.default,YE.default,ZE.default,XE.default,QE.default,e0.default,KE.default,VE.default,HE.default,GE.default,WE.default];return t?e.push(qE.default,BE.default):e.push(ME.default,zE.default),e.push(FE.default),e}pd.default=t0});var Qg=M(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var _e=te(),n0={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},r0={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:n0,code(t,e){let{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:g}=a;if(!l.validateFormats)return;s?x():b();function x(){let S=n.scopeValue("formats",{ref:g.formats,code:l.code.formats}),T=n.const("fDef",(0,_e._)`${S}[${i}]`),R=n.let("fType"),P=n.let("format");n.if((0,_e._)`typeof ${T} == "object" && !(${T} instanceof RegExp)`,()=>n.assign(R,(0,_e._)`${T}.type || "string"`).assign(P,(0,_e._)`${T}.validate`),()=>n.assign(R,(0,_e._)`"string"`).assign(P,T)),t.fail$data((0,_e.or)(N(),D()));function N(){return l.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${P}`}function D(){let W=p.$async?(0,_e._)`(${T}.async ? await ${P}(${r}) : ${P}(${r}))`:(0,_e._)`${P}(${r})`,K=(0,_e._)`(typeof ${P} == "function" ? ${W} : ${P}.test(${r}))`;return(0,_e._)`${P} && ${P} !== true && ${R} === ${e} && !${K}`}}function b(){let S=g.formats[o];if(!S){N();return}if(S===!0)return;let[T,R,P]=D(S);T===e&&t.pass(W());function N(){if(l.strictSchema===!1){g.logger.warn(K());return}throw new Error(K());function K(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function D(K){let Pe=K instanceof RegExp?(0,_e.regexpCode)(K):l.code.formats?(0,_e._)`${l.code.formats}${(0,_e.getProperty)(o)}`:void 0,Le=n.scopeValue("formats",{key:o,ref:K,code:Pe});return typeof K=="object"&&!(K instanceof RegExp)?[K.type||"string",K.validate,(0,_e._)`${Le}.validate`]:["string",K,Le]}function W(){if(typeof S=="object"&&!(S instanceof RegExp)&&S.async){if(!p.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${P}(${r})`}return typeof R=="function"?(0,_e._)`${P}(${r})`:(0,_e._)`${P}.test(${r})`}}}};hd.default=r0});var eb=M(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var s0=Qg(),o0=[s0.default];fd.default=o0});var tb=M(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.contentVocabulary=ir.metadataVocabulary=void 0;ir.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ir.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rb=M(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var i0=dg(),a0=$g(),l0=Xg(),c0=eb(),nb=tb(),d0=[i0.default,a0.default,(0,l0.default)(),c0.default,nb.metadataVocabulary,nb.contentVocabulary];md.default=d0});var ob=M(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.DiscrError=void 0;var sb;(function(t){t.Tag="tag",t.Mapping="mapping"})(sb||(gi.DiscrError=sb={}))});var ab=M(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var ar=te(),gd=ob(),ib=Zo(),u0=rs(),p0=ue(),h0={message:({params:{discrError:t,tagName:e}})=>t===gd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,ar._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},f0={keyword:"discriminator",type:"object",schemaType:"object",error:h0,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),u=e.const("tag",(0,ar._)`${n}${(0,ar.getProperty)(a)}`);e.if((0,ar._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:gd.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let b=x();e.if(!1);for(let S in b)e.elseIf((0,ar._)`${u} === ${S}`),e.assign(l,g(b[S]));e.else(),t.error(!1,{discrError:gd.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function g(b){let S=e.name("valid"),T=t.subschema({keyword:"oneOf",schemaProp:b},S);return t.mergeEvaluated(T,ar.Name),S}function x(){var b;let S={},T=P(s),R=!0;for(let W=0;W<i.length;W++){let K=i[W];if(K?.$ref&&!(0,p0.schemaHasRulesButRef)(K,o.self.RULES)){let Le=K.$ref;if(K=ib.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,Le),K instanceof ib.SchemaEnv&&(K=K.schema),K===void 0)throw new u0.default(o.opts.uriResolver,o.baseId,Le)}let Pe=(b=K?.properties)===null||b===void 0?void 0:b[a];if(typeof Pe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);R=R&&(T||P(K)),N(Pe,W)}if(!R)throw new Error(`discriminator: "${a}" must be required`);return S;function P({required:W}){return Array.isArray(W)&&W.includes(a)}function N(W,K){if(W.const)D(W.const,K);else if(W.enum)for(let Pe of W.enum)D(Pe,K);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(W,K){if(typeof W!="string"||W in S)throw new Error(`discriminator: "${a}" values must be unique strings`);S[W]=K}}}};bd.default=f0});var lb=M((i1,m0)=>{m0.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 wd=M((ye,yd)=>{"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 g0=sg(),b0=rb(),y0=ab(),cb=lb(),w0=["/properties"],bi="http://json-schema.org/draft-07/schema",lr=class extends g0.default{_addVocabularies(){super._addVocabularies(),b0.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(y0.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(cb,w0):cb;this.addMetaSchema(e,bi,!1),this.refs["http://json-schema.org/schema"]=bi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bi)?bi:void 0)}};ye.Ajv=lr;yd.exports=ye=lr;yd.exports.Ajv=lr;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=lr;var v0=ns();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return v0.KeywordCxt}});var cr=te();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return cr._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return cr.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return cr.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return cr.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return cr.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return cr.CodeGen}});var k0=Jo();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return k0.default}});var S0=rs();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return S0.default}})});var bb=M(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.formatNames=At.fastFormats=At.fullFormats=void 0;function Pt(t,e){return{validate:t,compare:e}}At.fullFormats={date:Pt(hb,_d),time:Pt(kd(!0),$d),"date-time":Pt(db(!0),mb),"iso-time":Pt(kd(),fb),"iso-date-time":Pt(db(),gb),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:E0,"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:L0,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:P0,int32:{type:"number",validate:C0},int64:{type:"number",validate:O0},float:{type:"number",validate:pb},double:{type:"number",validate:pb},password:!0,binary:!0};At.fastFormats={...At.fullFormats,date:Pt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,_d),time:Pt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,$d),"date-time":Pt(/^\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,mb),"iso-time":Pt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,fb),"iso-date-time":Pt(/^\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,gb),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};At.formatNames=Object.keys(At.fullFormats);function _0(t){return t%4===0&&(t%100!==0||t%400===0)}var $0=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,x0=[0,31,28,31,30,31,30,31,31,30,31,30,31];function hb(t){let e=$0.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&&_0(n)?29:x0[r])}function _d(t,e){if(t&&e)return t>e?1:t<e?-1:0}var vd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function kd(t){return function(n){let r=vd.exec(n);if(!r)return!1;let s=+r[1],o=+r[2],i=+r[3],a=r[4],l=r[5]==="-"?-1:1,u=+(r[6]||0),p=+(r[7]||0);if(u>23||p>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let g=o-p*l,x=s-u*l-(g<0?1:0);return(x===23||x===-1)&&(g===59||g===-1)&&i<61}}function $d(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 fb(t,e){if(!(t&&e))return;let n=vd.exec(t),r=vd.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 Sd=/t|\s/i;function db(t){let e=kd(t);return function(r){let s=r.split(Sd);return s.length===2&&hb(s[0])&&e(s[1])}}function mb(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function gb(t,e){if(!(t&&e))return;let[n,r]=t.split(Sd),[s,o]=e.split(Sd),i=_d(n,s);if(i!==void 0)return i||$d(r,o)}var T0=/\/|:/,R0=/^(?:[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 E0(t){return T0.test(t)&&R0.test(t)}var ub=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function P0(t){return ub.lastIndex=0,ub.test(t)}var A0=-(2**31),I0=2**31-1;function C0(t){return Number.isInteger(t)&&t<=I0&&t>=A0}function O0(t){return Number.isInteger(t)}function pb(){return!0}var N0=/[^\\]\\Z/;function L0(t){if(N0.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var yb=M(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.formatLimitDefinition=void 0;var j0=wd(),kt=te(),an=kt.operators,yi={formatMaximum:{okStr:"<=",ok:an.LTE,fail:an.GT},formatMinimum:{okStr:">=",ok:an.GTE,fail:an.LT},formatExclusiveMaximum:{okStr:"<",ok:an.LT,fail:an.GTE},formatExclusiveMinimum:{okStr:">",ok:an.GT,fail:an.LTE}},D0={message:({keyword:t,schemaCode:e})=>(0,kt.str)`should be ${yi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kt._)`{comparison: ${yi[t].okStr}, limit: ${e}}`};dr.formatLimitDefinition={keyword:Object.keys(yi),type:"string",schemaType:"string",$data:!0,error:D0,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 j0.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let x=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),b=e.const("fmt",(0,kt._)`${x}[${l.schemaCode}]`);t.fail$data((0,kt.or)((0,kt._)`typeof ${b} != "object"`,(0,kt._)`${b} instanceof RegExp`,(0,kt._)`typeof ${b}.compare != "function"`,g(b)))}function p(){let x=l.schema,b=a.formats[x];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${s}": format "${x}" does not define "compare" function`);let S=e.scopeValue("formats",{key:x,ref:b,code:i.code.formats?(0,kt._)`${i.code.formats}${(0,kt.getProperty)(x)}`:void 0});t.fail$data(g(S))}function g(x){return(0,kt._)`${x}.compare(${n}, ${r}) ${yi[s].fail} 0`}},dependencies:["format"]};var U0=t=>(t.addKeyword(dr.formatLimitDefinition),t);dr.default=U0});var Sb=M((bs,kb)=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var ur=bb(),M0=yb(),xd=te(),wb=new xd.Name("fullFormats"),q0=new xd.Name("fastFormats"),Td=(t,e={keywords:!0})=>{if(Array.isArray(e))return vb(t,e,ur.fullFormats,wb),t;let[n,r]=e.mode==="fast"?[ur.fastFormats,q0]:[ur.fullFormats,wb],s=e.formats||ur.formatNames;return vb(t,s,n,r),e.keywords&&(0,M0.default)(t),t};Td.get=(t,e="full")=>{let r=(e==="fast"?ur.fastFormats:ur.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function vb(t,e,n,r){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,xd._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}kb.exports=bs=Td;Object.defineProperty(bs,"__esModule",{value:!0});bs.default=Td});function z0(){let t=new _b.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$b.default)(t),t}var _b,$b,wi,xb=j(()=>{_b=zd(wd(),1),$b=zd(Sb(),1);wi=class{constructor(e){this._ajv=e??z0()}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 vi,Tb=j(()=>{Wn();vi=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]:[],u=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(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let p=new Set(l.filter(x=>x.type==="tool_use").map(x=>x.id)),g=new Set(o.filter(x=>x.type==="tool_result").map(x=>x.toolUseId));if(p.size!==g.size||![...p].every(x=>g.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},qr,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},Gn,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 Rb(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 Eb(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 Pb=j(()=>{});var ki,Ab=j(()=>{Of();Wn();xb();Ar();Tb();Pb();ki=class extends jo{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Mr.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 wi,this.setRequestHandler(qa,r=>this._oninitialize(r)),this.setNotificationHandler(za,()=>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=Mr.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new vi(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Cf(this._capabilities,e)}setRequestHandler(e,n){let s=Jt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=Bn(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(l,u)=>{let p=Wt(Vn,l);if(!p.success){let S=p.error instanceof Error?p.error.message:String(p.error);throw new z(V.InvalidParams,`Invalid tools/call request: ${S}`)}let{params:g}=p.data,x=await Promise.resolve(n(l,u));if(g.task){let S=Wt(Hn,x);if(!S.success){let T=S.error instanceof Error?S.error.message:String(S.error);throw new z(V.InvalidParams,`Invalid task creation result: ${T}`)}return S.data}let b=Wt($o,x);if(!b.success){let S=b.error instanceof Error?b.error.message:String(b.error);throw new z(V.InvalidParams,`Invalid tools/call result: ${S}`)}return b.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){Eb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Rb(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:Ah.includes(n)?n:La,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"},ao)}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(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(u=>u.type==="tool_use");if(o){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(a.filter(g=>g.type==="tool_use").map(g=>g.id)),p=new Set(s.filter(g=>g.type==="tool_result").map(g=>g.toolUseId));if(u.size!==p.size||![...u].every(g=>p.has(g)))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},Ja,n):this.request({method:"sampling/createMessage",params:e},qr,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},Gn,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},Gn,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(V.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(V.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},Ya,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 Rd(t){return!!t&&typeof t=="object"&&Cb in t}function Ob(t){return t[Cb]?.complete}var Cb,Ib,Nb=j(()=>{Cb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Ib||(Ib={}))});var Lb=j(()=>{});function F0(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"),!B0.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 H0(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 Ed(t){let e=F0(t);return H0(t,e.warnings),e.isValid}var B0,jb=j(()=>{B0=/^[A-Za-z0-9._-]{1,128}$/});var Si,Db=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 K0}from"zod";function qb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function zb(t){return"_def"in t||"_zod"in t||qb(t)}function Pd(t){return typeof t!="object"||t===null||zb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(qb)}function Ub(t){if(t){if(Pd(t))return gn(t);if(!zb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function G0(t){let e=Jt(t);return e?Object.entries(e).map(([n,r])=>{let s=Eh(r),o=Ph(r);return{name:n,description:s,required:!o}}):[]}function ln(t){let n=Jt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Bn(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function Mb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var _i,V0,ys,Bb=j(()=>{Ab();Ar();Ol();Wn();Nb();Lb();jb();Db();_i=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 ki(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(ln(_o)),this.server.assertCanSetRequestHandler(ln(Vn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(_o,()=>({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=zn(n.inputSchema);return s?Al(s,{strictUnions:!0,pipeStrategy:"input"}):V0})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let s=zn(n.outputSchema);s&&(r.outputSchema=Al(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Vn,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new z(V.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new z(V.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(V.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new z(V.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===V.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=zn(e.inputSchema)??e.inputSchema,i=await no(o,n);if(!i.success){let a="error"in i?i.error:"Unknown error",l=ro(a);throw new z(V.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(V.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let s=zn(e.outputSchema),o=await no(s,n.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=ro(i);throw new z(V.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,u=a.task,p=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(x=>setTimeout(x,p));let g=await r.taskStore.getTask(l);if(!g)throw new z(V.InternalError,`Task ${l} not found during polling`);u=g}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ln(xo)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(xo,async e=>{switch(e.params.ref.type){case"ref/prompt":return Vh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Gh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(V.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(V.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new z(V.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return ys;let o=Jt(r.argsSchema)?.[e.params.argument.name];if(!Rd(o))return ys;let i=Ob(o);if(!i)return ys;let a=await i(e.params.argument.value,e.params.context);return Mb(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 ys;throw new z(V.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ys;let o=await s(e.params.argument.value,e.params.context);return Mb(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ln(yo)),this.server.assertCanSetRequestHandler(ln(wo)),this.server.assertCanSetRequestHandler(ln(vo)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(yo,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(wo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(vo,async(e,n)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new z(V.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(V.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ln(ko)),this.server.assertCanSetRequestHandler(ln(So)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ko,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?G0(n.argsSchema):void 0}))})),this.server.setRequestHandler(So,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new z(V.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new z(V.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=zn(r.argsSchema),o=await no(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",u=ro(l);throw new z(V.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}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:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,s,o){let i={title:n,description:r,argsSchema:s===void 0?void 0:gn(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=gn(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 u=l instanceof K0?l._def?.innerType:l;return Rd(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,s,o,i,a,l,u){Ed(e);let p={title:n,description:r,inputSchema:Ub(s),outputSchema:Ub(o),annotations:i,execution:a,_meta:l,handler:u,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:g=>{typeof g.name<"u"&&g.name!==e&&(typeof g.name=="string"&&Ed(g.name),delete this._registeredTools[e],g.name&&(this._registeredTools[g.name]=p)),typeof g.title<"u"&&(p.title=g.title),typeof g.description<"u"&&(p.description=g.description),typeof g.paramsSchema<"u"&&(p.inputSchema=gn(g.paramsSchema)),typeof g.outputSchema<"u"&&(p.outputSchema=gn(g.outputSchema)),typeof g.callback<"u"&&(p.handler=g.callback),typeof g.annotations<"u"&&(p.annotations=g.annotations),typeof g._meta<"u"&&(p._meta=g._meta),typeof g.enabled<"u"&&(p.enabled=g.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(Pd(l))s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Pd(n[0])&&(i=n.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(u=>typeof u=="object"&&u!==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:u}=n;return this._createRegisteredTool(e,s,o,i,a,l,{taskSupport:"forbidden"},u,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()}},V0={type:"object",properties:{}};ys={completion:{values:[],hasMore:!1}}});function J0(t){return Uh.parse(JSON.parse(t))}function Fb(t){return JSON.stringify(t)+`
|
|
1967
|
+
`}var W0,$i,Hb=j(()=>{Wn();W0=10*1024*1024,$i=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??W0}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(`
|
|
1968
|
+
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),J0(n)}clear(){this._buffer=void 0}}});import Kb from"node:process";var xi,Vb=j(()=>{Hb();xi=class{constructor(e=Kb.stdin,n=Kb.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 $i({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=Fb(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var Gb,Wb=j(()=>{Gb=[]});var ry={};qd(ry,{AUTHORING_MCP_SERVER_NAME:()=>Xb,AUTHORING_MCP_SERVER_VERSION:()=>Qb,AUTHORING_RESOURCES:()=>nP,AUTHORING_TOOLS:()=>tP,AUTHORING_TOOLS_PUBLIC:()=>ny,buildAuthoringMcpServer:()=>ty,resolveSamplesDir:()=>ey,runAuthoringMcpServer:()=>rP});import{promises as Y0}from"node:fs";import{isAbsolute as Z0,resolve as Ti,sep as X0}from"node:path";import{z as q}from"zod";function Zb(){return Yb??=import("../mcp/grounding.js").then(e=>e,()=>null),Yb}function ey(t,e){if(e===void 0)return Ti(process.cwd(),t??"samples");let n=Ti(e);if(t===void 0)return n;if(Z0(t))return null;let r=Ti(n,t);return r===n||r.startsWith(n+X0)?r:null}function ve(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function eP(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 ty(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let b=await pt(t.baseUrl);if(!b)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:b.baseUrl,token:b.token}}let n=t.grounding??{},r=await Zb(),s=null;if(r)try{let b=await e();s={surface:"mcp-authoring",baseUrl:b.baseUrl,token:b.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(b=>({id:b.id,record_type:b.record_type,intent:b.intent}))}catch{l=[]}}let u=s?await eP(s,n):null,p=new _i({name:Xb,version:Qb},r?{instructions:r.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??s?.baseUrl??t.baseUrl??"this instance",sources:o,recipeIntents:l,promptNames:a.map(b=>b.id),deployedExtensions:u,docsToken:n.docsToken??r.docsPublicToken()})}:void 0);if(r&&s){let b=s;for(let S of a)p.registerPrompt(S.id,{title:S.name,description:S.description},async()=>{let T=await r.getMcpPromptSkill(b,S.id,n);if(!T)throw new Error(`unknown prompt: ${S.id}`);return{description:T.description,messages:[{role:"user",content:{type:"text",text:(T.prompts??[]).join(`
|
|
1876
1969
|
|
|
1877
|
-
`)}}]}})}p.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:S}=await e(),T=await fetch(`${v}/v1/catalog/records`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog fetch failed: ${T.status}`);return Se(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:B.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:B.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:S})=>{let{baseUrl:T,token:E}=await e(),P=S?`?source=${encodeURIComponent(S)}`:"",C=await fetch(`${T}/v1/catalog/records/${encodeURIComponent(v)}${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(C.status===404)throw new Error(`unknown record type "${v}" \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`record anatomy fetch failed: ${C.status}`);return Se(await C.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:B.array(B.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:B.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:S})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({types:v.join(",")});S&&P.set("source",S);let C=await fetch(`${T}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(C.status===404)throw new Error(`none of those record types resolved: ${v.join(", ")} \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`common columns fetch failed: ${C.status}`);return Se(await C.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:v,token:S}=await e(),T=await fetch(`${v}/v1/catalog/census`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog census failed: ${T.status}`);return Se(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:B.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:B.enum(Lb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:B.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:S,limit:T})=>{let{baseUrl:E,token:P}=await e(),C=new URLSearchParams({q:v});S&&C.set("kind",S),T!==void 0&&C.set("limit",String(T));let D=await fetch(`${E}/v1/catalog/objects?${C}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return Se(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:B.enum(Lb),externalId:B.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:v,externalId:S})=>{let{baseUrl:T,token:E}=await e(),P=await fetch(`${T}/v1/catalog/objects/${encodeURIComponent(v)}/${encodeURIComponent(S)}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${v}:${S} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return Se(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:B.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:B.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:v,limit:S})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({q:v});S!==void 0&&P.set("limit",String(S));let C=await fetch(`${T}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!C.ok)throw new Error(`kb search failed: ${C.status}`);return Se(await C.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:B.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:v})=>{let{baseUrl:S,token:T}=await e(),E=await fetch(`${S}/v1/kb/document/${encodeURIComponent(v)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!E.ok&&E.status!==404)throw new Error(`kb document fetch failed: ${E.status}`);return Se(await E.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:B.boolean().optional()}},async({recordsOnly:v})=>{let{baseUrl:S,token:T}=await e();return{content:[{type:"text",text:await an({baseUrl:S,token:T,recordsOnly:v})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:B.string(),event:B.string().optional(),template:B.enum(["require-field","enforce-format","blank"]).optional(),field:B.string().optional(),regex:B.string().optional(),source:B.string().optional(),id:B.string().optional()}},async v=>{let S=qt("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:S.relativePath,content:S.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:B.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:B.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:B.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:B.string().optional().describe("Target record type (defaults to the trigger record type)."),event:B.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:B.string().optional()}},async v=>{let S=qt("conduit",{recordType:v.recordType,source:v.source,to:v.to,toRecordType:v.toRecordType,event:v.event,id:v.id});return Se({path:S.relativePath,content:S.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:B.string().describe("The extension TS source."),samplesDir:B.string().optional().describe('Samples directory (default "samples").')}},async({source:v,samplesDir:S})=>{let T=zb(S,t.samplesRoot);if(T===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:P0})}],isError:!0};let E;try{E=await gr(T)}catch(D){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw D}let P=await Cs(v,E.map(D=>D.fixture)),C=P.filter(D=>!D.pass).length;return Se({total:P.length,passed:P.length-C,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:B.string(),recordType:B.string(),event:B.string(),source:B.string().describe('Adapter id or "standalone".'),sourceCode:B.string().describe("The verbatim extension TS."),extensionKind:B.string().optional()}},async v=>{let{baseUrl:S,token:T}=await e(),P=await new H({baseUrl:S,token:T}).deploy({id:v.id,recordType:v.recordType,event:v.event,source:v.source,sourceCode:v.sourceCode,extensionKind:v.extensionKind});return Se(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:B.string(),limit:B.number().int().positive().optional()}},async({id:v,limit:S})=>{let{baseUrl:T,token:E}=await e(),P=new H({baseUrl:T,token:E});return Se({id:v,logs:await P.logs(v,S)})}),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:v,token:S}=await e(),T=new H({baseUrl:v,token:S});return Se(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:B.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:B.string().optional().describe("Display name (defaults to the slug)."),description:B.string().optional().describe("Short description.")}},async({slug:v,name:S,description:T})=>{let{baseUrl:E,token:P}=await e(),C=new H({baseUrl:E,token:P});return Se(await C.appsCreate({slug:v,name:S,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:B.string().describe("App slug or id.")}},async({app:v})=>{let{baseUrl:S,token:T}=await e(),E=new H({baseUrl:S,token:T});return Se(await E.appsPull(v))}),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:B.string().describe("App slug or id."),files:B.record(B.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:B.string().optional().describe("Short note stored with the revision.")}},async({app:v,files:S,note:T})=>{let{baseUrl:E,token:P}=await e(),C=new H({baseUrl:E,token:P});return Se(await C.appsPush(v,S,{note:T}))});let g=B.object({name:B.string().describe("Field name (lowercase identifier)."),type:B.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:B.boolean().optional()}),$=B.object({slug:B.string().describe("Table slug; the physical table is cr_<slug>."),displayName:B.string().optional(),fields:B.array(g).describe("At least one field."),rowLevelOwner:B.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:v,token:S}=await e(),T=new H({baseUrl:v,token:S});return Se(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:B.array($),claimedBy:B.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:S})=>{let{baseUrl:T,token:E}=await e(),P=new H({baseUrl:T,token:E});return Se(await P.tablesPlan({tables:v,claimedBy:S}))}),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:B.array($),claimedBy:B.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:S})=>{let{baseUrl:T,token:E}=await e(),P=new H({baseUrl:T,token:E});return Se(await P.tablesApply({tables:v,claimedBy:S}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async v=>{let{baseUrl:S,token:T}=await e(),P=await(await fetch(`${S}/v1/catalog/records`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}})).text();return{contents:[{uri:v.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async v=>{let{baseUrl:S,token:T}=await e(),E=await an({baseUrl:S,token:T});return{contents:[{uri:v.href,mimeType:"text/plain",text:E}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async v=>{let S=ki(process.cwd(),"samples"),T=[];try{T=(await T0.readdir(S)).filter(P=>P.endsWith(".json"))}catch{T=[]}let E=await gr(S);return{contents:[{uri:v.href,mimeType:"application/json",text:JSON.stringify({files:T,samples:E.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 v=>{let S=await Db(),T=[];if(S){let{baseUrl:E,token:P}=await e();T=await S.listRecipesForSurface({surface:"mcp-authoring",baseUrl:E,token:P},n)}return{contents:[{uri:v.href,mimeType:"application/json",text:JSON.stringify({recipes:T})}]}}),p}async function O0(t={}){let e=await qb(t),n=new vi;await e.connect(n)}var Lb,jb,Ub,Mb,P0,Bb,I0,C0,Hb=j(()=>{Eb();Cb();zi();hr();Et();Xi();Ds();Nb();Lb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Ub="turbobase-authoring",Mb="0.1.0";P0="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";Bb=["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"],I0=[...Bb,...Ob],C0=["catalog:///","types://all","samples:///","recipes:///"]});zi();hr();Et();Xi();import{spawn as Ad}from"node:child_process";import{promises as re}from"node:fs";import{homedir as N0}from"node:os";import{basename as Gb,dirname as lr,join as Ye,relative as _i,resolve as ce,sep as Pd}from"node:path";import{Command as L0}from"commander";Yi();import{promises as cu}from"node:fs";function au(t,e){return e===t?"same-type-merge":"different-type-mint"}var du=4;function Qi(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=En(t,"id"),n=En(t,"on"),r=En(t,"source"),s=En(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=En(o,"source"),a=En(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]):du}}function En(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function Uy(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 uu(t,e,n="fixture"){let r=e.name??n,s=[],o;try{o=Qi(t)}catch(l){return{fixtureName:r,conduit:zy(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=Uy(e),a=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await Is(t),p=!!(await mr(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 g=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${g} 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 mr(l,i,{member:"transform",timeoutMs:200}),v=$.effects.logs,S=$.effects.result;if(!S||typeof S!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let T=S,E=au(o.fromRecordType,o.toRecordType),{wouldWriteBindings:P,masterAction:C}=My(o,E,e);return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,transformResult:T,applyBranch:E,wouldWriteBindings:P,masterAction:C,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 My(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 zy(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:du}}async function pu(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 hu(t){let e=await cu.readFile(t,"utf8");return JSON.parse(e)}function fu(t){return cu.readFile(t,"utf8")}function mu(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(`
|
|
1878
|
-
`);if(r.push(""),
|
|
1879
|
-
`)}function
|
|
1970
|
+
`)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:b,token:S}=await e(),T=await fetch(`${b}/v1/catalog/records`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog fetch failed: ${T.status}`);return ve(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:q.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:q.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:b,source:S})=>{let{baseUrl:T,token:R}=await e(),P=S?`?source=${encodeURIComponent(S)}`:"",N=await fetch(`${T}/v1/catalog/records/${encodeURIComponent(b)}${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(N.status===404)throw new Error(`unknown record type "${b}" \u2014 list them with catalog_get.`);if(!N.ok)throw new Error(`record anatomy fetch failed: ${N.status}`);return ve(await N.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:q.array(q.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:q.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:b,source:S})=>{let{baseUrl:T,token:R}=await e(),P=new URLSearchParams({types:b.join(",")});S&&P.set("source",S);let N=await fetch(`${T}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(N.status===404)throw new Error(`none of those record types resolved: ${b.join(", ")} \u2014 list them with catalog_get.`);if(!N.ok)throw new Error(`common columns fetch failed: ${N.status}`);return ve(await N.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:b,token:S}=await e(),T=await fetch(`${b}/v1/catalog/census`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog census failed: ${T.status}`);return ve(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:q.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:q.enum(Jb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:q.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:b,kind:S,limit:T})=>{let{baseUrl:R,token:P}=await e(),N=new URLSearchParams({q:b});S&&N.set("kind",S),T!==void 0&&N.set("limit",String(T));let D=await fetch(`${R}/v1/catalog/objects?${N}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return ve(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:q.enum(Jb),externalId:q.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:b,externalId:S})=>{let{baseUrl:T,token:R}=await e(),P=await fetch(`${T}/v1/catalog/objects/${encodeURIComponent(b)}/${encodeURIComponent(S)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${b}:${S} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return ve(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:q.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:q.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:b,limit:S})=>{let{baseUrl:T,token:R}=await e(),P=new URLSearchParams({q:b});S!==void 0&&P.set("limit",String(S));let N=await fetch(`${T}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!N.ok)throw new Error(`kb search failed: ${N.status}`);return ve(await N.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:q.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:b})=>{let{baseUrl:S,token:T}=await e(),R=await fetch(`${S}/v1/kb/document/${encodeURIComponent(b)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!R.ok&&R.status!==404)throw new Error(`kb document fetch failed: ${R.status}`);return ve(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:q.boolean().optional()}},async({recordsOnly:b})=>{let{baseUrl:S,token:T}=await e();return{content:[{type:"text",text:await pn({baseUrl:S,token:T,recordsOnly:b})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:q.string(),event:q.string().optional(),template:q.enum(["require-field","enforce-format","blank"]).optional(),field:q.string().optional(),regex:q.string().optional(),source:q.string().optional(),id:q.string().optional()}},async b=>{let S=$t("hook",{recordType:b.recordType,event:b.event,template:b.template,field:b.field,regex:b.regex,source:b.source,id:b.id});return ve({path:S.relativePath,content:S.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:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:q.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:q.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:q.string().optional().describe("Target record type (defaults to the trigger record type)."),event:q.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:q.string().optional()}},async b=>{let S=$t("conduit",{recordType:b.recordType,source:b.source,to:b.to,toRecordType:b.toRecordType,event:b.event,id:b.id});return ve({path:S.relativePath,content:S.content})}),p.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:q.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:q.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:q.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:q.string().optional()}},async b=>{let S=$t("process",{recordType:b.recordType,then:b.then,onFailure:b.onFailure,id:b.id});return ve({path:S.relativePath,content:S.content})}),p.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:q.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:q.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:q.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:q.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:q.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:q.array(q.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async b=>{let{baseUrl:S,token:T}=await e(),R=new H({baseUrl:S,token:T});return ve(await R.authorConduit({intent:b.intent,from:{source:b.fromSource,recordType:b.fromRecordType},to:{source:b.toSource,recordType:b.toRecordType},...b.intentId?{intentId:b.intentId}:{},...b.columns?.length?{columns:b.columns}:{}}))}),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:q.string().describe("The extension TS source."),samplesDir:q.string().optional().describe('Samples directory (default "samples").')}},async({source:b,samplesDir:S})=>{let T=ey(S,t.samplesRoot);if(T===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:Q0})}],isError:!0};let R;try{R=await yr(T)}catch(D){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw D}let P=await Us(b,R.map(D=>D.fixture)),N=P.filter(D=>!D.pass).length;return ve({total:P.length,passed:P.length-N,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:q.string(),recordType:q.string(),event:q.string(),source:q.string().describe('Adapter id or "standalone".'),sourceCode:q.string().describe("The verbatim extension TS."),extensionKind:q.string().optional()}},async b=>{let{baseUrl:S,token:T}=await e(),P=await new H({baseUrl:S,token:T}).deploy({id:b.id,recordType:b.recordType,event:b.event,source:b.source,sourceCode:b.sourceCode,extensionKind:b.extensionKind});return ve(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:q.string(),limit:q.number().int().positive().optional()}},async({id:b,limit:S})=>{let{baseUrl:T,token:R}=await e(),P=new H({baseUrl:T,token:R});return ve({id:b,logs:await P.logs(b,S)})}),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:b,token:S}=await e(),T=new H({baseUrl:b,token:S});return ve(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:q.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:q.string().optional().describe("Display name (defaults to the slug)."),description:q.string().optional().describe("Short description.")}},async({slug:b,name:S,description:T})=>{let{baseUrl:R,token:P}=await e(),N=new H({baseUrl:R,token:P});return ve(await N.appsCreate({slug:b,name:S,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:q.string().describe("App slug or id.")}},async({app:b})=>{let{baseUrl:S,token:T}=await e(),R=new H({baseUrl:S,token:T});return ve(await R.appsPull(b))}),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:q.string().describe("App slug or id."),files:q.record(q.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:q.string().optional().describe("Short note stored with the revision.")}},async({app:b,files:S,note:T})=>{let{baseUrl:R,token:P}=await e(),N=new H({baseUrl:R,token:P});return ve(await N.appsPush(b,S,{note:T}))});let g=q.object({name:q.string().describe("Field name (lowercase identifier)."),type:q.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:q.boolean().optional()}),x=q.object({slug:q.string().describe("Table slug; the physical table is cr_<slug>."),displayName:q.string().optional(),fields:q.array(g).describe("At least one field."),rowLevelOwner:q.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:b,token:S}=await e(),T=new H({baseUrl:b,token:S});return ve(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:q.array(x),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:S})=>{let{baseUrl:T,token:R}=await e(),P=new H({baseUrl:T,token:R});return ve(await P.tablesPlan({tables:b,claimedBy:S}))}),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:q.array(x),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:S})=>{let{baseUrl:T,token:R}=await e(),P=new H({baseUrl:T,token:R});return ve(await P.tablesApply({tables:b,claimedBy:S}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async b=>{let{baseUrl:S,token:T}=await e(),P=await(await fetch(`${S}/v1/catalog/records`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}})).text();return{contents:[{uri:b.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async b=>{let{baseUrl:S,token:T}=await e(),R=await pn({baseUrl:S,token:T});return{contents:[{uri:b.href,mimeType:"text/plain",text:R}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async b=>{let S=Ti(process.cwd(),"samples"),T=[];try{T=(await Y0.readdir(S)).filter(P=>P.endsWith(".json"))}catch{T=[]}let R=await yr(S);return{contents:[{uri:b.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 b=>{let S=await Zb(),T=[];if(S){let{baseUrl:R,token:P}=await e();T=await S.listRecipesForSurface({surface:"mcp-authoring",baseUrl:R,token:P},n)}return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({recipes:T})}]}}),p}async function rP(t={}){let e=await ty(t),n=new xi;await e.connect(n)}var Jb,Yb,Xb,Qb,Q0,ny,tP,nP,sy=j(()=>{Bb();Vb();Vi();mr();Ct();ra();Fs();Wb();Jb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Xb="turbobase-authoring",Qb="0.1.0";Q0="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";ny=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],tP=[...ny,...Gb],nP=["catalog:///","types://all","samples:///","recipes:///"]});Vi();mr();Ct();ra();import{spawn as Ld}from"node:child_process";import{promises as oe}from"node:fs";import{homedir as sP}from"node:os";import{basename as ay,dirname as Mt,join as Qe,relative as Ei,resolve as se,sep as Nd}from"node:path";import{Command as oP}from"commander";Ds();import{promises as Su}from"node:fs";function ku(t,e){return e===t?"same-type-merge":"different-type-mint"}var _u=4;function sa(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Cn(t,"id"),n=Cn(t,"on"),r=Cn(t,"source"),s=Cn(t,"recordType"),o=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let u=Cn(l[1]??"","source"),p=Cn(l[1]??"","recordType");u&&p&&o.push({source:u,recordType:p})}let i=o[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!r||!s||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:n,fromSource:r,fromRecordType:s,toSource:i.source,toRecordType:i.recordType,targets:o,cycleBudget:a?Number(a[1]):_u}}function Cn(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function ow(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 $u(t,e,n="fixture",r={}){let s=e.name??n,o=[],i;try{i=sa(t)}catch(u){return{fixtureName:s,conduit:aw(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}let a=ow(e),l=Object.entries(e.atlasLinks??{}).map(([u,p])=>({key:u,resolved:p}));try{let u=await js(t,{resolveDir:r.resolveDir}),g=!!(await br(u,a,{member:"when",timeoutMs:Ls})).whenResult;o.push({name:"from.when",status:g?"passed":"failed",detail:g?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let x=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${x} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),o.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!g)return{fixtureName:s,conduit:i,guards:o,whenPassed:g,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[]};let b=[],S=[],T=[];for(let P=0;P<i.targets.length;P+=1){let N=i.targets[P],D=await br(u,{...a,materialized:T.map(zt=>({...zt}))},{member:"transform",stepIndex:P,timeoutMs:Ls});b.push(...D.effects.logs);let W=D.effects.result;if(!W||typeof W!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${P+1})`:""} returned no result (expected { patch, createdFrom? })`);let K=W,Pe=ku(i.fromRecordType,N.recordType),{wouldWriteBindings:Le,masterAction:qt}=iw(i,N,Pe,e);S.push({to:N,transformResult:K,applyBranch:Pe,wouldWriteBindings:Le,masterAction:qt}),T.push({source:N.source,recordType:N.recordType,masterTable:`<${N.recordType} master, dry-run>`,masterRowId:`<dry-run target ${P+1}>`,externalId:null})}let R=S[0];return{fixtureName:s,conduit:i,guards:o,whenPassed:g,atlasResolutions:l,transformResult:R.transformResult,applyBranch:R.applyBranch,wouldWriteBindings:R.wouldWriteBindings,masterAction:R.masterAction,targets:S,logs:b}}catch(u){return{fixtureName:s,conduit:i,guards:o,whenPassed:!1,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}}function iw(t,e,n,r){return n==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function aw(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:_u}}async function xu(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 Tu(t){let e=await Su.readFile(t,"utf8");return JSON.parse(e)}function Ru(t){return Su.readFile(t,"utf8")}function Eu(t,e){let n=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let r=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${n.id}]: WHEN-FAILED (conduit short-circuited)`;if(r){let a=t.targets.reduce((l,u)=>l+u.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${n.id}`);let o=(n.targets.length>0?n.targets:[{source:n.toSource,recordType:n.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");s.push(`route: ${n.fromSource}.${n.fromRecordType} \u2192 ${o}${n.on?` on=${n.on}`:""}`),s.push(""),s.push("guards (dispatch order):");for(let a of t.guards){let l=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";s.push(` ${l} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)s.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return s.push(""),s.push("transform: SKIPPED (from.when gate did not fire)."),s.join(`
|
|
1971
|
+
`);let i=t.targets.length>0?t.targets:[{to:{source:n.toSource,recordType:n.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(i.forEach((a,l)=>{let u=r?` (target ${l+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";s.push(""),s.push(`transform${u} \u2192 patch:`),s.push(lw(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&s.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),s.push(""),s.push(`apply-branch${u}: ${a.applyBranch}`),s.push(` ${a.masterAction}`),s.push(""),s.push(`bindings that WOULD be written (txn_source_link)${u}:`);for(let p of a.wouldWriteBindings)s.push(` ${p.source} role=${p.role} external_id=${p.externalId??"null"} \u2014 ${p.why}`)}),t.logs.length>0){s.push(""),s.push("conduit logs:");for(let a of t.logs)s.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return s.join(`
|
|
1972
|
+
`)}function lw(t,e){return t.split(`
|
|
1880
1973
|
`).map(n=>e+n).join(`
|
|
1881
|
-
`)}var
|
|
1974
|
+
`)}var cw="2026-01-01",Pu="2026-01-01T00:00:00.000Z";function dw(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"?cw:n.startsWith("timestamp")?Pu: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:Pu}:{}:n==="uuid"?"00000000-0000-0000-0000-000000000000":n==="array"||n.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function uw(t){let e={};for(let n of t.columns)e[n.name]=dw(n.pgType,n.name);return e}function pw(t,e={}){let n=e.event??"before_save";return{name:`${t.recordType} ${n} (generated)`,context:{recordType:t.recordType,event:n,source:t.source,payload:uw(t)},expect:e.expect??"pass"}}function Au(t,e={}){return t.map(n=>({recordType:n.recordType,fixture:pw(n,e)}))}import{promises as Iu}from"node:fs";import{join as Cu,relative as hw,sep as fw}from"node:path";var mw=67324752,gw=33639248,bw=101010256,yw=(()=>{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 ww(t){let e=4294967295;for(let n=0;n<t.length;n++)e=yw[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}async function vw(t){let e=[];async function n(r){let s=await Iu.readdir(r,{withFileTypes:!0});for(let o of s){let i=Cu(r,o.name);o.isDirectory()?await n(i):o.isFile()&&e.push(hw(t,i).split(fw).join("/"))}}return await n(t),e.sort(),e}async function Ou(t){let e=await vw(t),n=[],r=[],s=0;for(let a of e){let l=Buffer.from(a,"utf8"),u=await Iu.readFile(Cu(t,a)),p=ww(u),g=Buffer.alloc(30+l.length);g.writeUInt32LE(mw,0),g.writeUInt16LE(20,4),g.writeUInt16LE(0,6),g.writeUInt16LE(0,8),g.writeUInt32LE(p,14),g.writeUInt32LE(u.length,18),g.writeUInt32LE(u.length,22),g.writeUInt16LE(l.length,26),l.copy(g,30),n.push(g,u);let x=Buffer.alloc(46+l.length);x.writeUInt32LE(gw,0),x.writeUInt16LE(20,4),x.writeUInt16LE(20,6),x.writeUInt16LE(0,10),x.writeUInt32LE(p,16),x.writeUInt32LE(u.length,20),x.writeUInt32LE(u.length,24),x.writeUInt16LE(l.length,28),x.writeUInt32LE(s,42),l.copy(x,46),r.push(x),s+=g.length+u.length}let o=Buffer.concat(r),i=Buffer.alloc(22);return i.writeUInt32LE(bw,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}}Xi();function kw(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function Ms(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function Sw(t){let e=_w(t,"from"),r=Nu(t,"to").map(s=>({source:Ms(s,"source"),recordType:Ms(s,"recordType")}));return{fromSource:e?Ms(e,"source"):void 0,fromRecordType:e?Ms(e,"recordType"):void 0,toSource:r[0]?.source,toRecordType:r[0]?.recordType,targets:r}}function _w(t,e){return Nu(t,e)[0]??null}function Nu(t,e){let n=[],r=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),s;for(;(s=r.exec(t))!==null;){let o=0,i=s.index+s[0].length-1;for(let a=i;a<t.length;a+=1){let l=t[a];if(l==="{")o+=1;else if(l==="}"&&(o-=1,o===0)){n.push(t.slice(i+1,a)),r.lastIndex=a+1;break}}}return n}function $w(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 xw(t,e){let n=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return n?Number(n[1]):void 0}function Tw(t){return/\bcreatedFrom\b/.test(t)}function Lu(t){let e=kw(t),n=[];if(e==="hook")return{kind:e,warnings:n};let{fromSource:r,fromRecordType:s,toRecordType:o,targets:i}=Sw(t);for(let p of i)if(r&&p.source&&r===p.source){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 ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let a=$w(t);if(a!==null){let p=/\bexternalId\b/.test(a),g=/\bfromSource\b/.test(a);!p&&!g&&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}``."})}let l=i.find(p=>p.recordType&&s&&p.recordType!==s)?.recordType??(s!==o?o:void 0);s&&l&&!Tw(t)&&n.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${l}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${l} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let u=xw(t,"cycleBudget");return u!==void 0&&(u<1?n.push({rule:"cycle-budget-too-low",message:`cycleBudget=${u} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):u>20&&n.push({rule:"cycle-budget-too-high",message:`cycleBudget=${u} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:n}}function ju(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(`
|
|
1882
1975
|
`);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(`
|
|
1883
1976
|
lint: ${r(`${e.warnings.length} warning(s).`)}`),i.join(`
|
|
1884
|
-
`)}function
|
|
1977
|
+
`)}function Du(t){return t.cases.filter(e=>e.status==="failed").length}function vr(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Rw(t){let e=Du(t),n=[];n.push('<?xml version="1.0" encoding="UTF-8"?>'),n.push(`<testsuite name="${vr(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let r of t.cases){let s=` <testcase name="${vr(r.name)}"`;if(r.status==="passed"){n.push(`${s} />`);continue}n.push(`${s}>`);let o=r.detail??"failed",i=r.type?` type="${vr(r.type)}"`:"";n.push(` <failure${i} message="${vr(o)}">${vr(o)}</failure>`),n.push(" </testcase>")}return n.push("</testsuite>"),`${n.join(`
|
|
1885
1978
|
`)}
|
|
1886
|
-
`}function
|
|
1887
|
-
`}function
|
|
1888
|
-
`)}function
|
|
1889
|
-
`)}function
|
|
1979
|
+
`}function Ew(t){let e={suite:t.name,tests:t.cases.length,failures:Du(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
|
|
1980
|
+
`}function qs(t,e){return e==="junit"?Rw(t):Ew(t)}var Ve={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`},On=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],nt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Uu=/\x1b\[[0-9;]*m/g;function Ot(t){return t.replace(Uu,"").length}function oa(t,e){return e<=0?1:Math.max(1,Math.ceil(Ot(t)/e))}function Pw(){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 ia=Pw();function Ee(){return ia}function aa(t){ia=t}function ze(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function rt(t,e){return ia?`${t}${e}${Ve.reset}`:e}var f={bold:t=>rt(Ve.bold,t),dim:t=>rt(Ve.dim,t),red:t=>rt(Ve.red,t),green:t=>rt(Ve.green,t),yellow:t=>rt(Ve.yellow,t),blue:t=>rt(Ve.blue,t),magenta:t=>rt(Ve.magenta,t),cyan:t=>rt(Ve.cyan,t),grey:t=>rt(Ve.grey,t)};var Se={success:t=>`${f.green("\u2713")} ${t}`,error:t=>`${f.red("\u2716")} ${t}`,warn:t=>`${f.yellow("\u26A0")} ${t}`,info:t=>`${f.dim("\xB7")} ${t}`,step:t=>`${f.cyan("\u25B8")} ${t}`},Ht={add:t=>f.green(`+ ${t}`),change:t=>f.yellow(`~ ${t}`),destroy:t=>f.red(`- ${t}`)},Aw=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),Iw=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),Cw=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Nn(t){let e=t.toLowerCase();return Aw.has(e)?f.green(t):Iw.has(e)?f.red(t):Cw.has(e)?f.yellow(t):t}function Kt(t,e=[]){let n=Math.max(Ot(t),...e.map(Ot),0),r=n+2,s=f.cyan(nt.v),o=a=>` ${a}${" ".repeat(n-Ot(a))} `,i=[f.cyan(`${nt.tl}${nt.h.repeat(r)}${nt.tr}`),`${s}${f.bold(o(t))}${s}`];if(e.length){i.push(`${f.cyan(nt.ml)}${f.dim(nt.h.repeat(r))}${f.cyan(nt.mr)}`);for(let a of e)i.push(`${s}${o(a)}${s}`)}return i.push(f.cyan(`${nt.bl}${nt.h.repeat(r)}${nt.br}`)),i.join(`
|
|
1981
|
+
`)}function ht(t,e={}){let n=e.indent??" ",r=e.gap??" ",s=e.head?[e.head,...t]:t,o=Math.max(0,...s.map(u=>u.length)),i=[];for(let u=0;u<o;u+=1)i[u]=Math.max(0,...s.map(p=>Ot(p[u]??"")));let a=u=>{let p=u.map((g,x)=>{let b=g??"";return x===u.length-1?b:b+" ".repeat(Math.max(0,i[x]-Ot(b)))});return n+p.join(r)},l=[];e.head&&(l.push(a(e.head.map(u=>f.bold(u)))),l.push(a(e.head.map((u,p)=>f.dim("\u2500".repeat(i[p]??Ot(u)))))));for(let u of t)l.push(a(u));return l.join(`
|
|
1982
|
+
`)}function la(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`${Ee()?e.map(r=>rt(Ve.cyan,r)).join(`
|
|
1890
1983
|
`):e.join(`
|
|
1891
1984
|
`)}
|
|
1892
|
-
${f.dim(` ${t}`)}`}var
|
|
1893
|
-
`),i}catch(i){throw o(),n&&
|
|
1894
|
-
`),i}}function
|
|
1895
|
-
`),o()},status(l){n=l,o()},done(l){clearInterval(a),i(),
|
|
1896
|
-
`)},stop(){clearInterval(a),i(),
|
|
1985
|
+
${f.dim(` ${t}`)}`}var st=t=>{process.stderr.write(t)};function zs(){return Ee()&&process.stderr.isTTY===!0}function Mu(t,e=15){let n=Math.max(0,Math.min(100,t??0)),r=Math.round(n/100*e);return`${"\u2588".repeat(r)}${f.dim("\u2591".repeat(e-r))}`}async function Z(t,e){let n=zs(),r=0,s;n&&(st($e.hideCursor),s=setInterval(()=>{st(`${$e.col0}${$e.clearLine}${f.magenta(On[r++%On.length])} ${t}`)},80));let o=()=>{s&&clearInterval(s),n&&st(`${$e.col0}${$e.clearLine}${$e.showCursor}`)};try{let i=await e();return o(),n&&st(`${Se.success(t)}
|
|
1986
|
+
`),i}catch(i){throw o(),n&&st(`${Se.error(t)}
|
|
1987
|
+
`),i}}function ca(t){let e=0,n={stage:"queued"},r=!1,s=()=>{let l=f.magenta(On[e%On.length]),u=f.cyan(n.stage),p=n.runStatus?` ${f.dim(`(${n.runStatus})`)}`:"",g=`${String(Math.round(n.percent??0)).padStart(3)}%`;return`${l} ${t} ${f.dim("\u25B8")} ${u}${p} ${Mu(n.percent)} ${g}`},o=()=>{st(`${$e.col0}${$e.clearLine}${s()}`),r=!0},i=()=>{r&&st(`${$e.col0}${$e.clearLine}`),r=!1};st($e.hideCursor);let a=setInterval(()=>{e+=1,o()},80);return{log(l){i(),st(`${l}
|
|
1988
|
+
`),o()},status(l){n=l,o()},done(l){clearInterval(a),i(),st($e.showCursor);let u=l.stage!=="failed",p=`${t} ${f.dim("\u25B8")} ${Ow(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;st(`${u?Se.success(p):Se.error(p)}
|
|
1989
|
+
`)},stop(){clearInterval(a),i(),st($e.showCursor)}}}function Ow(t){return t==="completed"?f.green(t):t==="failed"?f.red(t):f.cyan(t)}function Be(t,e,n={}){return new Promise((r,s)=>{let o=e.findIndex(T=>!T.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=T=>{process.stderr.write(T)},l=process.stdin,u=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${f.bold(f.cyan("?"))} ${f.bold(t)}
|
|
1897
1990
|
`),a(`${f.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
1898
|
-
`),a(
|
|
1899
|
-
`),
|
|
1900
|
-
`),s(new Error("aborted"));return}if(
|
|
1901
|
-
`){let
|
|
1902
|
-
`)}),s=n.sleep??
|
|
1903
|
-
`)});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(
|
|
1904
|
-
binding: ${r.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:r.length}}function
|
|
1905
|
-
`)}),r=e.sleep??
|
|
1991
|
+
`),a($e.hideCursor);let p=0,g=()=>{let T=process.stderr.columns??process.stdout.columns??80;p>0&&(a($e.cursorUp(p)),a($e.clearToEnd));let R=0;for(let P=0;P<e.length;P+=1){let N=e[P],D=P===i,W=D?f.cyan("\u25B6"):" ",K=N.disabled?f.grey(N.label):D?f.bold(f.cyan(N.label)):N.label,Pe=N.description?` ${f.dim(N.description)}`:"",Le=` ${W} ${K}${Pe}`;a(`\r${Le}
|
|
1992
|
+
`),R+=oa(Le,T)}p=R},x=()=>{l.removeListener("data",S),l.setRawMode?.(u??!1),l.pause(),a($e.showCursor)},b=T=>{let R=i;for(let P=0;P<e.length;P+=1)if(R=(R+T+e.length)%e.length,!e[R].disabled){i=R;return}},S=T=>{let R=T.toString("utf8");if(R===""||R==="q"){x(),a(`
|
|
1993
|
+
`),s(new Error("aborted"));return}if(R==="\r"||R===`
|
|
1994
|
+
`){let N=e[i];if(N.disabled)return;x(),r(N.value);return}if(R==="\x1B[A"||R==="k"){b(-1),g();return}if(R==="\x1B[B"||R==="j"){b(1),g();return}let P=Number(R);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,g())};l.on("data",S),g()})}function Bs(t,e){return`${Nn(t)}${" ".repeat(Math.max(0,e-t.length))}`}var zu=t=>new Promise(e=>setTimeout(e,t));function qu(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}] ${Bs(t.state,9)} ${t.conduitId} \u2192 ${e}${r} hop=${t.hop}${s}${n}`}async function Bu(t,e,n={}){let r=n.sink??(p=>{process.stdout.write(`${p}
|
|
1995
|
+
`)}),s=n.sleep??zu,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 p of[...i].reverse())r(qu(p)),a+=1,p.updatedAt>l&&(l=p.updatedAt);if(!n.follow)return a;let u=n.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<u;p+=1){await s(o);let g=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let x of[...g].reverse())r(qu(x)),a+=1,x.updatedAt>l&&(l=x.updatedAt)}return a}function Nw(t){let e=t.externalId??"\u2014",n=t.createdByConduit?` via=${t.createdByConduit}`:"",r=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Bs(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${n}${r}`}async function Fu(t,e={}){let n=e.sink??(s=>{process.stdout.write(`${s}
|
|
1996
|
+
`)});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(Nw(s));return n(`
|
|
1997
|
+
binding: ${r.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:r.length}}function Lw(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),n=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),r=t.occurrences>1?` x${t.occurrences}`:"",s=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",o=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${Bs(t.severity,5)} ${Bs(t.outcome,8)} ${t.code}${r}${n?` ${n}`:""}${o}${e?` ${e}`:""}${s}`}async function Hu(t,e={}){let n=e.sink??(P=>{process.stdout.write(`${P}
|
|
1998
|
+
`)}),r=e.sleep??zu,s=e.intervalMs??2e3,{follow:o,maxPolls:i,json:a,sink:l,sleep:u,intervalMs:p,...g}=e,x=P=>{n(a?JSON.stringify(P):Lw(P))},b=await t.platformEvents({...g,limit:g.limit??100});if(b.length===0&&!o)return n("logs: no events matched."),0;let S=0,T="";for(let P of[...b].reverse())x(P),S+=1,P.ts>T&&(T=P.ts);if(!o)return S;let R=i??Number.POSITIVE_INFINITY;for(let P=0;P<R;P+=1){await r(s);let N=await t.platformEvents({...g,...T?{after:T,since:void 0}:{},limit:200});for(let D of[...N].reverse())x(D),S+=1,D.ts>T&&(T=D.ts)}return S}Fs();Ds();function Vu(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 da=".github/workflows/turbobase-release-deploy.yml",qw=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1906
1999
|
# Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
1907
2000
|
#
|
|
1908
2001
|
# Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
|
|
@@ -2004,7 +2097,7 @@ jobs:
|
|
|
2004
2097
|
--ref "\${{ github.sha }}" \\
|
|
2005
2098
|
--project . \\
|
|
2006
2099
|
--follow
|
|
2007
|
-
`,
|
|
2100
|
+
`,zw=".github/workflows/turbobase-app-deploy.yml",Bw=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2008
2101
|
# Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
|
|
2009
2102
|
#
|
|
2010
2103
|
# What ships from this repo, and when:
|
|
@@ -2222,14 +2315,14 @@ jobs:
|
|
|
2222
2315
|
else
|
|
2223
2316
|
echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
|
|
2224
2317
|
fi
|
|
2225
|
-
`;function
|
|
2318
|
+
`;function Gu(){return[{path:da,content:qw}]}function Wu(){return[{path:zw,content:Bw}]}Fs();var Fw=[".mcp.json"];function Zu(t,e=Fw){let n=i=>i.replace(/^\//,""),r=new Set(t.split(`
|
|
2226
2319
|
`).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(`
|
|
2227
2320
|
`)?t:`${t}
|
|
2228
2321
|
`}
|
|
2229
2322
|
# Added by the Turbobase scaffold.
|
|
2230
2323
|
${s.join(`
|
|
2231
2324
|
`)}
|
|
2232
|
-
`}var
|
|
2325
|
+
`}var Hw=`# Turbobase Extensions \u2014 extension project
|
|
2233
2326
|
|
|
2234
2327
|
This directory authors **Turbobase extensions** (hooks today; conduits later)
|
|
2235
2328
|
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
@@ -2298,8 +2391,8 @@ order is the signal, and it is the part the product team reads first.
|
|
|
2298
2391
|
|
|
2299
2392
|
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
2300
2393
|
updating a test. It is checked into the repo so the whole team sees it.
|
|
2301
|
-
`,
|
|
2302
|
-
`;function
|
|
2394
|
+
`,Kw=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)+`
|
|
2395
|
+
`;function Vw(t){return`---
|
|
2303
2396
|
name: generate-types
|
|
2304
2397
|
description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
2305
2398
|
---
|
|
@@ -2310,7 +2403,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
|
|
|
2310
2403
|
|
|
2311
2404
|
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
2312
2405
|
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
2313
|
-
`}var
|
|
2406
|
+
`}var Gw=`---
|
|
2314
2407
|
name: mock-test
|
|
2315
2408
|
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
2316
2409
|
---
|
|
@@ -2319,7 +2412,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
|
2319
2412
|
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
2320
2413
|
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
2321
2414
|
fixture for each branch (a passing record and a rejecting record).
|
|
2322
|
-
`,
|
|
2415
|
+
`,Ww=`---
|
|
2323
2416
|
name: deploy
|
|
2324
2417
|
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
2325
2418
|
---
|
|
@@ -2327,7 +2420,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
|
2327
2420
|
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
2328
2421
|
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
2329
2422
|
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
2330
|
-
`;function
|
|
2423
|
+
`;function Jw(t){return`# ${t} \u2014 Turbobase app
|
|
2331
2424
|
|
|
2332
2425
|
This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
|
|
2333
2426
|
same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
|
|
@@ -2657,7 +2750,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
|
2657
2750
|
review, so what you write reaches the knowledge base and the product team instead
|
|
2658
2751
|
of evaporating at the end of the session. Keep the section headings exactly as
|
|
2659
2752
|
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
2660
|
-
`}var
|
|
2753
|
+
`}var Ln="customer",hn="email",Yw="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",Zw=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
|
|
2661
2754
|
//
|
|
2662
2755
|
// It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
|
|
2663
2756
|
// the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
|
|
@@ -2676,8 +2769,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
|
|
|
2676
2769
|
// Pure and credentials-free: no secrets, no network, no Node builtins, one
|
|
2677
2770
|
// concern per file, nothing factored into a shared module (the sandbox fences
|
|
2678
2771
|
// every import except the SDK).
|
|
2679
|
-
`;function
|
|
2680
|
-
`;return[{path:t.relativePath,content:`${
|
|
2772
|
+
`;function Xw(){let t=$t("hook",{recordType:Ln,event:"before_save",template:"enforce-format",field:hn,regex:Yw,id:`app:${Ln}:${hn}-format`,description:`Reject a ${Ln} write whose ${hn} is not an address.`}),e=(n,r,s)=>JSON.stringify({name:s,context:{recordType:Ln,event:"before_save",payload:n},expect:r},null,2)+`
|
|
2773
|
+
`;return[{path:t.relativePath,content:`${Zw}${t.content}`},{path:`samples/${Ln}.${hn}-ok.json`,content:e({company_name:"Acme Supply",[hn]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${Ln}.${hn}-malformed.json`,content:e({company_name:"Acme Supply",[hn]:"ada-at-example"},"reject","a malformed address is rejected")}]}var Qw="---\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",ev=`---
|
|
2681
2774
|
name: ship-app
|
|
2682
2775
|
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
2683
2776
|
---
|
|
@@ -2720,7 +2813,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
|
|
|
2720
2813
|
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
2721
2814
|
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
2722
2815
|
project root and DO travel \u2014 deploy reads them.
|
|
2723
|
-
`,
|
|
2816
|
+
`,tv=`---
|
|
2724
2817
|
name: business-rule-to-hook
|
|
2725
2818
|
description: Decide where a rule belongs \u2014 a hook on the instance (enforced for every writer, reusable by every app) or the app's UI. Use whenever you are about to write a validation, threshold, or "you can't do that" check.
|
|
2726
2819
|
---
|
|
@@ -2788,7 +2881,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
|
|
|
2788
2881
|
standing rules for every agent on the instance \u2014 see the record-learning skill.
|
|
2789
2882
|
A rule enforced in code and nowhere written down gets re-litigated by the next
|
|
2790
2883
|
person.
|
|
2791
|
-
`;function
|
|
2884
|
+
`;function nv(t){return`---
|
|
2792
2885
|
name: record-learning
|
|
2793
2886
|
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.
|
|
2794
2887
|
---
|
|
@@ -2843,7 +2936,7 @@ earlier claim" and still publish.
|
|
|
2843
2936
|
|
|
2844
2937
|
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
2845
2938
|
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
2846
|
-
`}function
|
|
2939
|
+
`}function rv(t){return`# What this instance's source system actually does
|
|
2847
2940
|
|
|
2848
2941
|
Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
2849
2942
|
Written for the knowledge base, and **everything here is verified against real
|
|
@@ -2974,7 +3067,7 @@ finding has not been handed to the knowledge base yet.
|
|
|
2974
3067
|
and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
|
|
2975
3068
|
already live, which is worth reading before adding another rule. -->
|
|
2976
3069
|
|
|
2977
|
-
`}function
|
|
3070
|
+
`}function sv(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
|
|
2978
3071
|
|
|
2979
3072
|
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
2980
3073
|
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
@@ -3054,7 +3147,7 @@ Expected / happened / cost / fix.
|
|
|
3054
3147
|
and what it would replace. These are the highest-signal entries in the file:
|
|
3055
3148
|
each one is a page downloading rows to fold that it could have asked for
|
|
3056
3149
|
folded. -->
|
|
3057
|
-
`}function
|
|
3150
|
+
`}function ov(t,e){let n=e?`
|
|
3058
3151
|
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
3059
3152
|
# --records focus a previous run stamped into the file, so a refresh never
|
|
3060
3153
|
# narrows what an agent deliberately widened.
|
|
@@ -3085,8 +3178,8 @@ ${n}
|
|
|
3085
3178
|
# surface unticked items at the start of a session.
|
|
3086
3179
|
turbobase project adopt -o ADOPT.md >/dev/null \\
|
|
3087
3180
|
|| echo "turbobase: \\\`turbobase project adopt\\\` failed (its error is above) \u2014 ADOPT.md was NOT refreshed." >&2
|
|
3088
|
-
`}var
|
|
3089
|
-
name: ${
|
|
3181
|
+
`}var Xu="Turbobase consultant",iv="turbobase-consultant",av=`---
|
|
3182
|
+
name: ${Xu}
|
|
3090
3183
|
description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
|
|
3091
3184
|
keep-coding-instructions: true
|
|
3092
3185
|
---
|
|
@@ -3159,8 +3252,8 @@ exists on purpose.
|
|
|
3159
3252
|
- Do not show a stack trace. Say what broke and what you are doing about it.
|
|
3160
3253
|
- Do not apologise repeatedly or pad with "great question".
|
|
3161
3254
|
- Do not use a table when a sentence works.
|
|
3162
|
-
`,
|
|
3163
|
-
`,
|
|
3255
|
+
`,lv=JSON.stringify({outputStyle:Xu,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"}]}]}},null,2)+`
|
|
3256
|
+
`,cv=`#!/usr/bin/env bash
|
|
3164
3257
|
# PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
|
|
3165
3258
|
#
|
|
3166
3259
|
# Advisory only: exits 0 always, and adds a note for the agent when the edited
|
|
@@ -3177,7 +3270,7 @@ set -uo pipefail
|
|
|
3177
3270
|
command -v node >/dev/null 2>&1 || exit 0
|
|
3178
3271
|
|
|
3179
3272
|
exec node "$(dirname "$0")/check-rule-placement.mjs"
|
|
3180
|
-
`,
|
|
3273
|
+
`,dv=String.raw`/**
|
|
3181
3274
|
* Is the file that was just edited enforcing a business rule inside the SPA?
|
|
3182
3275
|
*
|
|
3183
3276
|
* Reads the PostToolUse payload on stdin, and when BOTH signals are present —
|
|
@@ -3246,7 +3339,7 @@ process.stdout.write(
|
|
|
3246
3339
|
},
|
|
3247
3340
|
}),
|
|
3248
3341
|
);
|
|
3249
|
-
`,
|
|
3342
|
+
`,uv=`---
|
|
3250
3343
|
name: roles-and-permissions
|
|
3251
3344
|
description: Decide who can open a screen and who can change a record \u2014 declare roles in public/turbobase.json, gate the UI on capabilities, and turn a denial into a message that names the role to ask for. Use when adding a screen, a nav item, a write button, a role, or answering "who can see/do X".
|
|
3252
3345
|
---
|
|
@@ -3397,7 +3490,7 @@ a denial look like emptiness.
|
|
|
3397
3490
|
- Does every write catch \`TurbobasePermissionError\`?
|
|
3398
3491
|
- Did you run \`turbobase apps plan\`?
|
|
3399
3492
|
- Did you tell the user their administrator still has to ASSIGN the role?
|
|
3400
|
-
`,
|
|
3493
|
+
`,pv=`---
|
|
3401
3494
|
name: app-design
|
|
3402
3495
|
description: How a Turbobase app should look and behave. Read the published design system first, then the display rules here that stop a working build showing wrong data. Use before building any screen.
|
|
3403
3496
|
---
|
|
@@ -3490,7 +3583,7 @@ The design system covers the look. Two rules it does not:
|
|
|
3490
3583
|
Load it in the browser and check: does it render with ZERO rows, with ONE row,
|
|
3491
3584
|
and with several hundred? Does it survive the query failing? Does tab reach every
|
|
3492
3585
|
control, with a visible focus ring? A green \`npm run build\` proves none of these.
|
|
3493
|
-
`,
|
|
3586
|
+
`,Hs="",Ju=String.raw`{
|
|
3494
3587
|
"_comment": [
|
|
3495
3588
|
"Declarative sync config — part of this repo's desired state.",
|
|
3496
3589
|
" turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
|
|
@@ -3512,7 +3605,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
3512
3605
|
"fields": [],
|
|
3513
3606
|
"tables": []
|
|
3514
3607
|
}
|
|
3515
|
-
`,
|
|
3608
|
+
`,Yu=String.raw`{
|
|
3516
3609
|
"_comment": [
|
|
3517
3610
|
"Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
|
|
3518
3611
|
"Removing an entry does NOT remove the schedule unless you pass --prune.",
|
|
@@ -3528,51 +3621,51 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
3528
3621
|
],
|
|
3529
3622
|
"schedules": []
|
|
3530
3623
|
}
|
|
3531
|
-
`,
|
|
3624
|
+
`,hv=t=>`node_modules/
|
|
3532
3625
|
|
|
3533
3626
|
# Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
|
|
3534
3627
|
.mcp.json
|
|
3535
3628
|
|
|
3536
3629
|
.DS_Store
|
|
3537
|
-
`;function
|
|
3538
|
-
`))n(i)}return r}async function
|
|
3539
|
-
`)}),r=e.sleep??
|
|
3630
|
+
`;function ua(t={}){let e=Kw.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:hv(n)},{path:"INSTANCE-LEARNINGS.md",content:rv(s)},{path:"TURBOBASE-FEEDBACK.md",content:sv(s)},{path:".claude/settings.json",content:lv},{path:`.claude/output-styles/${iv}.md`,content:av},{path:".claude/skills/generate-types/SKILL.md",content:Vw(r)},{path:".claude/skills/record-learning/SKILL.md",content:nv(s)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:tv},{path:".claude/hooks/session-start-refresh-types.sh",content:ov(r,s),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:cv,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:dv}];return n?[{path:"CLAUDE.md",content:Jw(t.appSlug)},...o,{path:".claude/skills/preview-app/SKILL.md",content:Qw},{path:".claude/skills/ship-app/SKILL.md",content:ev},{path:".claude/skills/app-design/SKILL.md",content:pv},{path:".claude/skills/roles-and-permissions/SKILL.md",content:uv},...Xw(),{path:"conduits/.gitkeep",content:Hs},{path:"turbobase/sync.json",content:Ju},{path:"turbobase/schedules.json",content:Yu},...Wu()]:[{path:"CLAUDE.md",content:Hw},...o,{path:".claude/skills/mock-test/SKILL.md",content:Gw},{path:".claude/skills/deploy/SKILL.md",content:Ww},{path:"hooks/.gitkeep",content:Hs},{path:"conduits/.gitkeep",content:Hs},{path:"samples/.gitkeep",content:Hs},{path:"turbobase/sync.json",content:Ju},{path:"turbobase/schedules.json",content:Yu}]}import{promises as ha}from"node:fs";import{dirname as fv,join as ft,resolve as rp}from"node:path";function ep(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var kr="bundle.json",Ks="turbobase";function tp(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 pa(a)}function pa(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(Qu)),tables:[...t.sync.tables].sort(e(n=>n.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Qu)),conduits:[...t.guardrails.conduits].sort(e(n=>n.conduitId))},schedules:[...t.schedules].sort(e(n=>n.name))}}function Qu(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function np(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}")`}}var Gs="hooks",Ws="conduits",sp="processes",Vt="turbobase/sync.json",Gt="turbobase/schedules.json";function fa(t){let e=u=>{let p=new RegExp(`${u}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return p?p[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(t),r=/\bdefineProcess\s*[<(]/.test(t),s=/\bdefineHook\s*[<(]/.test(t);if(!n&&!s&&!r)return null;let o=e("id"),i=e("recordType");if(r){let u=e("source")??"standalone";return!o||!i?null:{id:o,recordType:i,event:"invoke",source:u,extensionKind:"process"}}if(n){let u=e("on"),p=e("source");return!o||!i||!u||!p?null:{id:o,recordType:i,event:u,source:p,extensionKind:"conduit"}}let a=e("event"),l=e("source")??"standalone";return!o||!i||!a?null:{id:o,recordType:i,event:a,source:l,extensionKind:"hook"}}async function Sr(t){let e;try{e=await ha.readdir(t,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of e){if(r.isDirectory()){if(r.name.startsWith(".")||r.name==="node_modules")continue;for(let s of await Sr(ft(t,r.name)))n.push(`${r.name}/${s}`);continue}r.name.endsWith(".ts")&&(r.name.endsWith(".test.ts")||r.name.endsWith(".d.ts")||n.push(r.name))}return n.sort()}async function Vs(t,e){let n;try{n=await ha.readFile(t,"utf8")}catch{return}try{return JSON.parse(n)}catch(r){throw new Error(`${e} is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}}function mv(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function gv(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function bv(t){let e={name:String(t.name??""),scheduleKind:String(t.scheduleKind??"cron"),scheduleExpr:String(t.scheduleExpr??""),scheduleTz:String(t.scheduleTz??"UTC"),body:t.body??{}};return typeof t.status=="string"&&(e.status=t.status),e}async function op(t=process.cwd()){let e=rp(t),[n,r,s]=await Promise.all([Sr(ft(e,Gs)),Sr(ft(e,Ws)),Sr(ft(e,sp))]);if(n.length>0||r.length>0||s.length>0)return!0;let[o,i]=await Promise.all([Vs(ft(e,Vt),Vt).catch(()=>{}),Vs(ft(e,Gt),Gt).catch(()=>{})]);return o!==void 0||i!==void 0}async function ip(t=process.cwd(),e={}){let n=rp(t),r=ep(e.tenant),s=[],o=[];for(let l of[Gs,Ws,sp])for(let u of await Sr(ft(n,l))){let p=`${l}/${u}`,g=await ha.readFile(ft(n,l,u),"utf8"),x=e.inline?await e.inline(g,fv(ft(n,l,u))):g,b=fa(x);if(!b){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(x)&&o.push({file:p,reason:"could not read id / recordType / event"});continue}let S={id:b.id,kind:b.extensionKind,recordType:b.recordType,event:b.event,source:b.source,sourceCode:x};b.extensionKind==="conduit"?r.conduits.push(S):r.hooks.push(S),s.push(p)}let i=await Vs(ft(n,Vt),Vt);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Vt} must be a JSON object with "fields" and/or "tables".`);let l=i;for(let u of Array.isArray(l.fields)?l.fields:[])r.sync.fields.push(mv(u));for(let u of Array.isArray(l.tables)?l.tables:[])r.sync.tables.push(gv(u));s.push(Vt)}let a=await Vs(ft(n,Gt),Gt);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Gt} must be a JSON array, or an object with a "schedules" array.`);for(let u of l)r.schedules.push(bv(u));s.push(Gt)}return r.guardrails.fieldRules=[...r.sync.fields],r.guardrails.validationHooks=r.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:pa(r),contributed:s,unparsed:o}}import{promises as ba}from"node:fs";import{resolve as _v}from"node:path";var yv="For app developers \u2014 adopt these";function ap(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 lp(t,e){let n=ap(t),r=ap(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 wv(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var gI=wv(yv);mr();Ct();var vv=t=>new Promise(e=>setTimeout(e,t));function cp(t){return t.stage==="completed"||t.stage==="failed"}function kv(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function Sv(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(`
|
|
3631
|
+
`))n(i)}return r}async function ma(t,e={}){let n=e.sink??(x=>{process.stdout.write(`${x}
|
|
3632
|
+
`)}),r=e.sleep??vv,s=e.intervalMs??2e3,o=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(x=>n(kv(x))),a=e.onPoll,l="",u="",p=x=>{a?.(x),x.stage!==u&&i(x),l=Sv(x,l,n),u=x.stage},g=await t();if(p(g),cp(g))return g;for(let x=0;x<o;x+=1)if(await r(s),g=await t(),p(g),cp(g))return g;return g}var y=t=>{process.stdout.write(`${t}
|
|
3540
3633
|
`)},L=t=>{process.stderr.write(`${t}
|
|
3541
|
-
`)};function k(t){L(f.red(`turbobase: ${t}`)),process.exit(1)}var
|
|
3542
|
-
`)){let s=
|
|
3634
|
+
`)};function k(t){L(f.red(`turbobase: ${t}`)),process.exit(1)}var _r=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function dp(t,e){let n=e.json===!0||typeof e.reporter=="string";(t.color===!1||n)&&aa(!1)}async function G(t){let e=await pt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let n=await It();if(t){let r=n.length?` Stored instances: ${n.map(s=>s.baseUrl).join(", ")}.`:"";k(`not signed in to ${tt(t)}.${r} Run \`turbobase auth login --base-url ${tt(t)} --token tb_pat_\u2026\`.`)}if(n.length===0&&k("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ze())try{let r=await Be("Multiple instances stored \u2014 pick the active one:",n.map(o=>({value:o.baseUrl,label:o.baseUrl,description:`updated ${o.updatedAt}`})));await As(r);let s=await pt();if(s)return{baseUrl:s.baseUrl,token:s.token}}catch{}k(`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 J(t,e,n){if(!(t instanceof Q)||t.status!==403)return;t.body?.error==="approval_required"&&k(`${n} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),k(`${n} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function ga(t,e,n){let r=n?Number(n):void 0;if(zs()){let o=ca(e),i;try{i=await ma(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(),k(`${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 ma(t,{sink:y,intervalMs:r})}catch(o){k(`${e} --follow failed: ${o instanceof Error?o.message:String(o)}`)}s.stage==="failed"&&k(`${e} failed${s.runStatus?` (${s.runStatus})`:""}.`),y(`${e} ${s.stage}.`)}var $v=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function xv(t){try{let e=await ba.readFile(t,"utf8");return $v.exec(e)?.[1]??null}catch{return null}}var Tv=/GENERATED by `turbobase project adopt`/,pp=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,Rv=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function up(t){let e=[],n=null;for(let r of t.split(`
|
|
3635
|
+
`)){let s=pp.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=Rv.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 Ev(t){let e=t.items.map(n=>[`- [${n.done?"x":" "}] ${n.text}`,...n.extra].join(`
|
|
3543
3636
|
`)).join(`
|
|
3544
3637
|
`);return`## v${t.version}
|
|
3545
3638
|
|
|
3546
|
-
${e}`}function
|
|
3547
|
-
`),a=i.findIndex(p=>
|
|
3639
|
+
${e}`}function Pv(t,e){let n=up(t);if(n.length===0&&!Tv.test(t))return null;let r=new Map(n.map(p=>[p.version,p])),s=[],o=0;for(let p of up(e)){let g=r.get(p.version);r.delete(p.version);let x=new Set(p.items.map(S=>S.key)),b=p.items.map(S=>{let T=g?.items.find(R=>R.key===S.key);return T?{...S,done:T.done,extra:T.extra}:S});for(let S of g?.items??[])x.has(S.key)||S.done||(b.push(S),o+=1);s.push({version:p.version,items:b})}for(let p of r.values()){let g=p.items.filter(x=>!x.done);g.length!==0&&(o+=g.length,s.push({version:p.version,items:g}))}s.sort((p,g)=>lp(g.version,p.version));let i=e.split(`
|
|
3640
|
+
`),a=i.findIndex(p=>pp.test(p)),l=(a===-1?i:i.slice(0,a)).join(`
|
|
3548
3641
|
`).replace(/\s+$/,"");return{markdown:s.length===0?`${l}
|
|
3549
3642
|
`:`${l}
|
|
3550
3643
|
|
|
3551
|
-
${s.map(
|
|
3644
|
+
${s.map(Ev).join(`
|
|
3552
3645
|
|
|
3553
3646
|
`)}
|
|
3554
|
-
`,carried:o}}function
|
|
3555
|
-
|
|
3556
|
-
`,
|
|
3557
|
-
`);for(let r of n.slice(0,
|
|
3558
|
-
`)),
|
|
3559
|
-
`))}catch(u){if(u instanceof
|
|
3560
|
-
`))}async function
|
|
3561
|
-
`))n.push(` ${f.dim("|")} ${a}`)}n.push("")}),n}function
|
|
3562
|
-
`)),
|
|
3563
|
-
`+f.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}
|
|
3564
|
-
`))}async function
|
|
3647
|
+
`,carried:o}}function hp(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 G(e.baseUrl),s=_v(process.cwd(),e.out),o=e.since?.trim()||await xv(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||k(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let u=await l.json();if(!u.available){y(`${n} ships no release notes to adopt from (nothing written).`);return}let p=u.releases.reduce((R,P)=>R+P.items.length,0);if(p===0){y(`up to date${o?` since v${o.replace(/^v/,"")}`:""}${u.currentVersion?` (instance is on v${u.currentVersion})`:""} \u2014 ${s} left untouched.`);return}let g=u.currentVersion??u.releases[0]?.version??"",x=`<!-- GENERATED by \`turbobase project adopt\` against ${n} \u2014 adopted-through=${g}. Re-run to refresh; delete this file once every line is done. -->
|
|
3648
|
+
|
|
3649
|
+
`,b=await ba.readFile(s,"utf8").catch(()=>null),S=u.markdown,T=0;if(b!==null&&b.trim()!==""){let R=Pv(b,u.markdown);R||k(`${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>\`.`),S=R.markdown,T=R.carried}await ba.writeFile(s,x+S,"utf8"),y(`wrote ${s} \u2014 ${p} item(s) across ${u.releases.length} release(s)${o?` since v${o.replace(/^v/,"")}`:""}${T>0?`, keeping ${T} unticked item(s) already in the file`:""}.`)})}Ct();var $r=["suggested_kb_edit","kb_correction"];var Av=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function Iv(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var PI=new Map(Av.map(t=>[Iv(t.heading),t]));var AI=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 Cv(t){return t.diff??!!t.dryRun}var Ov={update_page:"append to the existing page",new_page:"create a NEW page"},Nt=(t,e)=>` ${f.dim(t.padEnd(11))}${e}`,gp=t=>t.ownerEmail??t.ownerId;function jn(t){return!t.needsPageRef&&!t.blockedBy}var Js=t=>f.green(t?` + ${t}`:" +"),Nv=t=>f.red(t?` - ${t}`:" -"),fn=t=>f.dim(` ${t}`),Lv=` ${f.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,ya=80;function jv(t){let e=[Lv];t.target?(e.push(fn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(Nv(`visibility: ${t.target.visibility}`)),e.push(Js("visibility: admin"))):e.push(fn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(fn("title, slug, evidence: untouched")),e.push(fn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(fn("turbobase.document \xB7 new")),e.push(Js(`title: ${t.pageTitle}`)),e.push(Js("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(fn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(fn('appended under "## From app developers":'));let n=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
3650
|
+
`);for(let r of n.slice(0,ya))e.push(Js(r?` ${r}`:""));return n.length>ya&&e.push(f.yellow(` \u2026 ${n.length-ya} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function Dv(t,e={}){let n=[];return t.forEach((r,s)=>{let{target:o,entries:i}=r;if(n.push(`${String(s+1).padStart(2)}. ${f.bold(r.pageTitle)}`),n.push(Nt("page",o?`${o.title} (${o.slug}) [${o.visibility}]`:f.dim("new \u2014 no existing page matches"))),n.push(Nt("action",jn(r)?Ov[r.action]:f.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(Nt("unresolved",f.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(Nt("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?` ${f.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${f.dim(`(${a.kb_page_ref})`)}`:"";n.push(` ${f.dim("\xB7")} ${a.title.trim()}${u}${l}`)}),n.push(Nt("confidence",r.withdraws?f.red("WITHDRAWN from readers (text untouched)"):f.dim("untouched"))),r.supersedes&&n.push(Nt("supersedes",f.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(Nt("blocked",f.red(`unpublished work on this page belongs to ${gp(r.blockedBy)} \u2014 this page will be SKIPPED`))),r.alsoMatched.length>0&&n.push(Nt("ambiguous",f.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 u=t.findIndex(g=>g.key===l),p=u>=0?t[u]:void 0;return p?`#${u+1} "${p.pageTitle}"`:l});n.push(Nt("similar",f.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&&jn(r)&&n.push(...jv(r)),n.push("")}),n}function Uv(t){let e=u=>t.filter(u).length,n=t.reduce((u,p)=>u+p.entries.length,0),r=e(u=>u.withdraws),s=e(u=>u.blockedBy!=null),o=e(u=>u.needsPageRef),i=[`${n} finding${n===1?"":"s"}`,`${e(jn)} page(s)`,`${e(u=>u.action==="update_page"&&jn(u))} appended`,`${e(u=>u.action==="new_page"&&jn(u))} created (unpublished)`,...o>0?[f.red(`${o} SKIPPED \u2014 correction with no page to correct`)]:[]],a=r>0?f.red(`${r} page(s) WITHDRAWN from readers`):f.dim("no page withdrawn"),l=s>0?` \xB7 ${f.red(`${s} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function Mv(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(`${f.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${s.blockedBy?gp(s.blockedBy):"another editor"}; its findings stay pending`);continue}if(s.skipped==="unresolved_page_ref"){let l=[...new Set((o?.entries??[]).map(u=>u.kb_page_ref?.trim()).filter(u=>!!u))];r.push(`${f.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(u=>`"${u}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(s.skipped){r.push(`${f.yellow("skipped")} ${i} \u2014 ${s.skipped.replace(/_/g," ")}`);continue}let a=s.created?f.green("created "):f.green("appended");r.push(`${a} ${i} \u2014 ${s.appliedEntryIds.length} finding(s) \u2192 page ${f.bold(s.documentId??"?")}`+(s.created?f.dim(" (unpublished)"):"")),s.confidence==="downgraded"?r.push(` ${f.red("withdrawn from readers:")} ${i}`):s.confidence==="already_withdrawn"?r.push(` ${f.dim("page was already unpublished \u2014 left as is")}`):s.confidence==="missing"&&r.push(` ${f.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return r}function fp(t){if(t instanceof Q){let e=t.body;t.status===403&&e?.reason==="admin_required"&&k("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&k("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}J(t,"extensions:deploy","learnings push-kb")}async function xr(t,e){let n;try{n=await Z("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(s){return s instanceof Q&&s.status===404?L(f.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`.")):fu(s)?L(f.yellow(mp(s))):L(f.yellow(`could not re-read the pushed markdown: ${mp(s)} \u2014 planning anyway.`)),null}if(n.filesScanned===0)return L(f.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(f.yellow(`${n.parseSkipped} unparseable`)),L(f.dim(r.join(" \xB7 "))),n}function mp(t){return t instanceof Error?t.message:String(t)}async function bp(t,e=n=>new H(n)){t.section&&!$r.includes(t.section.trim())&&k(`unknown --section "${t.section}" \u2014 expected one of ${$r.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let n=await G(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 xr(r,t.app),i;try{i=await Z("reading the pending queue",()=>r.learningsPending(s))}catch(u){fp(u),k(`could not read the pending queue: ${u instanceof Error?u.message:String(u)}`)}if(i.items.length===0){if(i.pendingTotal===0&&o&&o.entriesDuplicate>0){L(`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}L(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(y(Dv(i.items,{diff:Cv(t)}).join(`
|
|
3651
|
+
`)),y(Uv(i.items)),t.dryRun){L(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(jn);if(a.length===0){L(f.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((u,p)=>u+p.entries.length,0);if(!t.yes){if(!ze()){L(f.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 Be(`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"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let u=await Z("writing pages",()=>r.learningsPushKb(i.planToken,s));y(Mv(u.applied,i.items).join(`
|
|
3652
|
+
`))}catch(u){if(u instanceof Q&&u.status===409){L(f.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${_r} kb push\` to review the current plan.`),process.exitCode=2;return}fp(u),L(f.red(`turbobase: ${u instanceof Error?u.message:String(u)}`)),process.exitCode=2}}Ct();var Dn=t=>new H(t);async function Un(t,e){let n=await G(t.baseUrl);return e(n)}async function Ys(t,e,n,r){return r.yes?!0:ze()?await Be(t,[{value:"yes",label:e,description:n},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function qv(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function yp(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function zv(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(`${yp(f.bold(o.slug),e)} ${yp(qv(o),10)} ${f.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 wp(t,e=Dn){let n={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),n.status=t.status);let r=await Un(t,e),s;try{s=await Z("reading the knowledge base",()=>r.docsList(n))}catch(o){J(o,"docs:publish","read the knowledge base"),k(`could not read the knowledge base: ${o instanceof Error?o.message:String(o)}`)}y(zv(s).join(`
|
|
3653
|
+
`))}async function vp(t,e,n=Dn){let r=[...new Set(t.map(l=>l.trim()).filter(Boolean))];r.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let s=await Un(e,n);if(!await Ys(`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 Z("publishing",()=>s.docsPublish(r))}catch(l){J(l,"docs:publish","publish a page"),k(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);y(f.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(L(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),L(f.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function kp(t,e,n=Dn){let r=[...new Set(t.map(l=>l.trim()).filter(Boolean))];r.length===0&&k("name at least one page slug. `turbobase kb list` shows them.");let s=await Un(e,n);if(!await Ys(`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 Z("unpublishing",()=>s.docsUnpublish(r))}catch(l){J(l,"docs:publish","unpublish a page"),k(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);y(f.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),L(f.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(L(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Sp(t,e=Dn){let n=await Un(t,e),r;try{r=await Z("reading the releases",()=>n.docsVersions())}catch(s){J(s,"docs:publish","read the knowledge-base releases"),k(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){y("no releases yet \u2014 nothing has been published.");return}for(let s of r.items){let o=s.is_current?f.green("current"):f.dim(" ");y(`v${String(s.version_no).padEnd(4)} ${o} ${s.published_at} ${s.node_count} page(s)${s.published_by?` ${f.dim(s.published_by)}`:""}`),s.release_note&&y(` ${f.dim(s.release_note)}`)}}async function _p(t,e,n=Dn){let r=Number(t);(!Number.isInteger(r)||r<1)&&k(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let s=await Un(e,n);if(await Ys(`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 Z("rolling back",()=>s.docsRollback(r));y(f.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){J(i,"docs:publish","roll the knowledge base back"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function $p(t,e,n=Dn){let r=(t??"").trim();r||k("name the page slug to delete. `turbobase kb list` shows them.");let s=await Un(e,n);if(await Ys(`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 Z("deleting",()=>s.docsDelete(r));y(f.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){J(i,"docs:publish","delete a page"),k(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}Ct();function Bv(t){return t.diff??!!t.dryRun}function Fv(t,e){let n=[];return t.forEach((r,s)=>{let o=r.action==="new_rule"?f.green("new rule"):f.yellow("amend rule"),i=r.targetPublished?` ${f.yellow("[currently live]")}`:"";n.push(`${s+1}. ${o} ${f.bold(r.slug)}${i}`),n.push(` ${r.name}`),r.description&&n.push(` ${f.dim(r.description)}`);for(let a of r.entries)n.push(` ${f.dim("\xB7")} ${f.dim(a.app_slug)} ${a.title}`);if(e.diff){n.push("");for(let a of r.bodyMarkdown.split(`
|
|
3654
|
+
`))n.push(` ${f.dim("|")} ${a}`)}n.push("")}),n}function Hv(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(f.yellow(`${n} amend a rule that is currently live`)),r.join(" \xB7 ")}async function xp(t,e=n=>new H(n)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&k("--limit must be a positive integer.");let n=await G(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 xr(r,t.app),i;try{i=await Z("reading the pending rules",()=>r.rulesPending(s))}catch(l){J(l,"extensions:deploy","read the pending rules"),k(`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){L(`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}L(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(y(Fv(i.items,{diff:Bv(t)}).join(`
|
|
3655
|
+
`)),y(Hv(i.items)),t.dryRun){L(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!ze()){L(f.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 Be(`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"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await Z("writing the rules",()=>r.rulesPush(i.planToken,s))}catch(l){l instanceof Q&&l.status===409&&k("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),k(`push failed: ${l instanceof Error?l.message:String(l)}`)}y(f.green(`wrote ${i.items.length} draft rule(s).`)),L(f.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}Ct();var Kv=["proposed","active","rejected"],Vv=["mechanic","operator","learning","code-baseline"],Zs=t=>new H(t);async function Xs(t,e){let n=await G(t.baseUrl);return e(n)}function Tp(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)||k(`${n}: unknown value '${s}' \u2014 expected one of ${e.join(", ")}.`);return r}}function Gv(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&k("--limit must be a positive number."),Math.floor(e)}function Pp(t){let e=Tp(t.status,Kv,"--status"),n=Tp(t.provenance,Vv,"--provenance"),r=Gv(t.limit);return{...e?{status:e}:{},...n?{provenance:n}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...r?{limit:r}:{}}}function Rp(t){return!!(t.provenance?.length||t.recordType||t.source)}var Ap=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function Wv(t){return t.status==="active"?f.green("active"):t.status==="rejected"?f.dim("rejected"):f.yellow("proposed")}function Jv(t){return t.message?t.message:t.kind&&t.field?f.dim(`${t.kind} ${t.field}`):t.kind?f.dim(t.kind):f.dim("(no description)")}function Ip(t){return[t.hookId,Wv(t),t.provenance==="learning"?f.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),Jv(t)]}async function Cp(t={},e=Zs){let n=await Xs(t,e),r=Pp(t),s;try{s=await n.proposals(r)}catch(i){J(i,"extensions:deploy","list hook proposals"),k(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return y(JSON.stringify(s,null,2));if(s.length===0){let i=r.status?.length?r.status.join("/"):"proposed";return y(`no ${i} hook proposals.
|
|
3656
|
+
`+f.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}y(ht(s.map(Ip),{head:Ap})),y(f.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&&y(f.dim(` ${o.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function Yv(t,e,n){return n.yes?!0:ze()?await Be(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function Zv(t){return!(t instanceof Q)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function wa(t,e){Zv(t)&&J(t,"extensions:deploy",e)}function va(t,e){let n=e instanceof Q?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);L(Se.error(`${f.bold(t)} \u2014 ${o}`))}async function Ep(t,e){try{let n=await t.proposalPromote(e);return y(Se.success(`${f.bold(e)} ${f.dim(`${n.previousStatus} \u2192`)} ${f.green(n.status)}`)),!0}catch(n){return wa(n,"promote a hook proposal"),va(e,n),!1}}async function Op(t,e={},n=Zs){!e.auto&&t.length===0&&k("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&k("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&k("promote: --apply / --all only mean something with --auto.");let r=await Xs(e,n);if(!e.auto){let p=0;for(let g of t)await Ep(r,g)&&(p+=1);p>0&&y(f.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let s=Pp({...e,status:e.status??"proposed"});s.provenance?.includes("learning")&&k("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),s.status?.some(p=>p!=="proposed")&&k("promote --auto: only `--status proposed` rows can be armed in bulk.");let o;try{o=await r.proposals(s)}catch(p){J(p,"extensions:deploy","list hook proposals"),k(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=o.filter(p=>p.provenance==="learning"),a=o.filter(p=>p.provenance!=="learning");if(e.json&&(y(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(y(`nothing to promote${Rp(s)?" for that filter":""}.`),i.length>0&&y(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(y(e.apply?`promoting ${f.bold(String(a.length))} hook proposal(s):`:`${f.bold("dry run")} \u2014 would promote ${f.bold(String(a.length))} hook proposal(s):`),y(ht(a.map(Ip),{head:Ap})),i.length>0&&y(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){y(""),y(Se.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Rp(s)&&!e.all&&k(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await Yv(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let u=0;for(let p of a)await Ep(r,p.hookId)&&(u+=1);y(f.dim(` ${u}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),u<a.length&&(process.exitCode=1)}async function Np(t,e={},n=Zs){t.length===0&&k("retract: name at least one proposal id.");let r=await Xs(e,n),s=0;for(let o of t)try{let i=await r.proposalRetract(o);y(Se.success(`${f.bold(o)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.yellow(i.status)}`)),s+=1}catch(i){wa(i,"retract a hook proposal"),va(o,i)}s>0&&y(f.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),s<t.length&&(process.exitCode=1)}async function Lp(t,e={},n=Zs){t.length===0&&k("reject: name at least one proposal id.");let r=await Xs(e,n),s=0;for(let o of t)try{let i=await r.proposalReject(o,e.reason);y(Se.success(`${f.bold(o)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.dim(i.status)}`)),s+=1}catch(i){wa(i,"reject a hook proposal"),va(o,i)}s<t.length&&(process.exitCode=1)}Ct();var Mn=t=>new H(t);async function qn(t,e){let n=await G(t.baseUrl);return e(n)}async function Qs(t,e,n,r){return r.yes?!0:ze()?await Be(t,[{value:"yes",label:e,description:n},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function Xv(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function jp(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function Qv(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(`${jp(f.bold(o.slug),e)} ${jp(Xv(o),10)} ${o.surfaces.join(",")||f.dim("none")}`),o.description&&n.push(` ${f.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 Dp(t,e=Mn){let n={};t.status&&(t.status!=="draft"&&t.status!=="published"&&k(`--status must be 'draft' or 'published' (got '${t.status}').`),n.status=t.status);let r=await qn(t,e),s;try{s=await Z("reading the skills",()=>r.skillsList(n))}catch(o){J(o,"skills:publish","read the instance skills"),k(`could not read the skills: ${o instanceof Error?o.message:String(o)}`)}y(Qv(s).join(`
|
|
3657
|
+
`))}async function Up(t,e,n=Mn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let s=await qn(e,n);if(!await Qs(`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 Z("publishing",()=>s.skillsPublish(r))}catch(a){J(a,"skills:publish","publish a skill"),k(`publish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(f.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Mp(t,e,n=Mn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&k("name at least one skill slug. `turbobase skills list` shows them.");let s=await qn(e,n);if(!await Qs(`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 Z("unpublishing",()=>s.skillsUnpublish(r))}catch(a){J(a,"skills:publish","unpublish a skill"),k(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(f.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function qp(t,e,n=Mn){let r=Number(t);(!Number.isInteger(r)||r<1)&&k(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let s=await qn(e,n);if(await Qs(`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 Z("rolling back",()=>s.skillsRollback(r));y(f.green(`rolled back to v${i.version.version_no}.`))}catch(i){J(i,"skills:publish","roll back a skills release"),k(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function zp(t,e=Mn){let n=await qn(t,e),r;try{r=await Z("reading the releases",()=>n.skillsReleases())}catch(s){J(s,"skills:publish","read the skills releases"),k(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){L("no releases yet.");return}for(let s of r.items){let o=s.is_current?f.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";y(`${o} v${s.version_no} ${s.skill_count} skill(s) ${f.dim(s.published_at)}${s.published_by?f.dim(` by ${s.published_by}`):""}${f.dim(i)}`)}}async function Bp(t,e,n=Mn){let r=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];r.length===0&&k("name at least one skill to delete. `turbobase skills list` shows the slugs.");let s=await qn(e,n);if(!await Qs(r.length===1?`Delete the skill '${r[0]}'?`:`Delete ${r.length} skills?
|
|
3565
3658
|
${r.join(`
|
|
3566
|
-
`)}`,"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 u of r)try{i.push(await
|
|
3567
|
-
`,{mode:384})}async function ik(t){let e=await Ta();e.push(t),await Mp(e)}async function zp(t){let e=await Ta(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await Mp(e),r??null}async function Ys(){return Ta()}function Ra(t,e=Date.now()){let n=[],r=[];for(let s of t)Wv(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function qp(t,e){xa(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new $r(n);let r=Jv(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>nk(u)))(e.fromTenant),i=sk(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=Yv(u.rows,r),g=Qv(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:Gv(e.ttl,s),sampleFraction:r,url:ok(o,e.baseUrl)};return await ik(l),l}async function Bp(t,e){xa(t.target());let r=(await Ys()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await zp(e),r):null}async function Ea(t,e=Date.now()){xa(t.target());let n=await Ys(),{expired:r}=Ra(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await zp(o.name),s.push(o)}return s}var xr={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish"],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"}},BI=Object.keys(xr).filter(t=>xr[t].mintable);var KI=xr.pat.prefix,ak=Object.entries(xr).map(([t,e])=>[e.prefix,t]),lk=/^[A-Za-z0-9_-]{20,}$/;function ck(t){if(typeof t!="string")return null;for(let[e,n]of ak)if(t.startsWith(e)&&lk.test(t.slice(e.length)))return n;return null}function Fp(t){return ck(t)==="pat"}hr();var dk=8e3,uk={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 pk(t){return uk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function hk(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(dk)})}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 Hp(t){return t.state==="accepted"?Ee()?f.green("accepted"):"accepted":t.state==="rejected"?Ee()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ee()?f.yellow("unreachable"):"unreachable"}async function Kp(t={},e=fetch){let n=await Rt(),{file:r}=Rs();if(n.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(f.dim(`no sign-ins stored in ${r}.`));return}let s=await dt(),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 hk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ee())b(ut(o.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),Hp(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)b(`${i.active?"* ":" "}${i.baseUrl} ${Hp(i.check)} (updated ${i.updatedAt})`);L(f.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(f.red(`${i.baseUrl}: ${pk(i.check.reason)}.`)),L(f.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"&&L(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function j0(t){let e=await Rt();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ue()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Me(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{k("cancelled.")}}async function D0(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 U0(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function M0(t,e,n){let r=await Qd({baseUrl:t,token:e}),s=(await Rt()).length-1;if(b(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),U0(r.baseUrl),!n)return;let o=await D0(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?L(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function z0(t){let e=await br(t),n=ca(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);k(r?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...n,sourceCode:e}}async function cr(t,e,n,r){try{return await re.access(t),"skipped"}catch{}return await re.mkdir(lr(t),{recursive:!0}),await re.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await re.chmod(t,r),"wrote"}async function Kb(t,e){if(Gb(t)!==".gitignore")return cr(t,e.content,e.executable,e.mode);let n=await re.readFile(t,"utf8").catch(()=>null);if(n===null)return cr(t,e.content,e.executable,e.mode);let r=Uu(n);return r===null?"skipped":(await re.writeFile(t,r,"utf8"),"merged")}function xd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Si(t){process.exit(t)}function q0(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 B0(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 F0(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 Vb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Id({includeInternal:t=!0}={}){let e=new L0;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.15.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${ra()}
|
|
3568
|
-
`),e.hook("preAction",(d,h)=>{
|
|
3569
|
-
${
|
|
3570
|
-
`).length} lines).`)}),
|
|
3659
|
+
`)}`,"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 u of r)try{i.push(await Z(`deleting ${u}`,()=>s.skillsDelete(u)))}catch(p){if(p instanceof Q&&p.status===404){a.push(u);continue}i.length>0&&L(f.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),J(p,"skills:publish","delete a skill"),k(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&y(f.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(f.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(f.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Fp}from"node:fs";import{join as ek,relative as tk,resolve as nk,sep as rk}from"node:path";var sk=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),ok=new Set([".mcp.json",".env"]);function ik(t){return ok.has(t)||t.startsWith(".env.")&&t!==".env.example"}function ak(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function lk(t){return t.includes(0)}async function Hp(t){let e=nk(t),n={},r=[],s=[],o=[];async function i(a){let l=await Fp.readdir(a,{withFileTypes:!0});for(let u of l){let p=ek(a,u.name);if(sk.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=tk(e,p).split(rk).join("/");if(ik(u.name)){s.push(g);continue}let x=await Fp.readFile(p);if(!ak(x)){r.push(g);continue}lk(x)&&o.push(g),n[g]=x.toString("utf8")}}return await i(e),{files:n,skipped:r,secrets:s,unstorable:o}}import{randomBytes as ck}from"node:crypto";var dk="/_tb/app-assets",uk=16,pk=/^[0-9a-f]{32}$/;function Kp(){return ck(uk).toString("hex")}function hk(t){return pk.test(t)}function Vp(t){if(!hk(t))throw new Error(`not a build id: ${t}`);return`${dk}/${t}/`}var Gp=7;Sa();var _a=50*1024*1024;import eo from"node:fs/promises";import Tr from"node:path";var $a={esbuild:"0.28.1","isolated-vm":"6.1.2"},xa="@turbobase/isolated-vm-prebuilds";function Ta(t,e){return`${t}-${e}`}function Ra(t=process.versions){return`abi${t.modules}`}var Wp=["darwin-x64","win32-arm64"];async function Jp(t){let e=t.platform??process.platform,n=t.arch??process.arch,r=Ta(e,n),s=Tr.join(t.home,"node_modules"),o=Tr.join(s,...xa.split("/"),"prebuilds",r),i=Tr.join(s,"isolated-vm","prebuilds",r),a;try{a=await eo.readdir(o)}catch{return[]}let l=[];await eo.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=Tr.join(i,u);try{await eo.copyFile(Tr.join(o,u),p,eo.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as fk}from"node:os";import{join as Yp}from"node:path";import{promises as Ea}from"node:fs";function Xp(){let t=process.env.TURBOBASE_HOME??Yp(fk(),".turbobase");return{dir:t,file:Yp(t,"sandboxes.json")}}var mk={s:1e3,m:6e4,h:36e5,d:864e5};function gk(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*mk[e[2]]}function bk(t,e=Date.now()){return new Date(e+gk(t)).toISOString()}function yk(t,e=Date.now()){let n=Date.parse(t);return Number.isNaN(n)?!0:n<=e}function wk(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 vk(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 kk="[REDACTED]",Rr=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Pa=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 Sk(t,e,n){let r={};for(let[s,o]of Object.entries(e)){let i=n[s];if(i===void 0)throw new Pa(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?r[s]=o==null?o:kk:r[s]=o}return r}function _k(t,e,n){return e.map(r=>Sk(t,r,n))}var Zp=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),$k=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function xk(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 Aa(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 $k)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=xk(t);if(!Zp.has(n))throw new Error(`local-only guard: target host '${n}' is not a recognised local Postgres (${[...Zp].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function Tk(t,e=Rk){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Rk(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function Ek(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Pk(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ia(){let{file:t}=Xp();try{let e=await Ea.readFile(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Qp(t){let{dir:e,file:n}=Xp();await Ea.mkdir(e,{recursive:!0}),await Ea.writeFile(n,`${JSON.stringify(t,null,2)}
|
|
3660
|
+
`,{mode:384})}async function Ak(t){let e=await Ia();e.push(t),await Qp(e)}async function eh(t){let e=await Ia(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await Qp(e),r??null}async function to(){return Ia()}function Ca(t,e=Date.now()){let n=[],r=[];for(let s of t)yk(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function th(t,e){Aa(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new Rr(n);let r=wk(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Tk(u)))(e.fromTenant),i=Ek(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=vk(u.rows,r),g=_k(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:bk(e.ttl,s),sampleFraction:r,url:Pk(o,e.baseUrl)};return await Ak(l),l}async function nh(t,e){Aa(t.target());let r=(await to()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await eh(e),r):null}async function Oa(t,e=Date.now()){Aa(t.target());let n=await to(),{expired:r}=Ca(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await eh(o.name),s.push(o)}return s}var Er={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish"],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"}},SC=Object.keys(Er).filter(t=>Er[t].mintable);var xC=Er.pat.prefix,Ik=Object.entries(Er).map(([t,e])=>[e.prefix,t]),Ck=/^[A-Za-z0-9_-]{20,}$/;function Ok(t){if(typeof t!="string")return null;for(let[e,n]of Ik)if(t.startsWith(e)&&Ck.test(t.slice(e.length)))return n;return null}function rh(t){return Ok(t)==="pat"}mr();var Nk=8e3,Lk={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 jk(t){return Lk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Dk(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(Nk)})}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 sh(t){return t.state==="accepted"?Ee()?f.green("accepted"):"accepted":t.state==="rejected"?Ee()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ee()?f.yellow("unreachable"):"unreachable"}async function oh(t={},e=fetch){let n=await It(),{file:r}=Ps();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(f.dim(`no sign-ins stored in ${r}.`));return}let s=await pt(),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 Dk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ee())y(ht(o.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),sh(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${sh(i.check)} (updated ${i.updatedAt})`);L(f.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(f.red(`${i.baseUrl}: ${jk(i.check.reason)}.`)),L(f.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"&&L(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function iP(t){let e=await It();e.length===0&&k("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ze()||k("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Be(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{k("cancelled.")}}async function aP(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 lP(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function cP(t,e,n){let r=await cu({baseUrl:t,token:e}),s=(await It()).length-1;if(y(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),lP(r.baseUrl),!n)return;let o=await aP(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?L(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function dP(t){let e=await ta(await wr(t),Mt(t)),n=fa(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);k(r?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...n,sourceCode:e}}async function En(t,e,n,r){try{return await oe.access(t),"skipped"}catch{}return await oe.mkdir(Mt(t),{recursive:!0}),await oe.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await oe.chmod(t,r),"wrote"}async function oy(t,e){if(ay(t)!==".gitignore")return En(t,e.content,e.executable,e.mode);let n=await oe.readFile(t,"utf8").catch(()=>null);if(n===null)return En(t,e.content,e.executable,e.mode);let r=Zu(n);return r===null?"skipped":(await oe.writeFile(t,r,"utf8"),"merged")}function Ad(t){if(t!==void 0){if(t==="junit"||t==="json")return t;k(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Ri(t){process.exit(t)}function uP(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 pP(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 hP(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 iy(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function jd({includeInternal:t=!0}={}){let e=new oP;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.17.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${la()}
|
|
3661
|
+
`),e.hook("preAction",(d,h)=>{dp(e.opts(),h.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 h=tt(d.baseUrl);d.token||k(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
3662
|
+
${_r} auth login --base-url ${h} --token tb_pat_\u2026`),rh(d.token)||k("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await cP(h,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=>oh({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 h=d??await iP("Pick the active instance:"),w=await As(h);if(!w){let $=await It();k(`no stored sign-in for ${tt(h)}.`+($.length?` Stored: ${$.map(v=>v.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${tt(h)} --token tb_pat_\u2026\`.`)}y(`active instance \u2192 ${w.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 It();for(let v of $)await Ji(v.baseUrl);y(`removed ${$.length} stored sign-in${$.length===1?"":"s"}.`);return}let h=await Ji(d.baseUrl);h||k(d.baseUrl?`no stored sign-in for ${tt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await pt();y(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.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:h,token:w}=await G(d.baseUrl),$;try{$=await pn({baseUrl:h,token:w,recordsOnly:d.recordsOnly})}catch(m){let _=m instanceof Error?m.message:String(m);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(_)){L("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{$=await pn({baseUrl:h,token:w,recordsOnly:!0})}catch(E){k(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else k(`types generation failed: ${_}`)}let v=se(process.cwd(),d.out);await oe.writeFile(v,$,"utf8"),y(`wrote ${v} (${$.split(`
|
|
3663
|
+
`).length} lines).`)}),hp(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:h,token:w}=await G(d.baseUrl),$=new URLSearchParams;d.records&&$.set("records",d.records),d.query&&$.set("query",d.query);let v=$.toString(),m=await fetch(`${h}/v1/catalog/grounding${v?`?${v}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});m.ok||k(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${m.status}`);let E=((await m.json()).markdown??"").trim(),A=se(process.cwd(),d.out),C=d.records?` records=${d.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
|
|
3571
3664
|
|
|
3572
|
-
`;await
|
|
3665
|
+
`;await oe.writeFile(A,O+(E?`${E}
|
|
3573
3666
|
`:`(no grounding available yet)
|
|
3574
|
-
`),"utf8"),
|
|
3575
|
-
${R===0?f.green(A):f.yellow(A)}`),Si(R>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 project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,h)=>{if(h.to){let _=await Td(),{baseUrl:R,token:A}=await V(h.baseUrl),O=new H({baseUrl:R,token:A});try{let N=await Y(`applying bundle to ${h.to}`,()=>O.configApply(_,{prune:h.prune}));b(`applied bundle to ${h.to}: +${N.applied.add} ~${N.applied.change} -${N.applied.destroy}`+(N.backfillsQueued.length?` (${N.backfillsQueued.length} backfill(s) queued)`:""));let U=N.skippedDestroys??[];if(U.length>0){L(`${U.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let I of U)L(` ${I.kind} ${I.id}`);L("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(N){N instanceof X&&N.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin."),k(`bundle apply failed: ${N instanceof Error?N.message:String(N)}`)}return}d||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:y,token:x}=await V(h.baseUrl),w=await z0(ce(process.cwd(),d)),m=new H({baseUrl:y,token:x});try{let _=await Y(`deploying ${Gb(d)}`,()=>m.deploy(w));Ee()?b(Mt("Deployed",[`${f.bold(_.id)} ${An(_.status)} ${f.dim(_.outcome)}`])):b(`deployed ${_.id} \u2192 status=${_.status} (${_.outcome}).`)}catch(_){_ instanceof X&&_.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),k(`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.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,h,y)=>{let x=!!(y.preview||y.replace||y.replaceLabel);y.replace&&y.replaceLabel&&k("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let w=ce(process.cwd(),h??".");await re.mkdir(w,{recursive:!0});let m=y.proposal??await E(w),{baseUrl:_,token:R}=await V(y.baseUrl),A=new H({baseUrl:_,token:R}),O=!1;try{O=(await A.appsList()).some(de=>de.slug===d||de.id===d)}catch(de){W(de,"extensions:deploy","deploy"),k(`could not reach ${_}: ${de instanceof Error?de.message:String(de)}`)}if(!O){y.create||k(`no app "${d}" on ${_} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let de=await Y(`creating app ${d}`,()=>g(_,R,{slug:d},{tolerateExisting:!0}));de.existed||b(`created ${de.slug??d}.`)}let N;if(y.replace)if(typeof y.replace=="string")N=y.replace;else{let{previews:de}=await G(_,R,d);if(de.length===0&&k(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),de.length>1){for(let Te of de)b(` ${Te.previewId} v${Te.version}${Te.label?` ${Te.label}`:""} ${Te.url}`);k(`${d} has ${de.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${de[0].previewId}\`.`)}N=de[0].previewId}let U;if(y.replaceLabel){let de=y.replaceLabel,{previews:Te}=await G(_,R,d),vt=Te.filter(Ti=>Ti.label===de);vt.length>0?(N=vt[0].previewId,vt.length>1&&L(`${vt.length} open previews carry the label "${de}"; replacing the newest (${N}). Close the others with \`turbobase apps preview discard\`.`)):b(`no open preview labelled "${de}" \u2014 opening one.`),U=de}let I=de=>re.stat(Ye(w,de)).then(()=>!0).catch(()=>!1),F=d,ie=w,fe=y.build!==!1;if(fe&&!await I("package.json"))if(await I("index.html"))b("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),fe=!1;else if(y.pull===!1)k(`${w} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let de=await Y(`pulling ${d}`,()=>$(_,R,d));F=de.slug??d,await v(w,de.files,!0),b(`pulled generated source (rev ${de.rev}).`)}let Tn;if(fe){let de=Ip();if(Tn={buildId:de,assetBase:Cp(de)},y.install!==!1&&!await I("node_modules")){b("installing dependencies\u2026");try{await C(["install"],w)}catch(Te){k(`npm install failed: ${Te instanceof Error?Te.message:String(Te)}`)}}b("building\u2026");try{await C(["run","build"],w,{TURBOBASE_ASSET_BASE:Tn.assetBase})}catch(Te){k(`build failed: ${Te instanceof Error?Te.message:String(Te)}`)}await I("dist")||k(`no dist/ after build in ${w} \u2014 check the app's build script.`),ie=Ye(w,"dist")}x&&!Tn&&k(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${F}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let Oe=await Fe(_,R,F,ie,y.entry,m,Tn,x?{label:y.label??U,replacePreviewId:N}:void 0);if(x){let de=Oe.previewUrl??"(no url returned)",Te=Oe.expiresAt?new Date(Oe.expiresAt).toLocaleDateString():`${Op} days`,vt=Oe.replacedVersion==null?null:`replaced v${Oe.replacedVersion} \u2014 same URL`;if(Ee())b(Mt(vt?"Preview replaced":"Preview deployed",[`${f.bold(F)} ${f.green(`v${Oe.version??"?"}`)} ${f.dim("not live")}`,`${f.bold(de)}`,...vt?[f.dim(vt)]:[],f.dim(`expires ${Te}`)]));else{let Ti=vt?`; ${vt}`:"";b(`preview ${F} v${Oe.version??"?"} \u2192 ${de} (expires ${Te}; /a/${F} unchanged${Ti}).`)}b(`next: turbobase apps promote ${F} ${Oe.previewId??"<preview-id>"} # make it live`),b(` turbobase apps preview discard ${Oe.previewId??"<preview-id>"}`);return}Ee()?b(Mt("Deployed",[`${f.bold(F)} ${f.green(`v${Oe.version??"?"}`)} ${f.dim(Oe.url??`/a/${F}`)}`])):b(`deployed ${F} \u2192 v${Oe.version??"?"} (${Oe.url??`/a/${F}`}).`),He(Oe),_n(Oe),await $n(Oe,w)}),l.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").action(async(d,h)=>{let y=await K0(d??".");y||k(`no public/turbobase.json under ${ce(process.cwd(),d??".")}.`);let x=Array.isArray(y.manifest.tables)?y.manifest.tables:[],w=Array.isArray(y.manifest.writes)?y.manifest.writes:[],m=Array.isArray(y.manifest.roles)?y.manifest.roles:[],_=Array.isArray(y.manifest.labels)?y.manifest.labels:[];if(x.length===0&&w.length===0&&m.length===0&&_.length===0)return b(`${y.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);let{baseUrl:R,token:A}=await V(h.baseUrl),O=new H({baseUrl:R,token:A});if(x.length>0){let N;try{N=await Y("planning tables",()=>O.tablesPlan({claimedBy:h.as,tables:x}))}catch(U){W(U,"extensions:deploy","plan tables"),ws(U)}b(`claiming as ${f.bold(N.claimedBy)}`);for(let U of N.tables)ys(U,{showClaimants:!0})}if(w.length>0||m.length>0||_.length>0){let N;try{N=await Y("checking declared writes, roles and labels",()=>O.appsPlan({writes:w,roles:m,labels:_}))}catch(U){W(U,"extensions:deploy","plan writes"),k(`plan writes failed: ${U instanceof Error?U.message:String(U)}`)}if(N.roles&&N.roles.verdicts.length>0){b(""),b(f.bold("roles"));let U=Math.max(...N.roles.verdicts.map(I=>I.name.length));for(let I of N.roles.verdicts){let F=I.name.padEnd(U);if(I.action==="error")L(` ${f.bold("ERROR")} ${F} \u2014 ${I.message??"cannot be created"}`);else if(I.action==="create"){let ie=I.addCapabilities?.length??0;b(` create ${F} ${f.dim(`${ie} capabilit${ie===1?"y":"ies"}`)}`)}else if(I.action==="add_capabilities"){let ie=(I.addCapabilities??[]).map(fe=>`+${fe}`).join(", ");b(` add ${F} ${f.dim(ie)}`)}else b(` ${f.dim("ok")} ${F} ${f.dim("already up to date")}`)}N.roles.verdicts.some(I=>I.action!=="error")&&b(f.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}if(N.labels&&N.labels.verdicts.length>0){b(""),b(f.bold("labels"));let U=Math.max(...N.labels.verdicts.map(I=>I.name.length));for(let I of N.labels.verdicts){let F=I.name.padEnd(U);if(I.action==="create")b(` create ${F} ${f.dim(I.color)}`);else{let ie=I.declaredColor?`${I.color} \u2014 declared ${I.declaredColor}, the instance's colour is kept`:I.color;b(` ${f.dim("ok")} ${F} ${f.dim(ie)}`)}}b(f.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}w.length>0&&b("");for(let U of N.verdicts){let I=`${U.source} ${U.recordType}.${U.op}`;U.allowed?U.heldForApproval?b(`${f.dim("HELD")} ${I} \u2014 allowed, but each write waits for operator approval.`):b(`${f.dim("ok")} ${I}`):L(`${f.bold("DENIED")} ${I}${U.rule?` \u2014 guardrail "${U.rule}"`:""} (${U.reason})`)}N.ok||(b(""),k(N.message??(N.roles&&!N.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}b(""),b(f.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),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,h,y)=>{let{baseUrl:x,token:w}=await V(y.baseUrl),m=await Y(`promoting ${h}`,()=>se(x,w,d,"promote",{previewId:h}));Ee()?b(Mt("Promoted",[`${f.bold(d)} ${f.green(`v${m.version??"?"}`)} ${f.dim(m.url??`/a/${d}`)}`])):b(`promoted ${d} \u2192 v${m.version??"?"} is now live at ${m.url??`/a/${d}`}.`),_n({labels:m.labels?{applied:!0,verdicts:m.labels}:null}),await $n(m)});let u=l.command("preview").description("Inspect and manage an app's open previews.");u.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,h)=>{let{baseUrl:y,token:x}=await V(h.baseUrl),w=await G(y,x,d);if(h.json)return b(JSON.stringify(w.previews,null,2));if(w.previews.length===0){b(`no open previews for ${d}.`);return}for(let m of w.previews){let _=m.label?` ${m.label}`:"",R=m.expiresAt?new Date(m.expiresAt).toLocaleDateString():"?";b(`v${m.version} ${m.previewId}${_} ${m.url} (expires ${R})`)}}),u.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,y)=>{let{baseUrl:x,token:w}=await V(y.baseUrl);await Y(`discarding ${h}`,()=>se(x,w,d,"discard",{previewId:h})),b(`discarded ${h}.`)}),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,h)=>{let{baseUrl:y,token:x}=await V(h.baseUrl),w=await Y(`creating ${d}`,()=>g(y,x,{slug:d,name:h.name,description:h.description})),m=w.slug??d;Ee()?b(Mt("Created",[`${f.bold(m)} ${f.dim(w.url??`/a/${m}`)}`])):b(`created ${m} (${w.url??`/a/${m}`}).`),b(`next: turbobase apps push ${m} . # store the source`),b(` turbobase apps deploy ${m} # build + go live`)});let p=Ps(fetch);async function g(d,h,y,x={}){let w=`${d.replace(/\/+$/,"")}/v1/apps`,m;try{m=await p(w,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:y.slug,name:y.name??y.slug,description:y.description})})}catch(_){k(`create request failed: ${_ instanceof Error?_.message:String(_)}`)}if(m.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),m.status===409){if(x.tolerateExisting)return{slug:y.slug,existed:!0};k(`an app with slug "${y.slug}" already exists.`)}return m.ok||k(`create failed: HTTP ${m.status} ${(await m.text().catch(()=>"")).slice(0,200)}`),await m.json().catch(()=>({}))}async function $(d,h,y){let x=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/pull`,w;try{w=await p(x,{headers:{Authorization:`Bearer ${h}`}})}catch(m){k(`pull request failed: ${m instanceof Error?m.message:String(m)}`)}return w.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),w.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),w.status===404&&k(`no generated source for "${y}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),w.ok||k(`pull failed: HTTP ${w.status} ${(await w.text().catch(()=>"")).slice(0,200)}`),await w.json()}async function v(d,h,y){let x=ce(d),w=0;for(let[m,_]of Object.entries(h)){let R=ce(x,m);R!==x&&!R.startsWith(x+Pd)&&k(`refusing to write outside ${x}: ${m}`),y||await re.stat(R).then(()=>!0).catch(()=>!1)&&k(`${R} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(lr(R),{recursive:!0}),await re.writeFile(R,_,"utf8"),w+=1}return w}function S(d){let h=d.indexOf(","),y=d.startsWith("data:")?h>=0?d.slice(h+1):"":d;if(!y)return null;try{let x=Buffer.from(y,"base64");return x.length>0?new Uint8Array(x):null}catch{return null}}async function T(d,h,y){let x=ce(d),w=async(_,R)=>{let A=ce(x,_);A!==x&&!A.startsWith(x+Pd)&&k(`refusing to write outside ${x}: ${_}`),y||await re.stat(A).then(()=>!0).catch(()=>!1)&&k(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(lr(A),{recursive:!0}),await re.writeFile(A,R)},m=`# ${h.title||"App change request"}
|
|
3667
|
+
`),"utf8"),y(`wrote ${A}${E?"":" (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 (${$r.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=>bp(d)),o.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>wp(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,h)=>vp(d,h)),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,h)=>kp(d,h)),o.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Sp(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,h)=>_p(d,h)),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,h)=>$p(d,h)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>xp(d)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>Dp(d)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Up(d,h)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Mp(d,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>zp(d)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>qp(d,h)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Bp(d,h));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 h;try{h=$t("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(v){k(v instanceof Error?v.message:String(v))}let w=se(process.cwd(),h.relativePath);await En(w,h.content)==="skipped"&&k(`refusing to overwrite existing file: ${w}`),y(`wrote ${w}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let h;try{h=$t("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(v){k(v instanceof Error?v.message:String(v))}let w=se(process.cwd(),h.relativePath);await En(w,h.content)==="skipped"&&k(`refusing to overwrite existing file: ${w}`),y(`wrote ${w}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let h;try{h=$t("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(v){k(v instanceof Error?v.message:String(v))}let w=se(process.cwd(),h.relativePath);await En(w,h.content)==="skipped"&&k(`refusing to overwrite existing file: ${w}`),y(`wrote ${w}`)}),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,h)=>{let w=Ad(h.reporter),$=await wr(se(process.cwd(),d)),v=se(process.cwd(),h.samples),m=await yr(v);m.length===0&&!w&&y(`no samples found under ${v} \u2014 add JSON fixtures to dry-run against.`);let _;try{_=await Us($,m.map(C=>C.fixture),{resolveDir:Mt(se(process.cwd(),d))})}catch(C){k(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(w){let C=uP(_);y(qs(C,w)),Ri(C.cases.some(O=>O.status==="failed")?1:0)}let E=0;for(let C of _){let O=C.pass?f.green("PASS"):f.red("FAIL");C.pass||(E+=1);let U=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";y(` ${O} ${C.name}${U}`)}let A=`${_.length-E}/${_.length} sample(s) passed.`;y(`
|
|
3668
|
+
${E===0?f.green(A):f.yellow(A)}`),Ri(E>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 project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,h)=>{if(h.to){let _=await Id(),{baseUrl:E,token:A}=await G(h.baseUrl),C=new H({baseUrl:E,token:A});try{let O=await Z(`applying bundle to ${h.to}`,()=>C.configApply(_,{prune:h.prune}));y(`applied bundle to ${h.to}: +${O.applied.add} ~${O.applied.change} -${O.applied.destroy}`+(O.backfillsQueued.length?` (${O.backfillsQueued.length} backfill(s) queued)`:""));let U=O.skippedDestroys??[];if(U.length>0){L(`${U.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let I of U)L(` ${I.kind} ${I.id}`);L("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(O){O instanceof Q&&O.status===403&&k("apply forbidden (403) \u2014 the stored PAT is not for an admin."),k(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}d||k("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:w,token:$}=await G(h.baseUrl),v=await dP(se(process.cwd(),d)),m=new H({baseUrl:w,token:$});try{let _=await Z(`deploying ${ay(d)}`,()=>m.deploy(v));Ee()?y(Kt("Deployed",[`${f.bold(_.id)} ${Nn(_.status)} ${f.dim(_.outcome)}`])):y(`deployed ${_.id} \u2192 status=${_.status} (${_.outcome}).`)}catch(_){_ instanceof Q&&_.status===403&&k("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),k(`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.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,h,w)=>{let $=!!(w.preview||w.replace||w.replaceLabel);w.replace&&w.replaceLabel&&k("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let v=se(process.cwd(),h??".");await oe.mkdir(v,{recursive:!0});let m=w.proposal??await R(v),{baseUrl:_,token:E}=await G(w.baseUrl),A=new H({baseUrl:_,token:E}),C=!1;try{C=(await A.appsList()).some(de=>de.slug===d||de.id===d)}catch(de){J(de,"extensions:deploy","deploy"),k(`could not reach ${_}: ${de instanceof Error?de.message:String(de)}`)}if(!C){w.create||k(`no app "${d}" on ${_} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let de=await Z(`creating app ${d}`,()=>g(_,E,{slug:d},{tolerateExisting:!0}));de.existed||y(`created ${de.slug??d}.`)}let O;if(w.replace)if(typeof w.replace=="string")O=w.replace;else{let{previews:de}=await K(_,E,d);if(de.length===0&&k(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),de.length>1){for(let Re of de)y(` ${Re.previewId} v${Re.version}${Re.label?` ${Re.label}`:""} ${Re.url}`);k(`${d} has ${de.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${de[0].previewId}\`.`)}O=de[0].previewId}let U;if(w.replaceLabel){let de=w.replaceLabel,{previews:Re}=await K(_,E,d),_t=Re.filter(Ii=>Ii.label===de);_t.length>0?(O=_t[0].previewId,_t.length>1&&L(`${_t.length} open previews carry the label "${de}"; replacing the newest (${O}). Close the others with \`turbobase apps preview discard\`.`)):y(`no open preview labelled "${de}" \u2014 opening one.`),U=de}let I=de=>oe.stat(Qe(v,de)).then(()=>!0).catch(()=>!1),F=d,ae=v,fe=w.build!==!1;if(fe&&!await I("package.json"))if(await I("index.html"))y("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),fe=!1;else if(w.pull===!1)k(`${v} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let de=await Z(`pulling ${d}`,()=>x(_,E,d));F=de.slug??d,await b(v,de.files,!0),y(`pulled generated source (rev ${de.rev}).`)}let An;if(fe){let de=Kp();if(An={buildId:de,assetBase:Vp(de)},w.install!==!1&&!await I("node_modules")){y("installing dependencies\u2026");try{await N(["install"],v)}catch(Re){k(`npm install failed: ${Re instanceof Error?Re.message:String(Re)}`)}}y("building\u2026");try{await N(["run","build"],v,{TURBOBASE_ASSET_BASE:An.assetBase})}catch(Re){k(`build failed: ${Re instanceof Error?Re.message:String(Re)}`)}await I("dist")||k(`no dist/ after build in ${v} \u2014 check the app's build script.`),ae=Qe(v,"dist")}$&&!An&&k(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${F}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let je=await Pe(_,E,F,ae,w.entry,m,An,$?{label:w.label??U,replacePreviewId:O}:void 0);if($){let de=je.previewUrl??"(no url returned)",Re=je.expiresAt?new Date(je.expiresAt).toLocaleDateString():`${Gp} days`,_t=je.replacedVersion==null?null:`replaced v${je.replacedVersion} \u2014 same URL`;if(Ee())y(Kt(_t?"Preview replaced":"Preview deployed",[`${f.bold(F)} ${f.green(`v${je.version??"?"}`)} ${f.dim("not live")}`,`${f.bold(de)}`,..._t?[f.dim(_t)]:[],f.dim(`expires ${Re}`)]));else{let Ii=_t?`; ${_t}`:"";y(`preview ${F} v${je.version??"?"} \u2192 ${de} (expires ${Re}; /a/${F} unchanged${Ii}).`)}y(`next: turbobase apps promote ${F} ${je.previewId??"<preview-id>"} # make it live`),y(` turbobase apps preview discard ${je.previewId??"<preview-id>"}`);return}Ee()?y(Kt("Deployed",[`${f.bold(F)} ${f.green(`v${je.version??"?"}`)} ${f.dim(je.url??`/a/${F}`)}`])):y(`deployed ${F} \u2192 v${je.version??"?"} (${je.url??`/a/${F}`}).`),Le(je),qt(je),await zt(je,v)}),l.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").action(async(d,h)=>{let w=await mP(d??".");w||k(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`);let $=Array.isArray(w.manifest.tables)?w.manifest.tables:[],v=Array.isArray(w.manifest.writes)?w.manifest.writes:[],m=Array.isArray(w.manifest.roles)?w.manifest.roles:[],_=Array.isArray(w.manifest.labels)?w.manifest.labels:[];if($.length===0&&v.length===0&&m.length===0&&_.length===0)return y(`${w.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);let{baseUrl:E,token:A}=await G(h.baseUrl),C=new H({baseUrl:E,token:A});if($.length>0){let O;try{O=await Z("planning tables",()=>C.tablesPlan({claimedBy:h.as,tables:$}))}catch(U){J(U,"extensions:deploy","plan tables"),Ss(U)}y(`claiming as ${f.bold(O.claimedBy)}`);for(let U of O.tables)ks(U,{showClaimants:!0})}if(v.length>0||m.length>0||_.length>0){let O;try{O=await Z("checking declared writes, roles and labels",()=>C.appsPlan({writes:v,roles:m,labels:_}))}catch(U){J(U,"extensions:deploy","plan writes"),k(`plan writes failed: ${U instanceof Error?U.message:String(U)}`)}if(O.roles&&O.roles.verdicts.length>0){y(""),y(f.bold("roles"));let U=Math.max(...O.roles.verdicts.map(I=>I.name.length));for(let I of O.roles.verdicts){let F=I.name.padEnd(U);if(I.action==="error")L(` ${f.bold("ERROR")} ${F} \u2014 ${I.message??"cannot be created"}`);else if(I.action==="create"){let ae=I.addCapabilities?.length??0;y(` create ${F} ${f.dim(`${ae} capabilit${ae===1?"y":"ies"}`)}`)}else if(I.action==="add_capabilities"){let ae=(I.addCapabilities??[]).map(fe=>`+${fe}`).join(", ");y(` add ${F} ${f.dim(ae)}`)}else y(` ${f.dim("ok")} ${F} ${f.dim("already up to date")}`)}O.roles.verdicts.some(I=>I.action!=="error")&&y(f.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}if(O.labels&&O.labels.verdicts.length>0){y(""),y(f.bold("labels"));let U=Math.max(...O.labels.verdicts.map(I=>I.name.length));for(let I of O.labels.verdicts){let F=I.name.padEnd(U);if(I.action==="create")y(` create ${F} ${f.dim(I.color)}`);else{let ae=I.declaredColor?`${I.color} \u2014 declared ${I.declaredColor}, the instance's colour is kept`:I.color;y(` ${f.dim("ok")} ${F} ${f.dim(ae)}`)}}y(f.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}v.length>0&&y("");for(let U of O.verdicts){let I=`${U.source} ${U.recordType}.${U.op}`;U.allowed?U.heldForApproval?y(`${f.dim("HELD")} ${I} \u2014 allowed, but each write waits for operator approval.`):y(`${f.dim("ok")} ${I}`):L(`${f.bold("DENIED")} ${I}${U.rule?` \u2014 guardrail "${U.rule}"`:""} (${U.reason})`)}O.ok||(y(""),k(O.message??(O.roles&&!O.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}y(""),y(f.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),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,h,w)=>{let{baseUrl:$,token:v}=await G(w.baseUrl),m=await Z(`promoting ${h}`,()=>W($,v,d,"promote",{previewId:h}));Ee()?y(Kt("Promoted",[`${f.bold(d)} ${f.green(`v${m.version??"?"}`)} ${f.dim(m.url??`/a/${d}`)}`])):y(`promoted ${d} \u2192 v${m.version??"?"} is now live at ${m.url??`/a/${d}`}.`),qt({labels:m.labels?{applied:!0,verdicts:m.labels}:null}),await zt(m)});let u=l.command("preview").description("Inspect and manage an app's open previews.");u.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=await K(w,$,d);if(h.json)return y(JSON.stringify(v.previews,null,2));if(v.previews.length===0){y(`no open previews for ${d}.`);return}for(let m of v.previews){let _=m.label?` ${m.label}`:"",E=m.expiresAt?new Date(m.expiresAt).toLocaleDateString():"?";y(`v${m.version} ${m.previewId}${_} ${m.url} (expires ${E})`)}}),u.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,w)=>{let{baseUrl:$,token:v}=await G(w.baseUrl);await Z(`discarding ${h}`,()=>W($,v,d,"discard",{previewId:h})),y(`discarded ${h}.`)}),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,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=await Z(`creating ${d}`,()=>g(w,$,{slug:d,name:h.name,description:h.description})),m=v.slug??d;Ee()?y(Kt("Created",[`${f.bold(m)} ${f.dim(v.url??`/a/${m}`)}`])):y(`created ${m} (${v.url??`/a/${m}`}).`),y(`next: turbobase apps push ${m} . # store the source`),y(` turbobase apps deploy ${m} # build + go live`)});let p=Is(fetch);async function g(d,h,w,$={}){let v=`${d.replace(/\/+$/,"")}/v1/apps`,m;try{m=await p(v,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:w.slug,name:w.name??w.slug,description:w.description})})}catch(_){k(`create request failed: ${_ instanceof Error?_.message:String(_)}`)}if(m.status===401&&k("create unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&k("create forbidden (403) \u2014 the PAT is not for an admin."),m.status===409){if($.tolerateExisting)return{slug:w.slug,existed:!0};k(`an app with slug "${w.slug}" already exists.`)}return m.ok||k(`create failed: HTTP ${m.status} ${(await m.text().catch(()=>"")).slice(0,200)}`),await m.json().catch(()=>({}))}async function x(d,h,w){let $=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/pull`,v;try{v=await p($,{headers:{Authorization:`Bearer ${h}`}})}catch(m){k(`pull request failed: ${m instanceof Error?m.message:String(m)}`)}return v.status===401&&k("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),v.status===403&&k("pull forbidden (403) \u2014 the PAT is not for an admin."),v.status===404&&k(`no generated source for "${w}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),v.ok||k(`pull failed: HTTP ${v.status} ${(await v.text().catch(()=>"")).slice(0,200)}`),await v.json()}async function b(d,h,w){let $=se(d),v=0;for(let[m,_]of Object.entries(h)){let E=se($,m);E!==$&&!E.startsWith($+Nd)&&k(`refusing to write outside ${$}: ${m}`),w||await oe.stat(E).then(()=>!0).catch(()=>!1)&&k(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await oe.mkdir(Mt(E),{recursive:!0}),await oe.writeFile(E,_,"utf8"),v+=1}return v}function S(d){let h=d.indexOf(","),w=d.startsWith("data:")?h>=0?d.slice(h+1):"":d;if(!w)return null;try{let $=Buffer.from(w,"base64");return $.length>0?new Uint8Array($):null}catch{return null}}async function T(d,h,w){let $=se(d),v=async(_,E)=>{let A=se($,_);A!==$&&!A.startsWith($+Nd)&&k(`refusing to write outside ${$}: ${_}`),w||await oe.stat(A).then(()=>!0).catch(()=>!1)&&k(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await oe.mkdir(Mt(A),{recursive:!0}),await oe.writeFile(A,E)},m=`# ${h.title||"App change request"}
|
|
3576
3669
|
|
|
3577
3670
|
> Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
|
|
3578
3671
|
> \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
|
|
@@ -3582,35 +3675,35 @@ ${h.bodyMarkdown||"_No description provided._"}
|
|
|
3582
3675
|
## Screen context
|
|
3583
3676
|
|
|
3584
3677
|
`+(h.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
|
|
3585
|
-
`);if(await
|
|
3586
|
-
`)}async function E(d){try{let h=await re.readFile(Ye(d,".turbobase","proposal.json"),"utf8"),y=JSON.parse(h);return typeof y.proposalId=="string"&&y.proposalId?y.proposalId:void 0}catch{return}}async function P(d,h,y,x,w,m){let _=new H({baseUrl:d,token:h});try{return await _.appsPush(y,x,{note:w,proposalId:m})}catch(R){if(R instanceof X){let A=R.body;if(R.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),R.status===403&&A?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),R.status===403&&W(R,"extensions:deploy","push app source"),R.status===404&&k(`no app "${y}" on this instance \u2014 create it with \`turbobase apps create ${y}\`.`),R.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),R.status===400){let O=A?.path?` in ${A.path}`:"",N=A?.reason?` (${A.reason})`:"";k(`push rejected: ${A?.error??"bad request"}${N}${O}.`)}}k(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function C(d,h,y){return new Promise((x,w)=>{let m=Ad("npm",d,{cwd:h,stdio:"inherit",...y?{env:{...process.env,...y}}:{}});m.on("error",w),m.on("exit",_=>_===0?x():w(new Error(`npm ${d.join(" ")} exited ${_??"?"}`)))})}async function D(d,h,y,x){let w=`${d.replace(/\/+$/,"")}${y}`,m;try{m=await p(w,{method:x.method,headers:{Authorization:`Bearer ${h}`,...x.body?{"content-type":"application/json"}:{}},...x.body?{body:JSON.stringify(x.body)}:{}})}catch(_){k(`request failed: ${_ instanceof Error?_.message:String(_)}`)}if(m.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!m.ok){let _=await m.text().catch(()=>""),R=_.slice(0,300);try{let A=JSON.parse(_);R=A.message??A.error??R}catch{}k(`failed: HTTP ${m.status} ${R}`)}return await m.json().catch(()=>({}))}async function se(d,h,y,x,w){return await D(d,h,`/v1/apps/${encodeURIComponent(y)}/preview/${x}`,{method:"POST",body:w})}async function G(d,h,y){return{previews:(await D(d,h,`/v1/apps/${encodeURIComponent(y)}/previews`,{method:"GET"})).previews??[]}}async function Fe(d,h,y,x,w,m,_,R){let A;try{A=await Y(`zipping ${x}`,()=>vu(x))}catch(I){k(`could not zip ${x}: ${I instanceof Error?I.message:String(I)}`)}A.fileCount===0&&k(`${x} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>ya&&k(`${x} zips to ${Vb(A.buffer.byteLength)} \u2014 over the ${Vb(ya)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let O={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};w&&(O["x-app-entry"]=w),m&&(O["x-proposal-id"]=m),_&&(O["x-app-build-id"]=_.buildId,O["x-app-asset-base"]=_.assetBase),R&&(O["x-app-channel"]="preview",R.label&&(O["x-app-preview-label"]=encodeURIComponent(R.label)),R.replacePreviewId&&(O["x-app-preview-replace"]=R.replacePreviewId));let N=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(y)}/deploy`,U;try{U=await Y(`deploying ${y} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(N,{method:"POST",headers:O,body:new Uint8Array(A.buffer)}))}catch(I){k(`deploy request failed: ${I instanceof Error?I.message:String(I)}`)}if(U.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),U.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),U.status===404){let I=await U.text().catch(()=>""),F={};try{F=JSON.parse(I)}catch{}F.error==="no_preview"&&k(`${F.message??`no open preview to replace on ${y}`} \u2014 list them with \`turbobase apps preview list ${y}\`.`),k(`no app "${y}" on ${d} \u2014 create it with \`turbobase apps create ${y}\`.`)}if(!U.ok){let I=await U.text().catch(()=>""),F=I.slice(0,300);try{let ie=JSON.parse(I);F=ie.message??ie.error??F}catch{}k(`deploy failed: HTTP ${U.status} ${F}`)}return await U.json().catch(()=>({}))}function He(d){let h=d.roles;if(!h||h.verdicts.length===0)return;let y=h.verdicts.filter(w=>w.action!=="noop");if(y.length===0)return;b(""),b(f.bold(h.applied?"roles":"roles (preview \u2014 not applied)"));let x=Math.max(...y.map(w=>w.name.length));for(let w of y){let m=w.name.padEnd(x);if(w.action==="create"){let _=w.addCapabilities?.length??0;b(` created ${m} ${f.dim(`${_} capabilit${_===1?"y":"ies"}`)}`)}else if(w.action==="add_capabilities"){let _=(w.addCapabilities??[]).map(A=>`+${A}`).join(", "),R=w.holdersRestamped?f.dim(` (${w.holdersRestamped} holder${w.holdersRestamped===1?"":"s"} re-stamped)`):"";b(` updated ${m} ${f.dim(_)}${R}`)}}b(f.dim(h.applied?" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.":" nothing was created \u2014 promoting this preview applies them."))}function _n(d){let h=d.labels;if(!h||h.verdicts.length===0)return;let y=h.verdicts.filter(w=>w.action!=="noop");if(y.length===0)return;b(""),b(f.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let x=Math.max(...y.map(w=>w.name.length));for(let w of y){let m=w.name.padEnd(x);if(w.action==="detach")b(` removed ${m} ${f.dim("no longer declared in the manifest")}`);else if(w.action==="create")b(` created ${m} ${f.dim(w.color)}`);else{let _=w.declaredColor?`${w.color} \u2014 declared ${w.declaredColor}, the instance's colour is kept`:w.color;b(` added ${m} ${f.dim(_)}`)}}b(f.dim(h.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function $n(d,h){let y=Ou(d,{localDocsModifiedAt:await sn(h)});y&&b(y.level==="warn"?f.yellow(y.message):f.dim(y.message))}async function sn(d){if(!d)return null;let h=null;for(let y of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let x=await re.stat(Ye(d,y));(h===null||x.mtimeMs>h)&&(h=x.mtimeMs)}catch{}return h===null?null:new Date(h)}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,h,y)=>{let{baseUrl:x,token:w}=await V(y.baseUrl);if(y.proposal){let A=new H({baseUrl:x,token:w}),O;try{O=await Y(`fetching proposal ${y.proposal}`,()=>A.appPullContext(y.proposal))}catch(ie){W(ie,"extensions:deploy","pull proposal"),ie instanceof X&&ie.status===404&&k(`no widget proposal "${y.proposal}" on ${x}.`),k(`could not fetch proposal ${y.proposal}: ${ie instanceof Error?ie.message:String(ie)}`)}let N=await Y(`pulling ${O.appSlug}`,()=>$(x,w,O.appSlug)),U=h??d,I=ce(process.cwd(),U??O.appSlug);await re.mkdir(I,{recursive:!0});let F=await v(I,N.files,!!y.force);await T(I,O,!!y.force),b(`pulled ${F} file${F===1?"":"s"} \u2192 ${I} (rev ${N.rev}), linked to proposal ${O.proposalId}.`),b(`next: cd ${_i(process.cwd(),I)||"."} && turbobase apps deploy ${O.appSlug}`);return}d||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let m=await Y(`pulling ${d}`,()=>$(x,w,d)),_=ce(process.cwd(),h??m.slug??d);await re.mkdir(_,{recursive:!0});let R=await v(_,m.files,!!y.force);b(`pulled ${R} file${R===1?"":"s"} \u2192 ${_} (rev ${m.rev}).`),b(`next: cd ${_i(process.cwd(),_)||"."} && 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(d,h,y)=>{let x=ce(process.cwd(),h??d),w=await dt(y.baseUrl).catch(()=>null),{scaffoldAppFiles:m,starterApp:_}=await Promise.resolve().then(()=>(ph(),uh)),R=y.title??d,A=m({slug:d,title:R,appTsx:_(R),instanceOrigin:w?.baseUrl});await re.mkdir(x,{recursive:!0});let O=await v(x,A,!!y.force);if(b(`scaffolded ${O} file${O===1?"":"s"} \u2192 ${x}`),y.claude!==!1){let U=ia({baseUrl:w?.baseUrl,token:w?.token,appSlug:d}),I=0;for(let F of U){let ie=await Kb(Ye(x,F.path),F);(ie==="wrote"||ie==="merged")&&(I+=1)}b(`wired Claude Code: ${I} file${I===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),w||L("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=_i(process.cwd(),x)||".";b(`next: cd ${N} && npm install && npm run dev`),b(` turbobase apps create ${d}`),b(` turbobase apps push ${d} .`),b(` 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:h,token:y}=await V(d.baseUrl),x=new H({baseUrl:h,token:y}),w;try{w=await x.appsList()}catch(m){W(m,"extensions:deploy","list apps"),k(`list apps failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return b(JSON.stringify(w,null,2));if(w.length===0)return b("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");b(ut(w.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(d,h,y)=>{let x=ce(process.cwd(),h??".");await re.stat(x).then(fe=>fe.isDirectory()).catch(()=>!1)||k(`${x} is not a directory.`);let{baseUrl:m,token:_}=await V(y.baseUrl),R=y.proposal??await E(x),{files:A,skipped:O,secrets:N,unstorable:U}=await Ap(x),I=Object.keys(A).length;if(I===0&&k(`no source files found under ${x} (build output and node_modules are skipped).`),U.length>0){for(let fe of U)L(`${fe} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${U.length} ${U.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let fe of O)L(f.dim(`skipped binary file ${fe}`));for(let fe of N)L(f.dim(`skipped ${fe} (holds credentials \u2014 never pushed)`));let F=await Y(`pushing ${I} file${I===1?"":"s"}`,()=>P(m,_,d,A,y.note,R));b(`pushed ${F.files} file${F.files===1?"":"s"} \u2192 ${F.slug} rev ${F.rev} (source only, nothing deployed).`);let ie=await Sr(new H({baseUrl:m,token:_}),F.slug);ie&&ie.entriesAdded>0&&b(`${ie.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),b(`next: turbobase apps deploy ${F.slug}`)}),s.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let h=await Td(),{baseUrl:y,token:x}=await V(d.baseUrl),w=new H({baseUrl:y,token:x}),m;try{m=await Y(`planning against ${d.to??y}`,()=>w.configPlan(h))}catch(_){k(`plan failed: ${_ instanceof Error?_.message:String(_)}`)}G0(m,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).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let h=await Td(),{baseUrl:y,token:x}=await V(d.baseUrl),w=h.tenant??W0(y),m=Fu(d.confirm,w);m.ok||k(`promote refused (fail-closed): ${m.reason}`);let _=new H({baseUrl:y,token:x});try{let R=await Y(`promoting ${d.from} \u2192 ${d.to} (${w})`,()=>_.configApply(h,{prune:d.prune}));if(Ee()){let O=[`${f.bold(`${d.from} \u2192 ${d.to}`)} ${f.dim(w??"")}`,`${Ut.add(String(R.applied.add))} ${Ut.change(String(R.applied.change))} ${Ut.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&O.push(f.dim(`${R.backfillsQueued.length} backfill(s) queued`)),b(Mt("Promoted",O))}else b(`promoted ${d.from} \u2192 ${d.to} (${w}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""));let A=R.skippedDestroys??[];if(A.length>0){L(`${A.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let O of A)L(` ${O.kind} ${O.id}`);L("Re-run with --prune to remove them, or add them to this repo.")}}catch(R){R instanceof X&&R.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${R instanceof Error?R.message:String(R)}`)}}),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,h)=>{let y=xd(h.reporter),x=ce(process.cwd(),d),w=await br(x),m=Su(w);y?b(Ns(B0(d,m),y)):b(_u(d,m,{warn:f.yellow,ok:f.green,dim:f.dim})),h.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(d,h)=>{let y=xd(h.reporter),x=await fu(ce(process.cwd(),d));if(h.against){h.against!=="sandbox"&&k(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await pu(Qi(x))}catch(_){k(_ instanceof Error?_.message:String(_))}return}h.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let w;try{w=await hu(ce(process.cwd(),h.fixture))}catch(_){k(`could not read fixture ${h.fixture}: ${_ instanceof Error?_.message:String(_)}`)}let m=await uu(x,w,h.fixture);if(y){let _=F0(m);b(Ns(_,y)),Si(_.cases.some(R=>R.status==="failed")?1:0)}b(mu(m,!!h.trace)),Si(m.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:h,token:y}=await V(d.baseUrl),x=new H({baseUrl:h,token:y});try{await Au(x,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:b})}catch(w){w instanceof X&&w.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),w instanceof X&&w.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${w instanceof Error?w.message:String(w)}`)}});let jt=s.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");jt.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 yp(d)}),jt.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,h)=>{await wp(d??[],h)}),jt.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{await vp(d,h)}),jt.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,h)=>{await kp(d,h)}),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,h)=>{let y=d.lastIndexOf("@"),x=y>0?d.slice(0,y):d,w=y>0?d.slice(y+1):void 0,m=Gi();m||k(`marketplace not configured \u2014 set ${Rn} and ${As}.
|
|
3587
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let _=
|
|
3588
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
3589
|
-
project init: ${
|
|
3590
|
-
project ci: ${h} written, ${
|
|
3591
|
-
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),
|
|
3592
|
-
`;d.force?(await
|
|
3593
|
-
samples init: ${
|
|
3594
|
-
`+f.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ut(w.map(bs),{head:$i})),b(f.dim(" first match wins; lower PRIO is evaluated first."))}),wt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:y,token:x}=await V(h.baseUrl),w=new H({baseUrl:y,token:x}),m;try{m=await w.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(_){W(_,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}b(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} created${m.status==="active"?"":f.dim(` (${m.status} \u2014 activate it to take effect)`)}`),b(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.actor?` actor=${m.actor}`:""}${m.when?` where ${m.when}`:""} @prio ${m.priority}`)),b(f.dim(` verify with: turbobase guardrails test --source ${m.source==="*"?"<source>":m.source} --record <record>`))}),wt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:y,token:x}=await V(h.baseUrl),w=new H({baseUrl:y,token:x}),m;try{m=await w.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(_){W(_,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}b(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} updated`),b(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.when?` where ${m.when}`:""} @prio ${m.priority}`))});for(let[d,h,y]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])wt.command(`${d} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(x,w)=>{let{baseUrl:m,token:_}=await V(w.baseUrl),R=new H({baseUrl:m,token:_});try{await R.guardrailUpdate(x,{status:h})}catch(A){W(A,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${f.green("\u2713")} guardrail ${f.bold(x)} ${y}`),h==="inactive"&&b(f.dim(" writes it was gating now fall through to the other rules."))});wt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:y,token:x}=await V(h.baseUrl),w=new H({baseUrl:y,token:x});try{await w.guardrailDelete(d)}catch(m){W(m,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}b(`${f.green("\u2713")} guardrail ${f.bold(d)} deleted`)}),wt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:y,token:x}=await V(h.baseUrl),w=new H({baseUrl:y,token:x}),m=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await w.guardrailPostureGet()}catch(O){W(O,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${O instanceof Error?O.message:String(O)}`)}b(`guardrail posture: ${f.bold(m(A.mode))}`),b(f.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"&&k("posture must be 'allow' or 'deny'.");let R;try{R=await w.guardrailPostureSet(_)}catch(A){W(A,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${f.green("\u2713")} guardrail posture set to ${f.bold(m(R.mode))}`),R.mode==="deny"&&b(f.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),wt.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let h;if(d.fields)try{h=JSON.parse(d.fields)}catch(R){k(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:y,token:x}=await V(d.baseUrl),w=new H({baseUrl:y,token:x}),m;try{m=await w.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){W(R,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return b(JSON.stringify(m,null,2));let _=`${d.source}/${m.op??d.record}`;m.degraded?(b(`${f.red("\u2717")} ${_} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(f.dim(` ${m.reason}`))):m.allowed?b(`${f.green("\u2713")} ${_} \u2014 ${m.decision}`+(m.blockedBy?f.dim(` (rule ${m.blockedBy})`):f.dim(" (no rule matched)"))):(b(`${f.red("\u2717")} ${_} \u2014 ${m.decision} by ${f.bold(m.blockedBy??"?")} at the ${m.phase} gate`),m.message&&b(f.dim(` ${m.message}`))),m.decision==="require_confirm"&&b(f.yellow(" this write is HELD for operator approval, not refused.")),m.allowed||(process.exitCode=1)});let dr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),ys=(d,h={})=>{let y=`${f.bold(d.table)} ${f.dim(d.displayName)}`;b(d.exists===!1?`${y} ${f.dim("(new)")}`:y);for(let x of d.fields){let w=[x.required?"required":null].filter(Boolean).join(", "),m=h.showClaimants&&x.claimedBy?.length?` ${f.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";b(` ${x.column.padEnd(28)} ${x.type}${w?` (${w})`:""}${m}`)}h.showClaimants&&d.claimants.length>1&&b(f.dim(` claimed by ${d.claimants.join(", ")}`))};function ws(d){if(d instanceof X&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let Cd=async d=>{let h=Ye(ce(process.cwd(),d),"public","turbobase.json"),y=await re.readFile(h,"utf8").catch(()=>null);if(y===null)return null;let x;try{x=JSON.parse(y)}catch(m){k(`${h} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let w=x.tables;return w===void 0?{tables:[],manifestPath:h}:(Array.isArray(w)||k(`${h}: "tables" must be an array.`),{tables:w,manifestPath:h})};dr.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:y}=await V(d.baseUrl),x=new H({baseUrl:h,token:y}),w;try{w=await x.tablesList()}catch(m){W(m,"extensions:deploy","list tables"),k(`list tables failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return b(JSON.stringify(w,null,2));if(w.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ut(w.map(m=>[m.table,m.displayName,String(m.fields.length),m.status,m.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),dr.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,h)=>{let y=await Cd(d??".");if(y||k(`no public/turbobase.json under ${ce(process.cwd(),d??".")}.`),y.tables.length===0)return b(`${y.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:w}=await V(h.baseUrl),m=new H({baseUrl:x,token:w}),_;try{_=await Y("planning tables",()=>m.tablesPlan({claimedBy:h.as,tables:y.tables}))}catch(R){W(R,"extensions:deploy","plan tables"),ws(R)}b(`claiming as ${f.bold(_.claimedBy)}`);for(let R of _.tables)ys(R,{showClaimants:!0});b(""),b(f.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),dr.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,h)=>{let y=await Cd(d??".");if(y||k(`no public/turbobase.json under ${ce(process.cwd(),d??".")}.`),y.tables.length===0)return b(`${y.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:w}=await V(h.baseUrl),m=new H({baseUrl:x,token:w}),_;try{_=await Y("applying tables",()=>m.tablesApply({claimedBy:h.as,tables:y.tables}))}catch(R){W(R,"extensions:deploy","apply tables"),ws(R)}for(let R of _.tables)ys(R,{showClaimants:!0});b(`applied ${_.tables.length} table${_.tables.length===1?"":"s"} as ${_.claimedBy}.`)}),dr.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let y=h.field.map(R=>{let[A,O,N]=R.split(":");return(!A||!O)&&k(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),N!==void 0&&N!=="required"&&k(`--field "${R}": the third part may only be "required".`),{name:A,type:O,...N==="required"?{required:!0}:{}}}),{baseUrl:x,token:w}=await V(h.baseUrl),m=new H({baseUrl:x,token:w}),_;try{_=await Y(`creating cr_${d}`,()=>m.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:y,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){W(R,"extensions:deploy","create a table"),ws(R)}for(let R of _.tables)ys(R);b(""),b(f.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),dr.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.confirm!==d&&k(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:y,token:x}=await V(h.baseUrl),w=new H({baseUrl:y,token:x}),m;try{m=await Y(`dropping cr_${d}`,()=>w.tablesDrop(d,h.confirm))}catch(_){W(_,"extensions:deploy","drop a table"),k(`drop failed: ${_ instanceof Error?_.message:String(_)}`)}if(!m.removed)return b(`no table named "${d}" on this instance \u2014 nothing dropped.`);b(`dropped ${m.table} and every row in it.`)});let xi=e.command("sandbox").description("Ephemeral local authoring sandboxes.");xi.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let h=Rd(),y;try{y=await qp(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(x){x instanceof $r&&k(x.message),k(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}b(`sandbox ${y.name} ready.`),b(` source: ${y.fromTenant} (sampled ${Math.round(y.sampleFraction*100)}%, redacted)`),b(` url: ${y.url}`),b(` expires: ${y.expiresAt}`)}),xi.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let h=Rd();await Ea(h).catch(()=>[]);let y;try{y=await Bp(h,d)}catch(x){k(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}y||k(`no sandbox named '${d}'.`),b(`destroyed sandbox ${y.name} (dropped ${y.database}).`)}),xi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Rd(),h=await Ea(d).catch(()=>[]),y=await Ys(),{active:x}=Ra(y);if(x.length===0)b("no active sandboxes.");else{for(let w of x)b(` ${w.name} from=${w.fromTenant} expires=${w.expiresAt} ${w.url}`);b(`
|
|
3595
|
-
${
|
|
3596
|
-
`,_=
|
|
3597
|
-
`).length} lines).`)});let
|
|
3598
|
-
run \`${
|
|
3678
|
+
`);if(await v("PROPOSAL.md",m),h.screenshot){let _=S(h.screenshot);_&&await v("proposal-screenshot.png",_)}await v(Qe(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
|
|
3679
|
+
`)}async function R(d){try{let h=await oe.readFile(Qe(d,".turbobase","proposal.json"),"utf8"),w=JSON.parse(h);return typeof w.proposalId=="string"&&w.proposalId?w.proposalId:void 0}catch{return}}async function P(d,h,w,$,v,m){let _=new H({baseUrl:d,token:h});try{return await _.appsPush(w,$,{note:v,proposalId:m})}catch(E){if(E instanceof Q){let A=E.body;if(E.status===401&&k("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&k("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&J(E,"extensions:deploy","push app source"),E.status===404&&k(`no app "${w}" on this instance \u2014 create it with \`turbobase apps create ${w}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&k("push rejected: the request body exceeded the instance limit."),k(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let C=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";k(`push rejected: ${A?.error??"bad request"}${O}${C}.`)}}k(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function N(d,h,w){return new Promise(($,v)=>{let m=Ld("npm",d,{cwd:h,stdio:"inherit",...w?{env:{...process.env,...w}}:{}});m.on("error",v),m.on("exit",_=>_===0?$():v(new Error(`npm ${d.join(" ")} exited ${_??"?"}`)))})}async function D(d,h,w,$){let v=`${d.replace(/\/+$/,"")}${w}`,m;try{m=await p(v,{method:$.method,headers:{Authorization:`Bearer ${h}`,...$.body?{"content-type":"application/json"}:{}},...$.body?{body:JSON.stringify($.body)}:{}})}catch(_){k(`request failed: ${_ instanceof Error?_.message:String(_)}`)}if(m.status===401&&k("unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&k("forbidden (403) \u2014 the PAT is not for an admin."),!m.ok){let _=await m.text().catch(()=>""),E=_.slice(0,300);try{let A=JSON.parse(_);E=A.message??A.error??E}catch{}k(`failed: HTTP ${m.status} ${E}`)}return await m.json().catch(()=>({}))}async function W(d,h,w,$,v){return await D(d,h,`/v1/apps/${encodeURIComponent(w)}/preview/${$}`,{method:"POST",body:v})}async function K(d,h,w){return{previews:(await D(d,h,`/v1/apps/${encodeURIComponent(w)}/previews`,{method:"GET"})).previews??[]}}async function Pe(d,h,w,$,v,m,_,E){let A;try{A=await Z(`zipping ${$}`,()=>Ou($))}catch(I){k(`could not zip ${$}: ${I instanceof Error?I.message:String(I)}`)}A.fileCount===0&&k(`${$} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>_a&&k(`${$} zips to ${iy(A.buffer.byteLength)} \u2014 over the ${iy(_a)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let C={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};v&&(C["x-app-entry"]=v),m&&(C["x-proposal-id"]=m),_&&(C["x-app-build-id"]=_.buildId,C["x-app-asset-base"]=_.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 O=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/deploy`,U;try{U=await Z(`deploying ${w} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(O,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(I){k(`deploy request failed: ${I instanceof Error?I.message:String(I)}`)}if(U.status===401&&k("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),U.status===403&&k("deploy forbidden (403) \u2014 the PAT is not for an admin."),U.status===404){let I=await U.text().catch(()=>""),F={};try{F=JSON.parse(I)}catch{}F.error==="no_preview"&&k(`${F.message??`no open preview to replace on ${w}`} \u2014 list them with \`turbobase apps preview list ${w}\`.`),k(`no app "${w}" on ${d} \u2014 create it with \`turbobase apps create ${w}\`.`)}if(!U.ok){let I=await U.text().catch(()=>""),F=I.slice(0,300);try{let ae=JSON.parse(I);F=ae.message??ae.error??F}catch{}k(`deploy failed: HTTP ${U.status} ${F}`)}return await U.json().catch(()=>({}))}function Le(d){let h=d.roles;if(!h||h.verdicts.length===0)return;let w=h.verdicts.filter(v=>v.action!=="noop");if(w.length===0)return;y(""),y(f.bold(h.applied?"roles":"roles (preview \u2014 not applied)"));let $=Math.max(...w.map(v=>v.name.length));for(let v of w){let m=v.name.padEnd($);if(v.action==="create"){let _=v.addCapabilities?.length??0;y(` created ${m} ${f.dim(`${_} capabilit${_===1?"y":"ies"}`)}`)}else if(v.action==="add_capabilities"){let _=(v.addCapabilities??[]).map(A=>`+${A}`).join(", "),E=v.holdersRestamped?f.dim(` (${v.holdersRestamped} holder${v.holdersRestamped===1?"":"s"} re-stamped)`):"";y(` updated ${m} ${f.dim(_)}${E}`)}}y(f.dim(h.applied?" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.":" nothing was created \u2014 promoting this preview applies them."))}function qt(d){let h=d.labels;if(!h||h.verdicts.length===0)return;let w=h.verdicts.filter(v=>v.action!=="noop");if(w.length===0)return;y(""),y(f.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let $=Math.max(...w.map(v=>v.name.length));for(let v of w){let m=v.name.padEnd($);if(v.action==="detach")y(` removed ${m} ${f.dim("no longer declared in the manifest")}`);else if(v.action==="create")y(` created ${m} ${f.dim(v.color)}`);else{let _=v.declaredColor?`${v.color} \u2014 declared ${v.declaredColor}, the instance's colour is kept`:v.color;y(` added ${m} ${f.dim(_)}`)}}y(f.dim(h.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function zt(d,h){let w=Vu(d,{localDocsModifiedAt:await cn(h)});w&&y(w.level==="warn"?f.yellow(w.message):f.dim(w.message))}async function cn(d){if(!d)return null;let h=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let $=await oe.stat(Qe(d,w));(h===null||$.mtimeMs>h)&&(h=$.mtimeMs)}catch{}return h===null?null:new Date(h)}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,h,w)=>{let{baseUrl:$,token:v}=await G(w.baseUrl);if(w.proposal){let A=new H({baseUrl:$,token:v}),C;try{C=await Z(`fetching proposal ${w.proposal}`,()=>A.appPullContext(w.proposal))}catch(ae){J(ae,"extensions:deploy","pull proposal"),ae instanceof Q&&ae.status===404&&k(`no widget proposal "${w.proposal}" on ${$}.`),k(`could not fetch proposal ${w.proposal}: ${ae instanceof Error?ae.message:String(ae)}`)}let O=await Z(`pulling ${C.appSlug}`,()=>x($,v,C.appSlug)),U=h??d,I=se(process.cwd(),U??C.appSlug);await oe.mkdir(I,{recursive:!0});let F=await b(I,O.files,!!w.force);await T(I,C,!!w.force),y(`pulled ${F} file${F===1?"":"s"} \u2192 ${I} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),y(`next: cd ${Ei(process.cwd(),I)||"."} && turbobase apps deploy ${C.appSlug}`);return}d||k("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let m=await Z(`pulling ${d}`,()=>x($,v,d)),_=se(process.cwd(),h??m.slug??d);await oe.mkdir(_,{recursive:!0});let E=await b(_,m.files,!!w.force);y(`pulled ${E} file${E===1?"":"s"} \u2192 ${_} (rev ${m.rev}).`),y(`next: cd ${Ei(process.cwd(),_)||"."} && 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(d,h,w)=>{let $=se(process.cwd(),h??d),v=await pt(w.baseUrl).catch(()=>null),{scaffoldAppFiles:m,starterApp:_}=await Promise.resolve().then(()=>(Th(),xh)),E=w.title??d,A=m({slug:d,title:E,appTsx:_(E),instanceOrigin:v?.baseUrl});await oe.mkdir($,{recursive:!0});let C=await b($,A,!!w.force);if(y(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${$}`),w.claude!==!1){let U=ua({baseUrl:v?.baseUrl,token:v?.token,appSlug:d}),I=0;for(let F of U){let ae=await oy(Qe($,F.path),F);(ae==="wrote"||ae==="merged")&&(I+=1)}y(`wired Claude Code: ${I} file${I===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),v||L("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 O=Ei(process.cwd(),$)||".";y(`next: cd ${O} && npm install && npm run dev`),y(` turbobase apps create ${d}`),y(` turbobase apps push ${d} .`),y(` 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:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w}),v;try{v=await $.appsList()}catch(m){J(m,"extensions:deploy","list apps"),k(`list apps failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(v,null,2));if(v.length===0)return y("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");y(ht(v.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(d,h,w)=>{let $=se(process.cwd(),h??".");await oe.stat($).then(fe=>fe.isDirectory()).catch(()=>!1)||k(`${$} is not a directory.`);let{baseUrl:m,token:_}=await G(w.baseUrl),E=w.proposal??await R($),{files:A,skipped:C,secrets:O,unstorable:U}=await Hp($),I=Object.keys(A).length;if(I===0&&k(`no source files found under ${$} (build output and node_modules are skipped).`),U.length>0){for(let fe of U)L(`${fe} contains a NUL byte (U+0000), which cannot be stored.`);k(`push aborted: ${U.length} ${U.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let fe of C)L(f.dim(`skipped binary file ${fe}`));for(let fe of O)L(f.dim(`skipped ${fe} (holds credentials \u2014 never pushed)`));let F=await Z(`pushing ${I} file${I===1?"":"s"}`,()=>P(m,_,d,A,w.note,E));y(`pushed ${F.files} file${F.files===1?"":"s"} \u2192 ${F.slug} rev ${F.rev} (source only, nothing deployed).`);let ae=await xr(new H({baseUrl:m,token:_}),F.slug);ae&&ae.entriesAdded>0&&y(`${ae.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),y(`next: turbobase apps deploy ${F.slug}`)}),s.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let h=await Id(),{baseUrl:w,token:$}=await G(d.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await Z(`planning against ${d.to??w}`,()=>v.configPlan(h))}catch(_){k(`plan failed: ${_ instanceof Error?_.message:String(_)}`)}bP(m,d.to??w)}),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).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let h=await Id(),{baseUrl:w,token:$}=await G(d.baseUrl),v=h.tenant??yP(w),m=np(d.confirm,v);m.ok||k(`promote refused (fail-closed): ${m.reason}`);let _=new H({baseUrl:w,token:$});try{let E=await Z(`promoting ${d.from} \u2192 ${d.to} (${v})`,()=>_.configApply(h,{prune:d.prune}));if(Ee()){let C=[`${f.bold(`${d.from} \u2192 ${d.to}`)} ${f.dim(v??"")}`,`${Ht.add(String(E.applied.add))} ${Ht.change(String(E.applied.change))} ${Ht.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&C.push(f.dim(`${E.backfillsQueued.length} backfill(s) queued`)),y(Kt("Promoted",C))}else y(`promoted ${d.from} \u2192 ${d.to} (${v}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""));let A=E.skippedDestroys??[];if(A.length>0){L(`${A.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let C of A)L(` ${C.kind} ${C.id}`);L("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof Q&&E.status===403&&k("promote forbidden (403) \u2014 the stored PAT is not for an admin."),k(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),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,h)=>{let w=Ad(h.reporter),$=se(process.cwd(),d),v=await wr($),m=Lu(v);w?y(qs(pP(d,m),w)):y(ju(d,m,{warn:f.yellow,ok:f.green,dim:f.dim})),h.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(d,h)=>{let w=Ad(h.reporter),$=await Ru(se(process.cwd(),d));if(h.against){h.against!=="sandbox"&&k(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await xu(sa($))}catch(_){k(_ instanceof Error?_.message:String(_))}return}h.fixture||k("replay needs a --fixture <file> (offline) or --against sandbox (online).");let v;try{v=await Tu(se(process.cwd(),h.fixture))}catch(_){k(`could not read fixture ${h.fixture}: ${_ instanceof Error?_.message:String(_)}`)}let m=await $u($,v,h.fixture,{resolveDir:Mt(se(process.cwd(),d))});if(w){let _=hP(m);y(qs(_,w)),Ri(_.cases.some(E=>E.status==="failed")?1:0)}y(Eu(m,!!h.trace)),Ri(m.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:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w});try{await Fu($,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:y})}catch(v){v instanceof Q&&v.status===403&&k("forbidden (403) \u2014 binding --retry requires an admin PAT."),v instanceof Q&&v.status===409&&k("binding is not retryable (only divergent/blocked bindings can be retried)."),k(`ext binding failed: ${v instanceof Error?v.message:String(v)}`)}});let Bt=s.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");Bt.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 Cp(d)}),Bt.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,h)=>{await Op(d??[],h)}),Bt.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{await Np(d,h)}),Bt.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,h)=>{await Lp(d,h)}),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,h)=>{let w=d.lastIndexOf("@"),$=w>0?d.slice(0,w):d,v=w>0?d.slice(w+1):void 0,m=Qi();m||k(`marketplace not configured \u2014 set ${In} and ${Cs}.
|
|
3680
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let _=ea(m.registryUrl);_&&k(_);let{baseUrl:E,token:A}=await G(h.baseUrl),C=new gr(m),O;try{O=await Z(`fetching ${d}`,()=>C.fetchBundle($,v))}catch(fe){k(`marketplace fetch failed for ${d}: ${fe instanceof Error?fe.message:String(fe)}`)}let U=$s(O.manifest),I=null;if(U.length>0){if(!h.connection){let fe=U.map(An=>An.source_system).join(", ");k(`${O.name}@${O.version} declares a connection input (source: ${fe}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}I=h.connection}let F=fP(O.bundle,O.name,O.kind),ae=new H({baseUrl:E,token:A});try{let fe=await Z(`installing ${O.name}@${O.version}`,()=>ae.deploy({...F,provenance:"marketplace",...I?{connectionId:I}:{}}));y(`installed ${O.name}@${O.version} \u2192 ${fe.id} (status=${fe.status}, ${fe.outcome})`+(I?` bound to connection ${I}.`:"."))}catch(fe){fe instanceof Q&&fe.status===403&&k("install forbidden (403) \u2014 the stored PAT is not for an admin."),k(`install failed: ${fe instanceof Error?fe.message:String(fe)}`)}}),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,h)=>{let w=Qi();w||k(`marketplace not configured \u2014 set ${In} and ${Cs}.
|
|
3681
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let $=ea(w.registryUrl);$&&k($);let v=se(process.cwd(),d),m=await wr(v),_=/\bdefineConduit\s*[<(]/.test(m)?"conduit":"hook",E={};if(h.manifest){let O=se(process.cwd(),h.manifest),U;try{U=await oe.readFile(O,"utf8")}catch{k(`manifest not found at ${h.manifest}.`)}let I;try{I=JSON.parse(U)}catch{k(`manifest is not valid JSON: ${h.manifest}.`)}(typeof I!="object"||I===null||Array.isArray(I))&&k("manifest must be a JSON object."),E=I}try{Ni(E,m)}catch(O){O instanceof Ft&&k(O.message),k(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let A=new gr(w);try{await Z(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:_,bundle:m,manifest:E}))}catch(O){O instanceof Q&&O.status===403&&k("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),O instanceof Q&&O.status===409&&k(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),k(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let C=$s(E);y(`published ${h.name}@${h.pkgVersion} (kind=${_}) to the marketplace.`),C.length>0&&y(` declares ${C.length} connection input(s): ${C.map(O=>O.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 h=await pt(d.baseUrl).catch(()=>null),w=ua({baseUrl:h?.baseUrl,token:h?.token}),$=0,v=0,m=0;for(let _ of w){let E=se(process.cwd(),_.path),A=await oy(E,_);A==="wrote"?($+=1,y(` wrote ${_.path}`)):A==="merged"?(m+=1,y(` merged ${_.path} (added the .mcp.json rule)`)):(v+=1,y(` skipped ${_.path} (exists)`))}y(`
|
|
3682
|
+
project init: ${$} written, ${m} merged, ${v} skipped.`)}),r.command("ci").description(`Write the reusable release-deploy GitHub Action to ${da} (non-destructive).`).action(async()=>{let d=Gu(),h=0,w=0;for(let $ of d){let v=se(process.cwd(),$.path);await En(v,$.content,$.executable)==="wrote"?(h+=1,y(` wrote ${$.path}`)):(w+=1,y(` skipped ${$.path} (exists)`))}y(`
|
|
3683
|
+
project ci: ${h} written, ${w} skipped.`),h>0&&(y(`
|
|
3684
|
+
Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),y("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),y("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:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w}),v;try{v=await $.catalogRecords()}catch(C){C instanceof Q&&(C.status===401||C.status===403)&&k("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),k(`catalog fetch failed: ${C instanceof Error?C.message:String(C)}`)}if(v.length===0){y("no records in the instance catalog \u2014 nothing to generate.");return}let m=se(process.cwd(),d.out),_=Au(v,{event:d.event}),E=0,A=0;for(let{recordType:C,fixture:O}of _){let U=Qe(m,`${C}.json`),I=`${JSON.stringify(O,null,2)}
|
|
3685
|
+
`;d.force?(await oe.mkdir(Mt(U),{recursive:!0}),await oe.writeFile(U,I,{mode:420}),E+=1,y(` wrote ${d.out}/${C}.json`)):await En(U,I)==="wrote"?(E+=1,y(` wrote ${d.out}/${C}.json`)):(A+=1,y(` skipped ${d.out}/${C}.json (exists \u2014 use --force to overwrite)`))}y(`
|
|
3686
|
+
samples init: ${E} written, ${A} skipped.`)});let St=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),vs=d=>[d.name??f.dim(d.id.slice(0,8)),d.status==="active"?f.green("active"):d.status==="proposed"?f.yellow("proposed"):f.dim("inactive"),d.decision==="deny"?f.red(d.decision):d.decision==="require_confirm"?f.yellow(d.decision):f.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??f.dim("any"),d.when||f.dim("(always)"),d.reason??""],Pi=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];St.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w}),v;try{v=await $.guardrailsList()}catch(m){J(m,"extensions:deploy","list guardrails"),k(`list guardrails failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(v,null,2));if(v.length===0)return y(`no write guardrails \u2014 every record the admin entitlement allows is writable.
|
|
3687
|
+
`+f.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(ht(v.map(vs),{head:Pi})),y(f.dim(" first match wins; lower PRIO is evaluated first."))}),St.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await v.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(_){J(_,"extensions:deploy","create a guardrail"),k(`create guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} created${m.status==="active"?"":f.dim(` (${m.status} \u2014 activate it to take effect)`)}`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.actor?` actor=${m.actor}`:""}${m.when?` where ${m.when}`:""} @prio ${m.priority}`)),y(f.dim(` verify with: turbobase guardrails test --source ${m.source==="*"?"<source>":m.source} --record <record>`))}),St.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&k("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await v.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(_){J(_,"extensions:deploy","edit a guardrail"),k(`edit guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} updated`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.when?` where ${m.when}`:""} @prio ${m.priority}`))});for(let[d,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])St.command(`${d} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async($,v)=>{let{baseUrl:m,token:_}=await G(v.baseUrl),E=new H({baseUrl:m,token:_});try{await E.guardrailUpdate($,{status:h})}catch(A){J(A,"extensions:deploy",`${d} a guardrail`),k(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail ${f.bold($)} ${w}`),h==="inactive"&&y(f.dim(" writes it was gating now fall through to the other rules."))});St.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$});try{await v.guardrailDelete(d)}catch(m){J(m,"extensions:deploy","delete a guardrail"),k(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(d)} deleted`)}),St.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await v.guardrailPostureGet()}catch(C){J(C,"extensions:deploy","read the guardrail posture"),k(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}y(`guardrail posture: ${f.bold(m(A.mode))}`),y(f.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"&&k("posture must be 'allow' or 'deny'.");let E;try{E=await v.guardrailPostureSet(_)}catch(A){J(A,"extensions:deploy","set the guardrail posture"),k(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail posture set to ${f.bold(m(E.mode))}`),E.mode==="deny"&&y(f.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),St.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let h;if(d.fields)try{h=JSON.parse(d.fields)}catch(E){k(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token:$}=await G(d.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await v.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){J(E,"extensions:deploy","test guardrails"),k(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return y(JSON.stringify(m,null,2));let _=`${d.source}/${m.op??d.record}`;m.degraded?(y(`${f.red("\u2717")} ${_} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(f.dim(` ${m.reason}`))):m.allowed?y(`${f.green("\u2713")} ${_} \u2014 ${m.decision}`+(m.blockedBy?f.dim(` (rule ${m.blockedBy})`):f.dim(" (no rule matched)"))):(y(`${f.red("\u2717")} ${_} \u2014 ${m.decision} by ${f.bold(m.blockedBy??"?")} at the ${m.phase} gate`),m.message&&y(f.dim(` ${m.message}`))),m.decision==="require_confirm"&&y(f.yellow(" this write is HELD for operator approval, not refused.")),m.allowed||(process.exitCode=1)});let pr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),ks=(d,h={})=>{let w=`${f.bold(d.table)} ${f.dim(d.displayName)}`;y(d.exists===!1?`${w} ${f.dim("(new)")}`:w);for(let $ of d.fields){let v=[$.required?"required":null].filter(Boolean).join(", "),m=h.showClaimants&&$.claimedBy?.length?` ${f.dim(`\u2190 ${$.claimedBy.join(", ")}`)}`:"";y(` ${$.column.padEnd(28)} ${$.type}${v?` (${v})`:""}${m}`)}h.showClaimants&&d.claimants.length>1&&y(f.dim(` claimed by ${d.claimants.join(", ")}`))};function Ss(d){if(d instanceof Q&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}k(`tables: ${d instanceof Error?d.message:String(d)}`)}let Dd=async d=>{let h=Qe(se(process.cwd(),d),"public","turbobase.json"),w=await oe.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let $;try{$=JSON.parse(w)}catch(m){k(`${h} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let v=$.tables;return v===void 0?{tables:[],manifestPath:h}:(Array.isArray(v)||k(`${h}: "tables" must be an array.`),{tables:v,manifestPath:h})};pr.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w}),v;try{v=await $.tablesList()}catch(m){J(m,"extensions:deploy","list tables"),k(`list tables failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(v,null,2));if(v.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(ht(v.map(m=>[m.table,m.displayName,String(m.fields.length),m.status,m.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),pr.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,h)=>{let w=await Dd(d??".");if(w||k(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:$,token:v}=await G(h.baseUrl),m=new H({baseUrl:$,token:v}),_;try{_=await Z("planning tables",()=>m.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch(E){J(E,"extensions:deploy","plan tables"),Ss(E)}y(`claiming as ${f.bold(_.claimedBy)}`);for(let E of _.tables)ks(E,{showClaimants:!0});y(""),y(f.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),pr.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,h)=>{let w=await Dd(d??".");if(w||k(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:$,token:v}=await G(h.baseUrl),m=new H({baseUrl:$,token:v}),_;try{_=await Z("applying tables",()=>m.tablesApply({claimedBy:h.as,tables:w.tables}))}catch(E){J(E,"extensions:deploy","apply tables"),Ss(E)}for(let E of _.tables)ks(E,{showClaimants:!0});y(`applied ${_.tables.length} table${_.tables.length===1?"":"s"} as ${_.claimedBy}.`)}),pr.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let w=h.field.map(E=>{let[A,C,O]=E.split(":");return(!A||!C)&&k(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&k(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:$,token:v}=await G(h.baseUrl),m=new H({baseUrl:$,token:v}),_;try{_=await Z(`creating cr_${d}`,()=>m.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){J(E,"extensions:deploy","create a table"),Ss(E)}for(let E of _.tables)ks(E);y(""),y(f.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),pr.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.confirm!==d&&k(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await Z(`dropping cr_${d}`,()=>v.tablesDrop(d,h.confirm))}catch(_){J(_,"extensions:deploy","drop a table"),k(`drop failed: ${_ instanceof Error?_.message:String(_)}`)}if(!m.removed)return y(`no table named "${d}" on this instance \u2014 nothing dropped.`);y(`dropped ${m.table} and every row in it.`)});let Ai=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ai.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let h=Cd(),w;try{w=await th(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch($){$ instanceof Rr&&k($.message),k(`sandbox create failed: ${$ instanceof Error?$.message:String($)}`)}y(`sandbox ${w.name} ready.`),y(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),y(` url: ${w.url}`),y(` expires: ${w.expiresAt}`)}),Ai.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let h=Cd();await Oa(h).catch(()=>[]);let w;try{w=await nh(h,d)}catch($){k(`sandbox destroy failed: ${$ instanceof Error?$.message:String($)}`)}w||k(`no sandbox named '${d}'.`),y(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Ai.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Cd(),h=await Oa(d).catch(()=>[]),w=await to(),{active:$}=Ca(w);if($.length===0)y("no active sandboxes.");else{for(let v of $)y(` ${v.name} from=${v.fromTenant} expires=${v.expiresAt} ${v.url}`);y(`
|
|
3688
|
+
${$.length} active sandbox(es).`)}h.length>0&&y(`(reaped ${h.length} expired sandbox(es).)`)}),s.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",Ks).action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w}),v;try{v=await Z("exporting instance config",()=>$.configExport())}catch(E){E instanceof Q&&(E.status===401||E.status===403)&&k("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),k(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let m=typeof v.serialized=="string"?v.serialized:`${JSON.stringify(v.manifest??v,null,2)}
|
|
3689
|
+
`,_=se(process.cwd(),d.out,kr);await oe.mkdir(Mt(_),{recursive:!0}),await oe.writeFile(_,m,"utf8"),y(`wrote ${d.out}/${kr} (${m.split(`
|
|
3690
|
+
`).length} lines).`)});let Ud=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),ly=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Md=()=>process.env.TURBOBASE_HOME?.trim()||Qe(sP(),".turbobase"),cy=()=>"1.17.0",_s=async()=>Promise.all(ly.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Ud.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await _s();for(let h of d)y(`${h.present?Se.success("installed"):Se.warn("missing")} ${f.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
|
|
3691
|
+
run \`${_r} ext extras install\` to fetch them into ${Md()}.`)}),Ud.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await _s();if(d.every(A=>A.present)){y(Se.success("extras already installed \u2014 nothing to do."));return}let h=Md();await oe.mkdir(h,{recursive:!0});let w=d.filter(A=>!A.present).map(A=>A.name),$=Ta(process.platform,process.arch),v=async(A,C)=>{let{code:O,stderr:U}=await ws("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&k(`extras install failed while installing ${C} (npm exited ${O}).
|
|
3599
3692
|
${U.trim()}
|
|
3600
|
-
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},m=
|
|
3601
|
-
${Object.keys(m.owned).length} owned file(s), ${Object.keys(m.context).length} context file(s), ${
|
|
3693
|
+
These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},m=w.filter(A=>A!=="isolated-vm");if(m.length>0){let A=m.map(C=>`${C}@${$a[C]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await v(A,m.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${$a["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await v(["--ignore-scripts",A],"isolated-vm"),Wp.includes($)){let O=`${xa}@${cy()}`;y(`fetching ${O} (no upstream binary for ${$}) \u2026`);let{code:U}=await ws("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);U!==0&&y(Se.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await Jp({home:h});C.length>0&&y(` ${Se.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${$}`)}let _=await _s(),E=_.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){y(Se.warn(`no prebuilt isolated-vm for ${$} / Node ${process.versions.node} (${Ra()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await ws("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(_=await _s(),E=_.filter(C=>!C.present).map(C=>C.name))}E.length>0&&k(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${$} / Node ${process.versions.node} (${Ra()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),y(Se.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Pn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Pn.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||k(`--target must be 'auto' or 'approved' (got '${d.target}').`);let w=await wP(se(process.cwd(),d.project??".")),$=Object.keys(w).length;!d.solution&&$===0&&k("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let m=(d.ref?await Od(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Od(["rev-parse","HEAD"]),_=d.gitRepo??process.env.GITHUB_REPOSITORY??await Od(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await G(d.baseUrl),U=new H({baseUrl:C,token:O}),I;try{I=await U.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:$>0?w:null,gitRepo:_,gitRef:E,gitSha:m,prUrl:A})}catch(F){J(F,"releases:write","release deploy"),F instanceof Q&&F.status===404&&k("solution_not_found \u2014 no solution with that id."),k(`release deploy failed: ${F instanceof Error?F.message:String(F)}`)}y(`release ${I.releaseId} enqueued \u2192 taskId=${I.taskId} (target=${h}`+($>0?`, uploaded ${$} bundle file(s)`:", live-fetch")+")."),d.follow&&await ga(()=>U.releaseStatus(I.releaseId),`release ${I.releaseId}`,d.intervalMs)}),Pn.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await v.releaseFiles(d)}catch(A){A instanceof Q&&A.status===404&&k(`release ${d} not found.`),A instanceof Q&&A.status===409&&k(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),J(A,"releases:write","pull a release"),k(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let _=se(process.cwd(),h.dir),E=0;for(let[A,C]of[["owned",m.owned],["context",m.context]])for(let[O,U]of Object.entries(C)){let I=Qe(_,A,O);await oe.mkdir(Mt(I),{recursive:!0}),await oe.writeFile(I,U,"utf8"),E++}await oe.writeFile(Qe(_,".turbobase-release.json"),JSON.stringify({releaseId:m.releaseId,version:m.version,contentDigest:m.contentDigest},null,2),"utf8"),y(`pulled release ${m.releaseId} (${m.status}) \u2192 ${_}
|
|
3694
|
+
${Object.keys(m.owned).length} owned file(s), ${Object.keys(m.context).length} context file(s), ${E} total
|
|
3602
3695
|
`+(m.logTail?`
|
|
3603
3696
|
the failure these bytes produced:
|
|
3604
3697
|
${m.logTail.trim()}
|
|
3605
3698
|
`:"")+`
|
|
3606
3699
|
edit the files under owned/, then:
|
|
3607
|
-
turbobase release push ${m.releaseId} --dir ${h.dir}`)}),
|
|
3700
|
+
turbobase release push ${m.releaseId} --dir ${h.dir}`)}),Pn.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(d,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m=se(process.cwd(),h.dir),_;try{_=await v.releaseFiles(d)}catch(I){I instanceof Q&&I.status===404&&k(`release ${d} not found.`),J(I,"releases:write","push a release"),k(`release push failed: ${I instanceof Error?I.message:String(I)}`)}let E=async(I,F)=>{try{return await oe.readFile(Qe(m,I,F),"utf8")}catch{return null}},A=[];for(let[I,F]of Object.entries(_.context)){let ae=await E("context",I);ae!==null&&ae!==F&&A.push(I)}A.length>0&&k(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
|
|
3608
3701
|
`+A.map(I=>` context/${I}`).join(`
|
|
3609
|
-
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let
|
|
3702
|
+
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={..._.context},O=0;for(let[I,F]of Object.entries(_.owned)){let ae=await E("owned",I);C[I]=ae??F,ae!==null&&ae!==F&&O++}O===0&&y("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let U=h.target==="approved"?"approved":"auto";try{let I=await v.releasePush(d,{files:C,target:U,...h.approvedBy?{approvedBy:h.approvedBy}:{}});y(`pushed ${Object.keys(C).length} file(s) (${O} edited) \u2192 release ${I.releaseId} (task ${I.taskId}).
|
|
3610
3703
|
follow it with:
|
|
3611
|
-
turbobase release status ${I.releaseId} --follow`)}catch(I){I instanceof
|
|
3612
|
-
${
|
|
3613
|
-
`)),t&&void 0,e}function
|
|
3614
|
-
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return
|
|
3615
|
-
${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
|
|
3704
|
+
turbobase release status ${I.releaseId} --follow`)}catch(I){I instanceof Q&&I.status===403&&k("an approved target needs --approved-by (the deploy gate fails closed)."),I instanceof Q&&I.status===409&&k("that solution already has an active release \u2014 roll it back or wait for it."),J(I,"releases:write","push a release"),k(`release push failed: ${I instanceof Error?I.message:String(I)}`)}}),Pn.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$});if(h.follow){await ga(()=>v.releaseStatus(d),`release ${d}`,h.intervalMs);return}let m;try{m=await v.releaseStatus(d)}catch(_){J(_,"releases:write","release status"),_ instanceof Q&&_.status===404&&k(`release ${d} not found.`),k(`release status failed: ${_ instanceof Error?_.message:String(_)}`)}y(`release ${d}: status=${m.releaseStatus??"?"} stage=${m.stage} ${m.percent}%`+(m.runStatus?` (${m.runStatus})`:"")),m.outputTail&&y(m.outputTail.replace(/\n+$/,""))}),Pn.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await G(h.baseUrl),v=new H({baseUrl:w,token:$}),m;try{m=await v.releaseRollback(d)}catch(_){J(_,"releases:write","release rollback"),_ instanceof Q&&_.status===404&&k(`release ${d} not found.`),_ instanceof Q&&_.status===409&&k(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),k(`release rollback failed: ${_ instanceof Error?_.message:String(_)}`)}y(`release ${m.releaseId} rolled back \u2192 status=${m.release?.status??"rolled_back"}.`)}),Pn.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w}),v;try{v=await $.releaseList()}catch(m){J(m,"releases:write","release list"),k(`release list failed: ${m instanceof Error?m.message:String(m)}`)}if(v.length===0){y("no releases.");return}if(Ee())y(ht(v.map(m=>[m.id,Nn(m.status),m.target,m.backend,m.solutionTitles?.length?m.solutionTitles.map(_=>`"${_}"`).join(", "):f.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let m of v){let _=m.solutionTitles?.length?` "${m.solutionTitles.join('", "')}"`:"";y(` ${m.id} ${m.status.padEnd(11)} target=${m.target} backend=${m.backend}${_}`)}y(`
|
|
3705
|
+
${v.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:h,token:w}=await G(d.baseUrl),$=new H({baseUrl:h,token:w}),v=d.limit?Number(d.limit):void 0,m=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await Bu($,d.conduit,{...d.follow?{follow:!0}:{},...v!==void 0?{limit:v}:{},...m!==void 0?{intervalMs:m}:{},sink:y})}catch(_){k(`logs --conduit failed: ${_ instanceof Error?_.message:String(_)}`)}return}if(d.extension){try{let _=await $.logs(d.extension,v);_.length===0&&y(`no logs for ${d.extension}.`);for(let E of _)y(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(_){k(`logs --extension failed: ${_ instanceof Error?_.message:String(_)}`)}return}try{await Hu($,{...d.subsystem?{subsystem:d.subsystem}:{},...d.severity?{severity:d.severity}:{},...d.code?{code:d.code}:{},...d.since?{since:d.since}:{},...d.correlationId?{correlationId:d.correlationId}:{},...d.follow?{follow:!0}:{},...d.json?{json:!0}:{},...v!==void 0?{limit:v}:{},...m!==void 0?{intervalMs:m}:{},sink:y})}catch(_){k(`logs failed: ${_ instanceof Error?_.message:String(_)}`)}}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(sy(),ry));await h({baseUrl:d.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
|
|
3706
|
+
`)),t&&void 0,e}function fP(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 mP(t){let e=Qe(se(process.cwd(),t),"public","turbobase.json"),n=await oe.readFile(e,"utf8").catch(()=>null);if(n===null)return null;let r;try{r=JSON.parse(n)}catch(s){k(`${e} is not valid JSON: ${s instanceof Error?s.message:String(s)}`)}return(typeof r!="object"||r===null||Array.isArray(r))&&k(`${e} must be a JSON object.`),{manifest:r,manifestPath:e}}async function gP(){let t=se(process.cwd(),Ks,kr),e;try{e=await oe.readFile(t,"utf8")}catch{k(`no config found \u2014 this project authors none (no ${Gs}/, ${Ws}/, ${Vt} or ${Gt}) and there is no ${Ks}/${kr}.
|
|
3707
|
+
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return tp(e)}catch(n){k(`bundle is invalid: ${n instanceof Error?n.message:String(n)}`)}}async function Id(){let t=process.cwd();if(!await op(t))return gP();let e;try{e=await ip(t,{inline:ta})}catch(n){k(`could not build the config bundle from this project: ${n instanceof Error?n.message:String(n)}`)}for(let n of e.unparsed)L(`${n.file}: ${n.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&k(`${e.unparsed.length} extension file(s) could not be identified. Every hook/conduit needs a literal \`id:\`, \`recordType:\` and \`event:\`/\`on:\` \u2014 run \`turbobase ext lint <file>\` on each.`),e.manifest}function bP(t,e){y(`plan against ${e}:`);for(let n of t.add)y(` ${Ht.add(`${n.kind} ${n.id}`)}`);for(let n of t.change)y(` ${Ht.change(`${n.kind} ${n.id}`)}`);for(let n of t.destroy)y(` ${Ht.destroy(`${n.kind} ${n.id}`)}`);y(`
|
|
3708
|
+
${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 yP(t){try{let n=new URL(t).hostname.split(".")[0];return n&&n!=="localhost"?n:void 0}catch{return}}function ws(t,e,n){return new Promise(r=>{let s=Ld(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 Cd(){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 ws("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 ws("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 wP(t){let e=se(t,"src"),n={},r=async s=>{let o;try{o=await oe.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=Ei(e,a).split(Nd).join("/");n[l]=await oe.readFile(a,"utf8")}}};return await r(e),n}function Od(t){return new Promise(e=>{let n=Ld("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 vP=!1;vP&&jd().parseAsync(process.argv).catch(t=>k(t instanceof Error?t.message:String(t)));jd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
|
|
3616
3709
|
`),process.exit(1)});
|